Android CountDown Timer won't stop [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Ok so here is my problem. I am working on a trivia game that uses a question counter to display 10 questions and once that happens it calls the finalscore class. I have implemented a timer that resets for every question and if time runs up it proceeds to the next question. However if nothing is clicked on the final question it will keep looping back to the finalscore class even after starting a new game.
public class game extends Activity implements OnClickListener {
// int[] anArray;
int[] anArray2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int numberOfQuestionsDisplayedCounter = 0;
int nextOrFinishValue = 0;
int randomValueZeroToThree = 0;
int randomValue0to29 = 0;
boolean alreadyDisplayQuestion = false;
boolean validQuestionNumber = false;
boolean rightButton1 = false;
boolean rightButton2 = false;
boolean rightButton3 = false;
boolean rightButton4 = false;
String questionFromDatabase;
String answer1FromDatabase;
String answer2FromDatabase;
String answer3FromDatabase;
String answer4FromDatabase;
String displayedQuestionFromDatabase = "question ";
String displayedAnswer1FromDatabase = "answer1a ";
String displayedAnswer2FromDatabase = "answer2a ";
String displayedAnswer3FromDatabase = "answer3a ";
String displayedAnswer4FromDatabase = "answer4a ";
int categoryId = 0;
int questionId = 0;
int currentScore = 0;
private CountDownTimer mCountDown;
public void onCreate(Bundle savedInstanceState) {
int randomInt = 1;
super.onCreate(savedInstanceState);
categoryId = com.triviagame.Trivia_Game.categoryIdInMainMenu;
// System.out.println("categoryID =" + categoryId);
setContentView(R.layout.displayquestion);
// gathers question and answers from database
gatherInfoBeforePopulating(); // includes generating random number
// between getting info from database 1
// to 30
// displays question, answers, score
populateWithQuestionInfo(displayedQuestionFromDatabase,
displayedAnswer1FromDatabase, displayedAnswer2FromDatabase,
displayedAnswer3FromDatabase, displayedAnswer4FromDatabase,
nextOrFinishValue);
// Sets buttons and listers for the buttons with the 4 possible answers
View answer1button = findViewById(R.id.answer1button);
answer1button.setOnClickListener(this);
View answer2button = findViewById(R.id.answer2button);
answer2button.setOnClickListener(this);
View answer3button = findViewById(R.id.answer3button);
answer3button.setOnClickListener(this);
View answer4button = findViewById(R.id.answer4button);
answer4button.setOnClickListener(this);
final TextView myCounter = (TextView) findViewById(R.id.tv);
mCountDown = new CountDownTimer(21000, 1000) {
#Override
public void onFinish() {
questionCheck();
resetTimer();
}
#Override
public void onTick(long millisUntilFinished) {
myCounter.setText("Time left: "
+ String.valueOf(millisUntilFinished / 1000));
}
}.start();
}
// Displays question, answers, score
public void populateWithQuestionInfo(String question, String answer1,
String answer2, String answer3, String answer4,
int nextQuestionOrFinish) {
// populate the question label
TextView questionLabel = (TextView) findViewById(R.id.question);
questionLabel.setText(question);
// populate answer1
Button buttonAnswer1 = (Button) findViewById(R.id.answer1button);
buttonAnswer1.setText(answer1);
// populate answer2
Button buttonAnswer2 = (Button) findViewById(R.id.answer2button);
buttonAnswer2.setText(answer2);
// populate answer3
Button buttonAnswer3 = (Button) findViewById(R.id.answer3button);
buttonAnswer3.setText(answer3);
// populate answer4
Button buttonAnswer4 = (Button) findViewById(R.id.answer4button);
buttonAnswer4.setText(answer4);
numberOfQuestionsDisplayedCounter++;
}
// Generates a random number between 0 and 3 to be used to display the
// possible answers randomly
int RandomGeneratorZeroToThree() {
int randomInt = 0;
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx) {
randomInt = randomGenerator.nextInt(4);
}
return randomInt;
}
// Generates a random number between 0 and 29 to be used to select the
// question to be displayed
int RandomGenerator0To29() {
int randomInt2 = 0;
Random randomGenerator2 = new Random();
for (int idx2 = 1; idx2 <= 10; ++idx2) {
randomInt2 = randomGenerator2.nextInt(30);
}
return randomInt2;
}
// returns true if the question has already been displayed
// returns false if the question has not been already displayed
boolean questionsAlreadyDisplayed(int randomValue0to29) {
for (int i = 0; i < 10; i++) {
if (anArray2[i] == randomValue0to29) {
return true; // question already displayed
}
}
anArray2[numberOfQuestionsDisplayedCounter] = randomValue0to29; // questionId
// added
// to
// array
// of
// displayed
// questions
return false; // random number can be used as it has been used already
}
// Connects to the database to gather the question and 4 possible answers.
// Uses DataBaseHelper class
void getInfoFromDatabase(int categoryId, int questionId) {
DataBaseHelper myDbHelper = new DataBaseHelper(
this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
questionFromDatabase = myDbHelper.getQuestion(categoryId,
questionId);
displayedQuestionFromDatabase = questionFromDatabase;
System.out
.println("questionFromDatabase = " + questionFromDatabase);
answer1FromDatabase = myDbHelper.getCorrectAnswer(categoryId,
questionId); // correct answer from database
System.out.println("correct answer from db = "
+ answer1FromDatabase);
answer2FromDatabase = myDbHelper.getWrongAnswer1(categoryId,
questionId);
answer3FromDatabase = myDbHelper.getWrongAnswer2(categoryId,
questionId);
answer4FromDatabase = myDbHelper.getWrongAnswer3(categoryId,
questionId);
myDbHelper.close();
} catch (SQLException sqle) {
System.out.println("Errored out");
try {
throw sqle;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// If the player selects the right answer this method is called to increase
// the score by 10 points
void increaseScore() {
currentScore = currentScore + 10;
com.triviagame.Trivia_Game.finalScore = currentScore;
}
// If the player selects the wrong answer this method is called to decrease
// the score by 10 points
void decreaseScore() {
currentScore = currentScore - 10;
// score can't go below 0
if (currentScore < 0) {
currentScore = 0;
}
com.triviagame.Trivia_Game.finalScore = currentScore;
}
// Displays the current scores on the activity
void displayScore() {
TextView yourScore = (TextView) findViewById(R.id.yourscore);
String currentScoreText;
currentScoreText = Integer.toString(currentScore);
yourScore.setText(currentScoreText);
}
void resetTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
final TextView myCounter = (TextView) findViewById(R.id.tv);
mCountDown = new CountDownTimer(21000, 1000) {
#Override
public void onFinish() {
questionCheck();
resetTimer();
}
#Override
public void onTick(long millisUntilFinished) {
myCounter.setText("Time left: "
+ String.valueOf(millisUntilFinished / 1000));
}
}.start();
}
void cancelTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
}
void questionCheck() {
if (nextOrFinishValue == 1) {
Intent e = new Intent(this, finalscore.class);
startActivity(e);
cancelTimer();
}
if (nextOrFinishValue == 0) { // If 10 questions have not been displayed
// yet, display the next question
gatherInfoBeforePopulating();
displayScore();
populateWithQuestionInfo(displayedQuestionFromDatabase,
displayedAnswer1FromDatabase, displayedAnswer2FromDatabase,
displayedAnswer3FromDatabase, displayedAnswer4FromDatabase,
nextOrFinishValue);
}
}
// gathers question and answers from database
void gatherInfoBeforePopulating() {
categoryId = Trivia_Game.getCategoryIdInMainMenu();
// Loop until a valid questionId that hasn't been used is obtained
while (validQuestionNumber == false) {
randomValue0to29 = RandomGenerator0To29();
System.out.println("random30 in onClick = " + randomValue0to29);
alreadyDisplayQuestion = questionsAlreadyDisplayed(randomValue0to29);
if (alreadyDisplayQuestion == true) {
System.out
.println("question number already displayed looking for a non displayed question");
}
if (alreadyDisplayQuestion == false) {
System.out.println("question not displayed yet");
validQuestionNumber = true;
}
}
validQuestionNumber = false;
alreadyDisplayQuestion = false;
questionId = randomValue0to29; // sets the valid random generated number
// to the questionID
// connect to database to gather the question and answers
getInfoFromDatabase(categoryId, questionId);
// Calls random number from 0 to 3 to determine which button will
// display the correct answer
randomValueZeroToThree = RandomGeneratorZeroToThree();
System.out.println("random4 in onClick = " + randomValueZeroToThree);
// Sets the order according to the button that is to display the correct
// answer
switch (randomValueZeroToThree) {
case 0:
displayedAnswer1FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer2FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = true;
rightButton2 = false;
rightButton3 = false;
rightButton4 = false;
break;
case 1:
displayedAnswer2FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = true;
rightButton3 = false;
rightButton4 = false;
break;
case 2:
displayedAnswer3FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer2FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = true;
rightButton4 = false;
break;
case 3:
displayedAnswer4FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer2FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = false;
rightButton4 = true;
break;
default:
displayedAnswer1FromDatabase = answer4FromDatabase; // no correct
// answer
displayedAnswer2FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer1FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = false;
rightButton4 = false;
}
// After the 9th question is displayed, the nextOfFinishValue should be
// set to 1 so the button displayes Finish instead of Next
if (numberOfQuestionsDisplayedCounter < 9) {
nextOrFinishValue = 0;
} else {
nextOrFinishValue = 1;
}
}
// Listeners for the 4 buttons with answers and the Next or Finish buttons
public void onClick(View v) {
switch (v.getId()) {
case R.id.answer1button:
if (rightButton1 == true) {
increaseScore();
resetTimer();
// put here to change color of button
} else {
decreaseScore();
resetTimer();
// change button to red
}
questionCheck();
break;
case R.id.answer2button:
if (rightButton2 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
case R.id.answer3button:
if (rightButton3 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
case R.id.answer4button:
if (rightButton4 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
}
}
#Override
protected void onResume() {
super.onResume();
music.play(this, R.raw.musicbackground); // play background music
}
#Override
protected void onPause() {
super.onPause();
music.stop(this); // stop playing background music
}
}

mCountdown is never null so change your code
void cancelTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
}
To
void cancelTimer() {
mCountDown.cancel();
}

Related

Sharing Intent Not working Properly

I have one quote application. I have implemented share and copy function in it. I am facing issue is that I am not getting shared first time sharing quote. Means if there 50 quote in list and if I try to share any quote from list than it is not sharing anything. after that if I move on another quote and try to sharing than its working fine. I have same issue in copy function also. I also face some time issue like if I share quote number 50 than its sharing another number quote. Please help me for solve the bug. Thanks
My Activity for it is like below.
public class QuoteDialogActivity extends Activity {
DAO db;
static final String KEY_ID = "_quid";
static final String KEY_TEXT = "qu_text";
static final String KEY_AUTHOR = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_FAVORITE = "qu_favorite";
static final String KEY_WEB_ID = "au_web_id";
ArrayList<HashMap<String, String>> quotesList;
HashMap<String, String> map;
ImageButton btnnext,btnprev,star,copy;
int pos,lstcount = 0;
ScrollView ll_quote;
String quote_id;
TextView text;
String quText, quAuthor, quPicture, quFavorite,quoteShare;
int auPictureSDCard;
String isFavorite;
String auPictureDir;
String siteUrl;
private ImageLoader imgLoader;
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
String TWITTER_CONSUMER_KEY;
String TWITTER_CONSUMER_SECRET;
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_FACEBOOK_LOGIN = "isFacebookLogedIn";
Typeface tf;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
String quote;
ProgressDialog pDialog;
private SharedPreferences mSharedPreferences;
private static SharedPreferences facebookPreferences, twitterPreferences;
Cursor c, c2;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
//private UiLifecycleHelper uiHelper;
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imgLoader = new ImageLoader(this);
//TWITTER_CONSUMER_KEY = getResources().getString(R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(R.string.TWITTER_CONSUMER_SECRET);
// uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
//facebookPreferences = getApplicationContext().getSharedPreferences("facebookPref", 0);
//twitterPreferences = getApplicationContext().getSharedPreferences("twitterPref", 0);
db = new DAO(this);
db.open();
c2 = db.getSettings();
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
c = db.getOneQuote(mSharedPreferences.getString("QOTD", ""));
} else {
c = db.getOneQuote(getIntent().getStringExtra("QuoteId"));
}
// if (c.getCount() != 0) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quote_dialog);
// ============================ check if user want to display
// ============================ background image for quote
if (c2.getString(c2.getColumnIndex("background")).equals("1")) {
Random random = new Random();
int idNumber = random.nextInt(20 - 1 + 1) + 1;
RelativeLayout layout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
Drawable d = null;
try {
View topShadow = (View) findViewById(R.id.topShadow);
View bottomShadow = (View) findViewById(R.id.bottomShadow);
topShadow.setVisibility(View.INVISIBLE);
bottomShadow.setVisibility(View.INVISIBLE);
d = Drawable.createFromStream(getAssets().open("backgrounds/" + String.valueOf(idNumber) + ".jpg"),
null);
layout.setBackgroundDrawable(d);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
// ===========================================================================================
quText = c.getString(c.getColumnIndex(KEY_TEXT));
quAuthor = c.getString(c.getColumnIndex(KEY_AUTHOR));
quPicture = c.getString(c.getColumnIndex(KEY_PICTURE));
auPictureSDCard = c.getInt(c.getColumnIndex(KEY_PICTURE_SDCARD));
quFavorite = c.getString(c.getColumnIndex(KEY_FAVORITE));
text = (TextView) findViewById(R.id.text); // title
// tf = Typeface.createFromAsset(getAssets(), "fonts/devnew.ttf");
//text.setTypeface(tf);
// author = (TextView) findViewById(R.id.author); // author
// picture = (ImageView) findViewById(R.id.picture); // thumb
text.setText(quText);
// author.setText("- " + quAuthor.trim());
// if (auPictureSDCard == 0) {
// AssetManager assetManager = getAssets();
// InputStream istr = null;
// try {
// istr = assetManager.open("authors_pics/" + quPicture);
// } catch (IOException e) {
// Log.e("assets", assetManager.toString());
// e.printStackTrace();
// }
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
// } else {
// siteUrl = getResources().getString(R.string.siteUrl);
//
// auPictureDir = siteUrl + "global/uploads/authors/";
// imgLoader.DisplayImage(
// auPictureDir + quPicture, picture);
// }
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open("authors_pics/" + quPicture);
} catch (IOException e) {
Log.e("assets", assetManager.toString());
e.printStackTrace();
}
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
final ImageButton dismiss = (ImageButton) findViewById(R.id.close);
dismiss.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
//=============================Next Button and Prev Button
star = (ImageButton) findViewById(R.id.star);
btnnext = (ImageButton)findViewById(R.id.nextButton);
btnprev = (ImageButton)findViewById(R.id.PrevioustButton);
pos= getIntent().getIntExtra("Pos",0);
quote_id = getIntent().getStringExtra("QuoteId");
lstcount = getIntent().getIntExtra("LstCount",0);
#SuppressWarnings("unchecked")
final ArrayList<HashMap<String, String>> quotesList =(ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("Quotes");
btnnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
text.setText(quotesList.get(pos).get(KEY_TEXT));
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quoteShare = quotesList.get(pos).get(KEY_TEXT);
Log.e("ErrorMsg", "quoteShare is: " + quoteShare);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();//new
Log.i("quote is",quote_id);
}
}
});
btnprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == 1 ||pos == 0)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
text.setText(quotesList.get(p-1).get(KEY_TEXT));
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();
}
}
});
//======================================================= Swipe
ll_quote = (ScrollView)findViewById(R.id.scrollView1);
ll_quote.setOnTouchListener(new OnTouchListener() {
int downX, upX;
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downX = (int) event.getX();
Log.i("event.getX()", " downX " + downX);
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
upX = (int) event.getX();
Log.i("event.getX()", " upX " + downX);
if (upX - downX > 100) {
if(pos == 0 || pos == 1)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(p-1).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
else if (downX - upX > -100) {
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(pos).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
return true;
}
return false;
}
});
// ========================== share button
final ImageButton share = (ImageButton) findViewById(R.id.share);
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,pos);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
//copy button
final ImageButton copyy = (ImageButton) findViewById(R.id.copy);
copyy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("simple text",quoteShare);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Status Copied",
Toast.LENGTH_LONG).show();
}
});
// ========================== set as favorite and unfavorite
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
star.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isFavorite.equals("0")) {
isFavorite = "1";
star.setImageResource(R.drawable.star_on);
} else {
isFavorite = "0";
star.setImageResource(R.drawable.star_off);
}
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
db.addOrRemoveFavorites(mSharedPreferences.getString("QOTD", ""), isFavorite);
} else {
// Log.i("quotes",quotesList.get(pos).get(String.valueOf(KEY_WEB_ID))+"POS"+pos+"quid"+quotesList.get(pos).get(KEY_ID));
db.addOrRemoveFavorites(quote_id, isFavorite);
// db.addOrRemoveFavorites(getIntent().getStringExtra("QuoteId"), isFavorite);
if (getIntent().getIntExtra("quotesType", 0) == 2 && isFavorite.equals("0")) {
Intent i = new Intent(QuoteDialogActivity.this, QuotesActivity.class);
i.putExtra("quotesType", 2);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(i);
}
}
}
});
// }
}
// ==============================================================================
public void FirstFav()
{
String Image_id=quote_id;
quFavorite = db.getFavQuotes(quote_id);
if(quFavorite.length()>0)
isFavorite = quFavorite;
else
isFavorite = "0";
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
}
//===================================================================================
}
Thanks

CountDownTimer Android issue

I'm trying to implement a CountDownTimer in an Android Application. This timer will, while running, countdown from a value, than reset, than countdown from a different value. Switching back and force between values until either a set number of rounds have elapsed or the stop button has been pressed. I can get the CountDownTimer samples to work, but I guess I'm missing something here. Below is the applicable button press code;
CounterState state = CounterState.WORKOUT;
private WorkoutTimer workoutTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout_stopwatch);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set up OnClickListeners
((Button) findViewById(R.id.start_button)).setOnClickListener(this);
((Button) findViewById(R.id.stop_button)).setOnClickListener(this);
((Button) findViewById(R.id.reset_button)).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.start_button:
if (!timer_running) {
timer_running = true;
Log.d(TAG, "clicked on Start Button");
// If the state is unknown, set it to Workout first
int State = state.getStateValue();
if (State == 0) {
state.setStateValue(1);
}
workoutTimer.start();
}
break;
case R.id.stop_button:
Log.d(TAG, "clicked on Stop Button");
if (timer_running); {
timer_running = false;
workoutTimer.cancel();
}
break;
private class WorkoutTimer extends CountDownTimer{
public WorkoutTimer(long interval) {
super(getThisTime(), interval);
Log.d(TAG, "WorkoutTimer Constructed...");
}
TextView digital_display = (TextView) findViewById(R.id.digital_display);
TextView numOfRounds = (TextView) findViewById(R.id.number_of_rounds);
public void onFinish() {
int State = state.getStateValue();
int roundsLeft = 0;
if (State == 1) {
state.setStateValue(2);
} else {
state.setStateValue(1);
}
decrementRounds();
try {
roundsLeft = Integer.parseInt(numOfRounds.getText().toString());
} catch(NumberFormatException nfe) {
roundsLeft = 999;
}
if (roundsLeft > 0 || roundsLeft != 999) {
workoutTimer.start();
}
}
public void onTick(long millisUntilFinished) {
final long minutes_left = ((millisUntilFinished / 1000) / 60);
final long seconds_left = (millisUntilFinished / 1000) - (minutes_left * 60);
final long millis_left = millisUntilFinished % 100;
String time_left = String.format("%02d:%02d.d", minutes_left, seconds_left,
millis_left);
digital_display.setText(time_left);
}
}
private long getThisTime() {
long time = 0;
TextView workout_time = (TextView) findViewById(R.id.workout_time);
TextView rest_time = (TextView) findViewById(R.id.rest_time);
switch(state) {
case WORKOUT:
try {
time = Integer.parseInt(workout_time.getText().toString());
} catch(NumberFormatException nfe) {
time = 999;
}
// time = 90;
Log.d(TAG, "Workout time = " + time);
break;
case REST:
try {
time = Integer.parseInt(rest_time.getText().toString());
} catch(NumberFormatException nfe) {
time = 999;
}
// time = 30;
Log.d(TAG, "Rest time = " + time);
break;
case UNKNOWN:
time = 0;
break;
}
return time;
}
Everything starts up okay, but crashes when I click either button. If I comment out my calls to the workoutTimer, no crash. I never see my log in the constructor of the workoutTimer class, so obviously I'm missing something here. Any help would be appreciated.
-Ian
You have not initialized your workoutTimer. You need to add the following line in your onCreate method.
workoutTimer = new WorkoutTimer(...);

Scoring of trivia game becomes inaccurate after 2nd game

I have a trivia game that is 10 timed questions. A wrong answer is supposed to output 0 points. A correct answer is supposed to output the remaining of the 20,000 milliseconds converted to a 100 point scale.
Right now the game works on the first game. Then, if the user keeps playing for a second time, the points for each question becomes incorrect. For example, incorrect answers begin to have a variety of points from 1 to 100 and also correct answers sometimes have 0 points and also sometimes wrong point totals. So I am guessing some variable is possibly not resetting on the second game so it is causing the points to be a little off.
I posted all the code that deals with the algorithm. My question is how I can get this code to output the correct answer no matter how many times the user plays before closing the app.
QuestionView.java
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter, timeremaining;
AdView adView;
ArrayList<Question> queries;
public static ArrayList<Long> pointsPerQuestion = new ArrayList<Long>(10);
Timer cdTimer;
ProgressBar bar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.questionview);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
questionNumber = (TextView)findViewById(R.id.questionnumber);
timeremaining = (TextView)findViewById(R.id.timeremaining);
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(20000);
tracker.sendView("/QuestionView - Started Quiz");
loadQuestion();
}
public void loadQuestion() {
if(i == 10) {
cdTimer.cancel();
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(1);
if(answer == 1) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(2);
if(answer == 2) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(3);
if(answer == 3) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public static ArrayList<Long> getPointsPerQuestion() {
return pointsPerQuestion;
}
public void correct() {
pointsPerQuestion.add(points);
score = score + points;
i++;
loadQuestion();
}
public void incorrect() {
long zero = 0;
pointsPerQuestion.add(zero);
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
points = 0;
if(i >= 9) {
cdTimer.cancel();
pointsPerQuestion.add(points);
endQuiz();
} else {
wrongAnswers++;
incorrect();
}
}
#Override
public void onTick(long millisUntilFinished) {
bar.setProgress((int) millisUntilFinished);
points = millisUntilFinished / 200;
timeremaining.setText("Score remaining: " + points);
if(i < 10) {
questionNumber.setText("Question " + (i + 1) + " of 10");
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putExtra("pointsPerQuestion", pointsPerQuestion);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
}
Here is a Question object:
exodus.add(new Question("6th", "3rd", "5th", "4th", 2, "Name that plague: All livestock dies", -1, "Exodus 9:6"));
In my Results class, which is where the points per question is displayed, this is the line that displays the points:
scoreTV.setText("You received " + QuestionView.getPointsPerQuestion().get(x) + " out of a possible 100 points.");
Everything else is pretty much in my QuestionView above. Let me know if you still need something else.
First 3 Strings are answers A (index 0), B (index 1), C (index 2) and D (index 3). The first int is the correct answer. The 5th String is the question. The second int is set to the answer selected by user during quiz. Last String is the bible verse where the answer is found.

how to intent another class using json array [duplicate]

This question already has an answer here:
How to limit the display of questions in the quiz using json array in android?
(1 answer)
Closed 10 years ago.
im developing a quiz wherein i have 10 questions stored. and it is randomly displayed my problem is after that my 10th question i do not know how to intent it to my score class which score must be display of the player recently played the quiz.
this is where the questions is loaded:
public class Question1 extends Activity {
Intent menu = null;
BufferedReader bReader = null;
static JSONArray quesList = null;
static int index = 50;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question10);
Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(1 * 1000);
finish();
loadQuestions();
Intent intent = new Intent(Question1.this,
Question2.class);
Question1.this.startActivity(intent);
} catch (Exception e) {
}
}
};
thread.start();
}
//List<JSONObject> question = null;
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
/* question = new ArrayList<JSONObject>();
int n = Math.min(10, quesList.length());
for(int i = 0; i < n; i++) {
JSONObject questions1 = quesList.getJSONObject(i);
question.add(questions1);*/
} catch (Exception e) {
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList()throws JSONException{
Random rnd = new Random();
for (int i = quesList.length() - 1; i >= 0; i--)
{
int j = rnd.nextInt(i + 1);
// Simple swap
Object object = quesList.get(j);
quesList.put(j, quesList.get(i));
quesList.put(i, object);
}
return quesList;
}
this is where the event of the questions:
public class Question2 extends Activity {
/** Called when the activity is first created. */
TextView question, items = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioGroup answers = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review = false;
Button next = null;
int score = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startquiz);
try {
score = getIntent().getIntExtra("score",0);
items = (TextView)findViewById(R.id.displayitems);
question = (TextView) findViewById(R.id.displayquestion);
answer1 = (RadioButton) findViewById(R.id.option1);
answer2 = (RadioButton) findViewById(R.id.option2);
answer3 = (RadioButton) findViewById(R.id.option3);
answers = (RadioGroup) findViewById(R.id.QueGroup1);
next = (Button) findViewById(R.id.selected);
next.setOnClickListener(nextListener);
selected = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(selected, -1);
correctAns = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(correctAns, -1);
this.showQuestion(0, review);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
private void showQuestion(int qIndex, boolean review) {
try {
JSONObject aQues = Question1.getQuesList().getJSONObject(
qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.BLACK);
answer2.setTextColor(Color.BLACK);
answer3.setTextColor(Color.BLACK);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("", selected[qIndex] + "");
if (selected[qIndex] == 0)
answers.check(R.id.option1);
if (selected[qIndex] == 1)
answers.check(R.id.option2);
if (selected[qIndex] == 2)
answers.check(R.id.option3);
setText();
if (quesIndex == (Question1.getQuesList().length() - 1))
next.setEnabled(false);
if (quesIndex < (Question1.getQuesList().length() - 1))
next.setEnabled(true);
if (review) {
Log.d("review", selected[qIndex] + "" + correctAns[qIndex]);
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
Log.d("", Arrays.toString(selected));
Log.d("", Arrays.toString(correctAns));
}
private OnClickListener nextListener = new OnClickListener() {
public void onClick(View v) {
int i = correctAns.length;
if (v == next){
if (correctAns[i] == selected[i])
{
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(), "Your answer is wrong..." + correctAns, Toast.LENGTH_SHORT).show();
}
}
quesIndex++;
try {
if (quesIndex >= Question1.getQuesList().length())
quesIndex = Question1.getQuesList().length() - 1;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
showQuestion(quesIndex, review);
}
};
private void setText() throws JSONException {
this.setTitle("Question " + (quesIndex + 1) + " out of "
+ Question1.getQuesList().length());
items.setGravity(250);
}
public void reload() {
setAnswer();
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
I am unable to understand why you're trying to run a separate thread in Question1.onCreate(). If you want to load the questions in the background, use AsyncTask. Personally, I prefer to use an IntentService to do background tasks where you want to persist the results. An IntentService is particularly useful for decoding JSON.
You don't say what is happening now with your app, but my guess is that the Activity Question2 never starts. I'm not sure, but I suspect it's because you're trying to start the Activity from a background thread. You could use runOnUiThread() to fix this, but it would be much better to load the questions in an IntentService, send a local BroadcastMessage to your Activity when the loading is done, and then display the results. Also, I'd parse the JSON into a database or content provider.

change imageview using int

I've been stuck on this for a whole day, please help me. So I have 2 arrays filled with five dice rolls from two players and I want to set them to the according dice image that I put in my drawable. This is the original code that I have, displaying the arrays in TextView.
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice;
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
I can't figure out how to get it to display the ImageView instead.
private final static int[] diceImages = new int[] { R.drawable.d1,
R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
What I am missing?
Here's my full code, sorry its a mess. I just started to learn programming on my own and this is my first program. Any advice on making it better is appreciated too.
package com.kelvinblade.liardice;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice, result, whosTurn, tvLog, score;
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
Button openDice, callDice;
EditText NumDice, DiceNum;
int NumOfDice, DiceNumber, turn;
int currentDiceQuantity, currentDiceFace;
boolean isOneWildCard = true;
int callLog[] = new int[70];
int playerOneEnergy, playerTwoEnergy;
boolean playerOneStart = true;
private final int[] diceImages = new int[] { R.drawable.d1, R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializePlaceHolders();
startGame();
}
// Initialize the Place Holders
private void initializePlaceHolders() {
p1Dice = (TextView) findViewById(R.id.tvP1Dice);
p2Dice = (TextView) findViewById(R.id.tvP2Dice);
openDice = (Button) findViewById(R.id.bOpenDice);
callDice = (Button) findViewById(R.id.bCallDice);
whosTurn = (TextView) findViewById(R.id.tvWhosTurn);
tvLog = (TextView) findViewById(R.id.tvLog);
score = (TextView) findViewById(R.id.tvScore);
result = (TextView) findViewById(R.id.tvResult);
NumDice = (EditText) findViewById(R.id.etNumDice);
DiceNum = (EditText) findViewById(R.id.etDiceNum);
p1Dice1 = (ImageView) findViewById(R.id.ivDice1);
p1Dice2 = (ImageView) findViewById(R.id.ivDice2);
p1Dice3 = (ImageView) findViewById(R.id.ivDice3);
p1Dice4 = (ImageView) findViewById(R.id.ivDice4);
p1Dice5 = (ImageView) findViewById(R.id.ivDice5);
openDice.setOnClickListener(this);
callDice.setOnClickListener(this);
}
// Game starts here
public void startGame() {
playerOneEnergy = 4;
playerTwoEnergy = 4;
playGame();
}
// Starts level
public void playGame() {
if ((playerOneEnergy != 0) && (playerTwoEnergy != 0)) {
initialize();
player1 = rollDice();
player2 = rollDice();
displayDice();
displayTurn();
} else if (playerTwoEnergy == 0) {
result.setText("Loading Next Stage!");
startGame();
} else
result.setText("Game Over!");
}
// Initialize the Variables
private void initialize() {
turn = 0;
currentDiceQuantity = 0;
currentDiceFace = 0;
result.setText("New Game.");
tvLog.setText("Game Log:");
}
// Rolls the Dice
private int[] rollDice() {
int[] diceArray = new int[5];
Random randomDice = new Random();
for (int i = 0; i < 5; i++) {
diceArray[i] = randomDice.nextInt(6) + 1;
}
return diceArray;
}
// Displays the Dice for Player 1 & 2
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
// try to display the dice array as image <here's the problem>
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
}
// Button actions
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCallDice:
try {
getCall();
} catch (Exception e) {
Dialog d = new Dialog(this);
d.setTitle("Invalid call. Please try again.");
d.show();
}
if ((validInput()) && (validCall()))
runCall();
else
result.setText("Invalid call");
break;
case R.id.bOpenDice:
checkDice();
break;
}
}
private void runCall() {
currentDiceQuantity = NumOfDice;
currentDiceFace = DiceNumber;
result.setText("Valid call");
writeLog();
displayLog();
turn++;
displayTurn();
}
private void startAImove() {
Random randomAction = new Random();
int randomCall = randomAction.nextInt(1);
if ((randomCall == 0) && (!isFirstMove()))
checkDice();
else {
while (!validCall()) {
NumOfDice = randomAction.nextInt(5) + 1;
DiceNumber = randomAction.nextInt(5) + 1;
}
runCall();
}
}
// Gets the Call from Player 1
private void getCall() {
String s = NumDice.getText().toString();
NumOfDice = Integer.parseInt(s);
String s1 = DiceNum.getText().toString();
DiceNumber = Integer.parseInt(s1);
if (DiceNumber == 1) {
isOneWildCard = false;
}
}
// Checks to see if the call is a valid input
private boolean validInput() {
int MaxNumOfDice = 5;
int MaxDiceQuantity = 6;
if ((NumOfDice <= MaxNumOfDice * 2) && (DiceNumber <= MaxDiceQuantity)) {
return true;
} else
return false;
}
// Checks to see if Valid Call
private boolean validCall() {
if (NumOfDice > currentDiceQuantity) {
return true;
} else if (((NumOfDice == currentDiceQuantity) && (currentDiceFace != 1))
&& ((DiceNumber == 1) || (DiceNumber > currentDiceFace))) {
return true;
} else {
return false;
}
}
// Writes to Log
private void writeLog() {
callLog[turn * 2] = currentDiceQuantity;
callLog[turn * 2 + 1] = currentDiceFace;
}
// Display Log
private void displayLog() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Game Log:\n");
for (int i = 0; i < turn + 1; i++) {
sbfNumbers.append((i + 1) + ": Player" + (i % 2 + 1) + " "
+ callLog[i * 2] + "x" + callLog[i * 2 + 1] + "\n");
}
tvLog.setText(sbfNumbers.toString());
}
// Display who's turn
public void displayTurn() {
if (whichPlayersTurn() == 1)
whosTurn.setText("Player 1's Turn...");
else {
whosTurn.setText("Player 2's Turn...");
// startAImove();
}
}
// Checks who's turn
private int whichPlayersTurn() {
boolean isTurnEven = false;
if (turn % 2 == 0)
isTurnEven = true;
if (((playerOneStart) && (isTurnEven))
|| ((!playerOneStart) && (!isTurnEven))) {
return 1;
} else
return 2;
}
// Checks if it's the first move
private boolean isFirstMove() {
if (currentDiceQuantity == 0)
return true;
else
return false;
}
// Checks the Player 1 & 2 for the Dice
private void checkDice() {
if (!isFirstMove()) {
int DiceCount = 0;
for (int i = 0; i < 5; i++) {
if (player1[i] == DiceNumber)
DiceCount++;
if (player2[i] == DiceNumber)
DiceCount++;
if ((player1[i] == 1) && (isOneWildCard))
DiceCount++;
if ((player2[i] == 1) && (isOneWildCard))
DiceCount++;
}
if (((DiceCount >= NumOfDice) && (whichPlayersTurn() != 1))
|| ((DiceCount < NumOfDice) && (whichPlayersTurn() == 1))) {
result.setText("Player 1 Wins!");
playerTwoEnergy--;
playerOneStart = false;
} else {
result.setText("Player 1 Loses!");
playerOneEnergy--;
playerOneStart = true;
}
displayWinLost();
playGame();
} else
result.setText("Can not open on first move!");
}
// Display Win / Lose
private void displayWinLost() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Player One Energy : " + playerOneEnergy
+ "\nPlayer Two Energy: " + playerTwoEnergy);
score.setText(sbfNumbers.toString());
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
Thank you so much in advanced. Any help is highly appreciated. Thanks again!!
In your code imageViews are not in an array, so you cannot do p1Dice[i] .
So please change to
private ImageView[] p1Dice = new ImageView[5];
or
p1Dice1.setImageResource(diceImage[player1[0]]);
p1Dice2.setImageResource(diceImage[player1[1]]);
p1Dice3.setImageResource(diceImage[player1[2]]);
The ImageViews are not in an array, so you cannot do p1Dice[i].something()
Change the declaration to ImageViews to this
private ImageView[] p1Dice = new ImageView[5];

Categories

Resources