2017-06-11 5 views
0

メニューナビアイテムのナビゲーションドロワーがあります。ここでは、1つのアイテムについて定義します。クリックすると、新しいアクティビティが開きます。このアクティビティの中で、スタートフラッグゲームクイズのレイアウトをデザインします。プレイゲームボタンをクリックすると、クリックユーザーを待つことなく、終わり。 "PlayGame"レイアウトの中で、私はフラグのためのimageViewと回答のための4つのボタンを定義します。フラグの名前と回答は外部データベースから来ます。私はアプリをデバッグすると、countDownTimerはnull量を実現する、すべてが正しかった、ちょうどタイマーが使用を待つことはなく、クイズを再生することはとても速いです。Androidクイズゲームでユーザーが回答をクリックしてすぐに実行できるようにTimerを待たずに

これは私のデータベースです。

WorldCountryDatabase

public class WorldCountryDatabase extends SQLiteOpenHelper { 

private static final String TAG = "databaseHelper"; 
private static final String DB_NAME = "worldCountries.db"; 
private static final int DB_VERSION = 1; 
private static final String TABLE_NAME = "country"; 
private static String DB_PATH = ""; 
private Context mContext; 
private SQLiteDatabase database; 

public WorldCountryDatabase(Context context) { 
    super(context, DB_NAME, null, DB_VERSION); 

    DB_PATH = context.getDatabasePath(DB_NAME).getPath(); 

    File file = new File(DB_PATH + "worldCountries.db"); 
    if (file.exists()) 

     openDataBase(); 

    this.mContext = context; 


} 

public void createDatabase() { 

    boolean dbExist = checkDatabase(); 

    if (dbExist) { 

     Log.d("MIN1", "Database already Exist"); 

    } else { 
     this.getReadableDatabase(); 
    } 
    try { 
     copyDataBase(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     Log.i("MIN2", e.getMessage()); 

    } 


} 

private boolean checkDatabase() { 
    SQLiteDatabase checkDB = null; 

    try { 


     String myPath = DB_PATH + DB_NAME; 
     checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); 

    } catch (SQLiteException e) { 
     e.printStackTrace(); 
     Log.d("MIN3", e.getMessage()); 

    } 
    if (checkDB != null) { 
     checkDB.close(); 
    } 
    return checkDB != null; 
} 

public synchronized void close() { 
    if (database != null) { 
     database.close(); 
     SQLiteDatabase.releaseMemory(); 
    } 
    super.close(); 

} 


private void copyDataBase() throws IOException { 

    try { 


     InputStream in = mContext.getAssets().open(DB_NAME); 
     String outFileName = DB_PATH + DB_NAME; 
     OutputStream out = new FileOutputStream(outFileName); 
     byte[] buffer = new byte[1024]; 
     int length; 

     while ((length = in.read(buffer)) > 0) { 
      out.write(buffer, 0, length); 
     } 


     out.flush(); 
     out.close(); 
     in.close(); 

     Log.d("MIN4", "Database copy"); 


    } catch (SQLiteException e) { 
     Log.d("MIN5", e.getMessage()); 

    } 
} 

public Cursor QueryData(String query) { 
    return database.rawQuery(query, null); 
} 


@Override 
public void onCreate(SQLiteDatabase db) { 

    Log.d("MIN6", "onCreate"); 



} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 


    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); 
    onCreate(db); 

    Log.v("LOG_TAG", "Upgrading Database from version" + oldVersion + "To" + newVersion + 
      "Which will destroy all oldest data"); 


    if (newVersion > oldVersion) { 
     try { 
      copyDataBase(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 


} 

public void openDataBase() { 

    String myPath = DB_PATH + DB_NAME; 
    database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); 
    Log.d("MIN7", "Opened database"); 


} 

// CRUD Table 
public List<Questions> getAllQuestions() { 

    List<Questions> questionsList = new ArrayList<>(); 
    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor c; 

    try { 
     c = db.rawQuery("SELECT * FROM country ORDER BY Random()", null); 
     if (c == null) return null; 
     c.moveToFirst(); 
     do { 
      int Id = c.getInt(c.getColumnIndex("id")); 
      String Image = c.getString(c.getColumnIndex("Image")); 
      String AnswerA = c.getString(c.getColumnIndex("AnswerA")); 
      String AnswerB = c.getString(c.getColumnIndex("AnswerB")); 
      String AnswerC = c.getString(c.getColumnIndex("AnswerC")); 
      String AnswerD = c.getString(c.getColumnIndex("AnswerD")); 
      String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer")); 

      Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer); 
      questionsList.add(question); 


       } while (c.moveToNext()); 
       c.close(); 


    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    database.close(); 
    return questionsList; 
} 



// Insert Score to Ranking table. 
public void insertScore(double score) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    ContentValues content = new ContentValues(); 
    content.put("Score", score); 
    db.insert("Ranking", null, content); 
} 

// Get score and sort Ranking. 
public List<Ranking> getRanking() { 

    List<Ranking> rankingList = new ArrayList<>(); 
    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor c; 
    try { 
     c = db.rawQuery("SELECT * FROM country ORDER BY Score DESC;", null); 
     if (c == null) return null; 
     c.moveToFirst(); 
     do { 

      int ID = c.getInt(c.getColumnIndex("id")); 
      int Score = c.getInt(c.getColumnIndex("Score")); 

      Ranking ranking = new Ranking(ID, Score); 
      rankingList.add(ranking); 


     } while (c.moveToNext()); 
     c.close(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    db.close(); 
    return rankingList; 
} 



public int getPlayCount(int level) 
{ 
    int result = 0; 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor c; 
    try{ 
     c = db.rawQuery("SELECT PlayCount FROM UserPlayCount WHERE Level="+level+";",null); 
     if(c == null) return 0; 
     c.moveToNext(); 
     do{ 
      result = c.getInt(c.getColumnIndex("PlayCount")); 
     }while(c.moveToNext()); 
     c.close(); 
    }catch (Exception ex) 
    { 
     ex.printStackTrace(); 
    } 
    return result; 
} 

public void updatePlayCount(int level,int playCount) 
{ 
    String query = String.format("UPDATE UserPlayCount Set PlayCount = %d WHERE Level = %d",playCount,level); 
    database.execSQL(query); 
} 

これは私のChoicGameクラスです。

ChoiceGame

public class ChoiceGame extends AppCompatActivity { 

TextView modeText; 
SeekBar seekBarMode; 
Button playGame, scoreGame; 
WorldCountryDatabase worldCountryDatabase; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_game_flag); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    if (getSupportActionBar() != null) 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    getSupportActionBar().setHomeButtonEnabled(true); 


    modeText = (TextView) findViewById(R.id.modeText); 
    seekBarMode = (SeekBar) findViewById(R.id.seekBarMode); 
    playGame = (Button) findViewById(R.id.playGame); 
    scoreGame = (Button) findViewById(R.id.scoreGame); 

    worldCountryDatabase = new WorldCountryDatabase(this); 
    try { 
     worldCountryDatabase.createDatabase(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 


    //Event 
    seekBarMode.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 
     @Override 
     public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 
      if (progress == 0) 
       modeText.setText(Common.MODE.EASY.toString()); 
      else if (progress == 1) 
       modeText.setText(Common.MODE.MEDIUM.toString()); 
      else if (progress == 2) 
       modeText.setText(Common.MODE.HARD.toString()); 
      else if (progress == 3) 
       modeText.setText(Common.MODE.HARDEST.toString()); 
     } 

     @Override 
     public void onStartTrackingTouch(SeekBar seekBar) { 

     } 

     @Override 
     public void onStopTrackingTouch(SeekBar seekBar) { 

     } 
    }); 
    playGame.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(getApplicationContext(), PlayGameCountry.class); 
      intent.putExtra("Mode", getPlayMode()); // Send Mode to Playing page 
      startActivity(intent); 
      finish(); 
     } 
    }); 

    scoreGame.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(getApplicationContext(), ScoreGame.class); 
      startActivity(intent); 
      finish(); 
     } 
    }); 
} 



private String getPlayMode() { 
    if (seekBarMode.getProgress() == 0) 
     return Common.MODE.EASY.toString(); 
    else if (seekBarMode.getProgress() == 1) 
     return Common.MODE.MEDIUM.toString(); 
    else if (seekBarMode.getProgress() == 2) 
     return Common.MODE.HARD.toString(); 
    else 
     return Common.MODE.HARDEST.toString(); 
} 

}

、最後にこれが私のPlayingGameクラスです。まず

PlayingGmae

public class PlayGameCountry extends AppCompatActivity implements View.OnClickListener { 

final static long INTERVAL = 1; // 1 second 
final static long TIMEOUT = 7; // 1 second 

CountDownTimer countDownTimer; 
int progressValue = 0; 

int score = 0, index = 0, thisQuestion = 0, correctAnswer, totalQuestions; 
List<Questions> questionsList = new ArrayList<>(); 
String mode; 

ProgressBar progressBar; 
ImageView flagCountry; 
TextView scoreText, numberQuestion; 
Button answerA, answerB, answerC, answerD; 

WorldCountryDatabase worldCountryDatabase; 
ChoiceGame choiceGame; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_play_game_country); 

    // Get data from ChoiceGame 
    Bundle bundle = getIntent().getExtras(); 
    if (bundle != null) 

     mode = bundle.getString("Mode"); 


    worldCountryDatabase = new WorldCountryDatabase(this); 


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    if (getSupportActionBar() != null) { 
     getSupportActionBar().setHomeButtonEnabled(true); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    } 

    flagCountry = (ImageView) findViewById(R.id.flagQuiz); 
    scoreText = (TextView) findViewById(R.id.scoreText); 
    numberQuestion = (TextView) findViewById(R.id.trueAnswer); 

    answerA = (Button) findViewById(R.id.firstAnswer); 
    answerB = (Button) findViewById(R.id.secondAnswer); 
    answerC = (Button) findViewById(R.id.thirthAnswer); 
    answerD = (Button) findViewById(R.id.forthAnswer); 

    progressBar = (ProgressBar) findViewById(R.id.progressUser); 

    answerA.setOnClickListener(this); 
    answerB.setOnClickListener(this); 
    answerC.setOnClickListener(this); 
    answerD.setOnClickListener(this); 


} 

@Override 
protected void onResume() { 
    super.onResume(); 

    questionsList = this.getQuestionMode(mode); 
    assert questionsList != null; 
    totalQuestions = questionsList.size(); 

    countDownTimer = new CountDownTimer(INTERVAL, TIMEOUT) { 
     @Override 
     public void onTick(long millisUntilFinished) { 

      progressBar.setProgress(progressValue); 
      progressValue++; 
     } 

     @Override 
     public void onFinish() { 
      countDownTimer.cancel(); 
      showQuestion(++index); 

     } 
    }; 
    showQuestion(index); 
} 

private void showQuestion(int index) { 

    if (index < totalQuestions) { 
     thisQuestion++; 
     numberQuestion.setText(String.format("%d/%d", thisQuestion, totalQuestions)); 
     progressBar.setProgress(0); 
     progressValue = 0; 

     int ImageId = this.getResources().getIdentifier(questionsList.get(index).getImage().toLowerCase(), "drawable", getPackageName()); 
     flagCountry.setBackgroundResource(ImageId); 
     answerA.setText(questionsList.get(index).getAnswerA()); 
     answerB.setText(questionsList.get(index).getAnswerB()); 
     answerC.setText(questionsList.get(index).getAnswerC()); 
     answerD.setText(questionsList.get(index).getAnswerD()); 


     countDownTimer.start(); 
    } else { 
     Intent scoreIntent = new Intent(getApplicationContext(), Done.class); 
     Bundle bundle = new Bundle(); 
     bundle.putInt("SCORE", score); 
     bundle.putInt("TOTAL", totalQuestions); 
     bundle.putInt("CORRECT", correctAnswer); 
     scoreIntent.putExtras(bundle); 
     startActivity(scoreIntent); 
     finish(); 
    } 
} 

@Override 
public void onClick(View v) { 

    countDownTimer.cancel(); 

    if (index < totalQuestions) { 

     Button clickedButton = (Button) v; 

     if (clickedButton.getText().equals(questionsList.get(index).getCorrectAnswer())) 

     { 

      score += 10; // increase score 

      correctAnswer++; //increase correct answer 

      showQuestion(++index); 

     } else 

      showQuestion(++index); // If choose right , just go to next question 


     scoreText.setText(String.format("%d", score)); 
    } 
} 

private List<Questions> getQuestionMode(String mode) { 

    List<Questions> questionList = new ArrayList<>(); 
    worldCountryDatabase = new WorldCountryDatabase(this); 

    try { 
     worldCountryDatabase.createDatabase(); 
     worldCountryDatabase.openDataBase(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    int limit = 0; 
    if (mode.equals(Common.MODE.EASY.toString())) 
     limit = 30; 
    else if (mode.equals(Common.MODE.MEDIUM.toString())) 
     limit = 50; 
    else if (mode.equals(Common.MODE.HARD.toString())) 
     limit = 100; 
    else if (mode.equals(Common.MODE.HARDEST.toString())) 
     limit = 200; 
    try { 

     Cursor cursor = worldCountryDatabase.QueryData(String.format("SELECT * FROM country ORDER BY Random() LIMIT %d", limit)); 

     if (cursor == null) return null; 
     if (cursor.moveToNext()) { 
      do { 


       int Id = cursor.getInt(cursor.getColumnIndex("id")); 
       String Image = cursor.getString(cursor.getColumnIndex("Image")); 
       String AnswerA = cursor.getString(cursor.getColumnIndex("AnswerA")); 
       String AnswerB = cursor.getString(cursor.getColumnIndex("AnswerB")); 
       String AnswerC = cursor.getString(cursor.getColumnIndex("AnswerC")); 
       String AnswerD = cursor.getString(cursor.getColumnIndex("AnswerD")); 
       String CorrectAnswer = cursor.getString(cursor.getColumnIndex("CorrectAnswer")); 

       Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer); 
       questionList.add(question); 

      } while (cursor.moveToNext()); 
      worldCountryDatabase.close(); 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return questionList; 
} 

}

、私はWorldCountryDatabaseの内側に "getQuestionMode" メソッドを定義するが、このアプリはPlayingCountryGameレイアウトやオープンScoreGameに行きませんクラス。私が "getQuestionMode"メソッドを内部に定義した後、PlayingCountryGameクラス。私は自分の問題を明確に伝えたい。

私を助けてください、良い友達。 ありがとうございました皆さん。

答えて

0

問題はコンストラクタと値だと思います。

https://developer.android.com/reference/android/os/CountDownTimer.html#CountDownTimer(long, long)

コンストラクタはミリ秒単位ではなく秒の時間を必要としています。 1秒から1000ミリ秒の変換が必要です。

final static long INTERVAL = 1000; // 1 second -> 1000 milliseconds 
final static long TIMEOUT = 7000; // 7 seconds -> 7000 milliseconds 

そして、パラメタの順序。

countDownTimer = new CountDownTimer(TIMEOUT, INTERVAL){ ... } 
+0

感謝親愛なる:あなたはコンストラクタがある7秒を待つ場合

。私はこれに気付かない。非常に多くのありがとう。:) –

関連する問題