Android - Control the flow of Loop by button presses - android

I have an activity class in my Android App, where after some data is handled, that data is sent to another method in another class which gives back an ArrayList. What I want to do is to iterate through that ArrayList and for every piece of text in it, I would like to update the TextView label in my interface. However this should be done whenever the user presses the 'Yes' button on screen. (i.e. whenever the user presses the 'Yes' button, the loop would progress to the next element of the ArrayList and its value updated in the TextView label). Here is what I have so far:
try {
sentenceGenerator = new SentenceGenerator();
ArrayList<ArrayList<String>> states = stateGenerator
.getPossibleStates(resultOutput, result, result);
for (ArrayList<String> state : states) {
viewPoint = state.get(0);
subject = state.get(1);
object = state.get(2);
subjectInfo = new ObjectReference();
if (resultOutput.equals("Sliema")) {
Sliema sliema = new Sliema();
subjectInfo = sliema.getInfo(viewPoint, object, subject);
}
try {
s = sentenceGenerator.generateSentence("start", "middle",
"end", resultOutput, viewPoint, object, subject,
subjectInfo.type, subjectInfo.name,
subjectInfo.properties, false);
instructionTextView = (TextView) findViewById(R.id.instructionTextView);
mHandler = new Handler();
instructionTextView
.setText("Press 'Yes' to start Orientation procedure");
Button confirmButton = (Button) findViewById(R.id.confirmButton);
Button declineButton = (Button) findViewById(R.id.declineButton);
confirmButton
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mHandler.post(mUpdate);
}
});
declineButton
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//
}
});
Log.d("INSTRUCTIONS", s);
} catch (Exception e) {
}
}
} catch (ClassNotFoundException e) {
}
and this is the update Handler:
private Runnable mUpdate = new Runnable() {
public void run() {
instructionTextView.setText(s);
// mHandler.postDelayed(this, 1000);
confirmPressed = true;
// i++;
}
};
Any Suggestions? Thanks in advance!

Try Adding a break;in the buttonclickListener where you want to terminate the loop.

Related

Showing results for a quiz app (Android Studio)

I have a quiz app that is working properly, but the thing is the user must answer all questions correctly in order to win the game(if the player gets it wrong the game will be over) .
What I wanted to do is have the questions answered and then at the end there will be an activity that will show how many the player has answered then there will be the options to retry and go back to menu
This is the code for the maingameactivity
public class MainGameActivity extends AppCompatActivity {
FButton buttonA, buttonB, buttonC, buttonD;
TextView questionText, triviaQuizText, timeText, resultText, coinText;
TriviaQuizHelper triviaQuizHelper;
TriviaQuestion currentQuestion;
List<TriviaQuestion> list;
int qid = 0;
int timeValue = 20;
int coinValue = 0;
CountDownTimer countDownTimer;
Typeface tb, sb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_main);
//Initializing variables
questionText = (TextView) findViewById(R.id.triviaQuestion);
buttonA = (FButton) findViewById(R.id.buttonA);
buttonB = (FButton) findViewById(R.id.buttonB);
buttonC = (FButton) findViewById(R.id.buttonC);
buttonD = (FButton) findViewById(R.id.buttonD);
triviaQuizText = (TextView) findViewById(R.id.triviaQuizText);
timeText = (TextView) findViewById(R.id.timeText);
resultText = (TextView) findViewById(R.id.resultText);
coinText = (TextView) findViewById(R.id.coinText);
//Setting typefaces for textview and buttons - this will give stylish fonts on textview and button etc
tb = Typeface.createFromAsset(getAssets(), "fonts/TitilliumWeb-Bold.ttf");
sb = Typeface.createFromAsset(getAssets(), "fonts/shablagooital.ttf");
triviaQuizText.setTypeface(sb);
questionText.setTypeface(tb);
buttonA.setTypeface(tb);
buttonB.setTypeface(tb);
buttonC.setTypeface(tb);
buttonD.setTypeface(tb);
timeText.setTypeface(tb);
resultText.setTypeface(sb);
coinText.setTypeface(tb);
//Our database helper class
triviaQuizHelper = new TriviaQuizHelper(this);
//Make db writable
triviaQuizHelper.getWritableDatabase();
//It will check if the ques,options are already added in table or not
//If they are not added then the getAllOfTheQuestions() will return a list of size zero
if (triviaQuizHelper.getAllOfTheQuestions().size() == 0) {
//If not added then add the ques,options in table
triviaQuizHelper.allQuestion();
}
//This will return us a list of data type TriviaQuestion
list = triviaQuizHelper.getAllOfTheQuestions();
//Now we gonna shuffle the elements of the list so that we will get questions randomly
Collections.shuffle(list);
//currentQuestion will hold the que, 4 option and ans for particular id
currentQuestion = list.get(qid);
//countDownTimer
countDownTimer = new CountDownTimer(22000, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to timeText
timeText.setText(String.valueOf(timeValue) + "\"");
//With each iteration decrement the time by 1 sec
timeValue -= 1;
//This means the user is out of time so onFinished will called after this iteration
if (timeValue == -1) {
//Since user is out of time setText as time up
resultText.setText(getString(R.string.timeup));
//Since user is out of time he won't be able to click any buttons
//therefore we will disable all four options buttons using this method
disableButton();
}
}
//Now user is out of time
public void onFinish() {
//We will navigate him to the time up activity using below method
timeUp();
}
}.start();
//This method will set the que and four options
updateQueAndOptions();
}
public void updateQueAndOptions() {
//This method will setText for que and options
questionText.setText(currentQuestion.getQuestion());
buttonA.setText(currentQuestion.getOptA());
buttonB.setText(currentQuestion.getOptB());
buttonC.setText(currentQuestion.getOptC());
buttonD.setText(currentQuestion.getOptD());
timeValue = 20;
//Now since the user has ans correct just reset timer back for another que- by cancel and start
countDownTimer.cancel();
countDownTimer.start();
//set the value of coin text
coinText.setText(String.valueOf(coinValue));
//Now since user has ans correct increment the coinvalue
coinValue++;
}
//Onclick listener for first button
public void buttonA(View view) {
//compare the option with the ans if yes then make button color green
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
//Check if user has not exceeds the que limit
if (qid < list.size() - 1) {
//Now disable all the option button since user ans is correct so
//user won't be able to press another option button after pressing one button
disableButton();
//Show the dialog that ans is correct
correctDialog();
}
//If user has exceeds the que limit just navigate him to GameWon activity
else {
gameWon();
}
}
//User ans is wrong then just navigate him to the PlayAgain activity
else {
gameLostPlayAgain();
}
}
//Onclick listener for sec button
public void buttonB(View view) {
if (currentQuestion.getOptB().equals(currentQuestion.getAnswer())) {
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for third button
public void buttonC(View view) {
if (currentQuestion.getOptC().equals(currentQuestion.getAnswer())) {
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for fourth button
public void buttonD(View view) {
if (currentQuestion.getOptD().equals(currentQuestion.getAnswer())) {
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//This method will navigate from current activity to GameWon
public void gameWon() {
Intent intent = new Intent(this, GameWon.class);
startActivity(intent);
finish();
}
//This method is called when user ans is wrong
//this method will navigate user to the activity PlayAgain
public void gameLostPlayAgain() {
Intent intent = new Intent(this, PlayAgain.class);
startActivity(intent);
finish();
}
//This method is called when time is up
//this method will navigate user to the activity Time_Up
public void timeUp() {
Intent intent = new Intent(this, Time_Up.class);
startActivity(intent);
finish();
}
//If user press home button and come in the game from memory then this
//method will continue the timer from the previous time it left
#Override
protected void onRestart() {
super.onRestart();
countDownTimer.start();
}
//When activity is destroyed then this will cancel the timer
#Override
protected void onStop() {
super.onStop();
countDownTimer.cancel();
}
//This will pause the time
#Override
protected void onPause() {
super.onPause();
countDownTimer.cancel();
}
//On BackPressed
#Override
public void onBackPressed() {
Intent intent = new Intent(this, HomeScreen.class);
startActivity(intent);
finish();
}
//This dialog is show to the user after he ans correct
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(MainGameActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog_correct);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
//Since the dialog is show to user just pause the timer in background
onPause();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
FButton buttonNext = (FButton) dialogCorrect.findViewById(R.id.dialogNext);
//Setting type faces
correctText.setTypeface(sb);
buttonNext.setTypeface(sb);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//it will increment the question number
qid++;
//get the que and 4 option and store in the currentQuestion
currentQuestion = list.get(qid);
//Now this method will set the new que and 4 options
updateQueAndOptions();
//reset the color of buttons back to white
resetColor();
//Enable button - remember we had disable them when user ans was correct in there particular button methods
enableButton();
}
});
}
//This method will make button color white again since our one button color was turned green
public void resetColor() {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
}
//This method will disable all the option button
public void disableButton() {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
}
//This method will all enable the option buttons
public void enableButton() {
buttonA.setEnabled(true);
buttonB.setEnabled(true);
buttonC.setEnabled(true);
buttonD.setEnabled(true);
}
}
Edited
Just remove the wrapper if else inside all the buttons better to keep it as, don't repeat the code. I am assuming the screen that shows result is handled inside gameWon and you have implemented functionality for inCorrectDialog
public void buttonA(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonB(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonC(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonD(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonPressed(Button button) {
button.setButtonColor(ContextCompat.getColor(getApplicationContext(), R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
correctDialog();
} else {
inCorrectDialog();
}
} else {
gameWon();
}
}

Compare data from edit text with data from if statement

I'm making a quiz app. User has to finish the phrase shown on display and write the name of the car in the edittext, after pushing on button, if the answer right, edittext become green, if doesn't, become red. If all answers right (green), intent move on next activity.
I have some difficulties with if statement edit text become red even the answer was right. Also how to make INTENT to move on next activity if all right, if not it doesn't move?
public class MainActivity extends AppCompatActivity {
EditText et_one_one, et_one_two, et_one_three;
Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_one_one = (EditText) findViewById(R.id.et_one_one);
et_one_two = (EditText) findViewById(R.id.et_one_two);
et_one_three = (EditText) findViewById(R.id.et_one_three);
final String t1 = et_one_one.getText().toString();
final String t2 = et_one_two.getText().toString();
final String t3 = et_one_three.getText().toString();
buttonCheck = (Button) findViewById(R.id.buttonCheck);
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (t1.equals("maserati")){
et_one_one.setBackgroundColor(Color.GREEN);
}
else {
et_one_one.setBackgroundColor(Color.RED);
}
if (t2.equals("mercedes")){
et_one_two.setBackgroundColor(Color.GREEN);
}
else{
et_one_two.setBackgroundColor(Color.RED);
}
if (t3.equals("bmw")){
et_one_three.setBackgroundColor(Color.GREEN);
}
else{
et_one_three.setBackgroundColor(Color.RED);
}
}
});
}
}
You're changing the color of just the et_one_one each time in your if else statements. Shouldn't it be for different edittexts?
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean allAnswersCorrect = true;
String t1 = et_one_one.getText().toString();
String t2 = et_one_two.getText().toString();
String t3 = et_one_three.getText().toString();
if (t1.equals("maserati")){
et_one_one.setBackgroundColor(Color.GREEN);
}
else {
allAnswersCorrect = false;
et_one_one.setBackgroundColor(Color.RED);
}
if (t2.equals("mercedes")){
et_one_two.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_two.setBackgroundColor(Color.RED);
}
if (t3.equals("bmw")){
et_one_three.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_three.setBackgroundColor(Color.RED);
}
if(allAnswersCorrect){
Intent intent = new Intent(YourActivity.this, YourSecondActivity.class);
startActivity(intent);
}
}
});
Maintain a allAnswersCorrect boolean to check whether your answers are correct or not. If all are correct the move to your next activity.
You should use t2.equals("maserati"), and it will be ok.

How to get button's id which was created programmatically in Async Task onPostExecute

I create adapter in onPostExecute like this, and i set button's id programmatically.
list.add(new adapters.GunADP("name","name","name",buttonId));
//i set button id 5000
When i try to getId in end of the onPostExecute method, android don't find that id. And i also can't get that id from onCreate because when app starts that buttun does not exist.
And i created hackButton for try to get id from hackButton's onClickListener, id returns successfully because onpostexecute method's finished and now that id exist but i don't want to use this way.
btn_devam = (Button) findViewById(R.id.button_ileri);
btn_devam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button x = (Button) findViewById(5000);
x.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(this, "tag "+v.getTag()+"id "+v.getId(), Toast.LENGTH_SHORT).show();
}
});
}
});
So how can i get button's id which i created programmatically after onPostExecute finished?
I want to use this code;
Button x = (Button) findViewById(5000);
I cannot use that in oncreate, and also end of the onpostexecute. So how can i get that specific id after that created.
I think you are missing the reference of the view that contains that Button.
yourView.findViewById("Id to search");
yourview is the reference of parent view of your button i.e V in your function argument.
I've solved!
I've created thread like this in on create
private Thread mMainThread;
mMainThread = new Thread(){
#Override
public void run(){
try{
synchronized (this) {
wait(2000);
try{
Button x = (Button) findViewById(5000);
x.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(BiletSecim.this, "tag "+v.getTag()+" id "+v.getId(), Toast.LENGTH_SHORT).show();
}
});
}catch(Exception e){
}
}
}catch (Exception e) {
}
}};
Then at the end of onpostexecute method i start the thread
mMainThread.start();
2000 miliseconds is okay for me.

android can't close dialog when run socket

I have some problem. Dialog.dismiss() does not work.
I want to input ip, username, password to login WinServer 2003. When I clicked Submit button, the dialog can't be closed. To be noted, my Thread-socket able to retrieve messages from Server and send messages back to Server. The Dialog can only be closed When the Thread-socket got error.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jiemian);
netInit();
JieMianActivity.jiemian = this;
LayoutInflater factory = LayoutInflater.from(JieMianActivity.this);
View view = factory.inflate(R.layout.login, null);
dialog02 = new AlertDialog.Builder(JieMianActivity.this)
.setIcon(android.R.drawable.btn_star)
.setTitle("login")
.setView(view)
.setPositiveButton("submit", onclickButton)
.setNegativeButton("cancel", onclickButton).create();
dialog02.show();
}
private OnClickListener onclickButton = new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.v("which", which+"");
switch(which){
case Dialog.BUTTON_POSITIVE:
dialog.dismiss();//doesn't work , cann't close dialog.
EditText ip = (EditText) findViewById(R.id.ip);
EditText username = (EditText) findViewById(R.id.username);
EditText password = (EditText) findViewById(R.id.password);
new Connect(JieMianActivity.jiemian).run();//do some socket thing
break;
case Dialog.BUTTON_NEGATIVE:
dialog.dismiss();
JieMianActivity.jiemian.finish();
break;
}
}
};
This is my Thread:
class Connect extends Thread{
private JieMianActivity jiemain;
public Connect(JieMianActivity jiemian){
this.jiemain = jiemian;
}
public void run(){
//Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
try {
Display display = getWindowManager().getDefaultDisplay();
InputStream is = getResources().getAssets().open(
connect2RDP.mapFile);
sfv = (SurfaceView) findViewById(R.id.surfaceView);
sfh = sfv.getHolder();
sfh.addCallback(JieMianActivity.jiemian);
if (conn.connect("192.168.10.134", "Adminstrator", "123",
display.getWidth(), display.getHeight(), 3389, is)) {
Log.v("login", "success");
//dialog02.dismiss();
Log.v("login", "ok");
canvas = new MyCanvas();
canvas.setRop(new RasterOp());
canvas.setHeight(Options.height);
canvas.setWidth(Options.width);
canvas.setRight(Options.width - 1);
canvas.setBottom(Options.height - 1);
canvas.setBackstore(new WrappedImage(Options.width,
Options.height, JieMianActivity.jiemian));
canvas.setJiemian(JieMianActivity.jiemian);
canvas.setSurView(sfv);
canvas.setSurHolder(sfh);
conn.doconnect(JieMianActivity.jiemian);// 启动RDP
// init();
}
} catch (OrderException e) {
} catch (Exception e) {
}
}
};
You need to change your code to start a Thread, You need to call the method start() - that will execute the run() method written in that Thread.
So,
Invoke Connect.start() instead of Connect.run() inside your onClick handler.
I think you should close your alert dialog in UI thread else it wont work. You can do this in two ways : 1. Use message handler 2. Use RunOnUiThread. Sample for your reference :
1.
messageHandler.sendEmptyMessageDelayed(unique_id, 500);
private Handler messageHandler = new Handler()
{
#Override
public void handleMessage(Message msg) {
switch(msg.what) {
case unique_id:
// do here
break;
}
}
};
2.
Runnable hide_ui = new Runnable() {
#Override
public void run() {
// do here
}
};
runOnUiThread(hide_ui);

Android Dialog return String?

Hi I am popping up dialog to take comments from user. And returning a value according to that. That "rcomment" is a global variable. And it returns null. This is not working. What am I doing wrong ?
public String getDoNotBoardDialog(final int groupposition)
{
final Dialog dia = new Dialog(this);
dia.requestWindowFeature(Window.FEATURE_NO_TITLE);
dia.setContentView(R.layout.donotboard);
final EditText donotedit = (EditText) dia.findViewById(R.id.donotboardcomment);
donotedit.setText("");
Button button1 = (Button) dia.findViewById(R.id.donotboardbutton);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
r = donotedit.getText().toString();
String boardingComment = getString(R.string.donotboard) + " " + r;
PostCommentForAC(groupposition, boardingComment);
Intent intent = new Intent(getBaseContext(), TestExList.class);
intent.putExtra("EmpID", empid);
startActivity(intent);
rcomment = "true";
dia.cancel();
}
});
Button button2 = (Button) dia.findViewById(R.id.boardbutton);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
rcomment = "false";
dia.cancel();
}
});
dia.show();
return rcomment;
}
The getDoNotBoardDialog will initial return rcomment as null. rcomment will only be changed to "true" or "false" when the onClickListeners are fired. They are fired not when getDoNotBoardDialog is run, but after that, whenever the onClickListeners are fired.
Whatever you want to happen when rcomment is changed to "true" or "false" should be placed in the onClick methods. So if you want to check what rcomment is after a user clicks, do it there.
Edit: dont use below code. It will kill your app (ANR).
You would have to wait before you can return something. A quick (but really dirty) solution would be to add some wait/notify mechanism like so: (written blind so might contain some errors).
public String getDoNotBoardDialog(final int groupposition) {
// some Object to wait on
final Object waitOnMe = new Object();
final Dialog dia = new Dialog(this);
dia.requestWindowFeature(Window.FEATURE_NO_TITLE);
dia.setContentView(R.layout.donotboard);
final EditText donotedit = (EditText) dia.findViewById(R.id.donotboardcomment);
donotedit.setText("");
Button button1 = (Button) dia.findViewById(R.id.donotboardbutton);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
r = donotedit.getText().toString();
String boardingComment = getString(R.string.donotboard) + " " + r;
PostCommentForAC(groupposition, boardingComment);
Intent intent = new Intent(getBaseContext(), TestExList.class);
intent.putExtra("EmpID", empid);
startActivity(intent);
rcomment = "true";
dia.cancel();
// stop waiting.
synchronized(waitOnMe) {
waitOnMe.notify();
}
}
});
Button button2 = (Button) dia.findViewById(R.id.boardbutton);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
rcomment = "false";
dia.cancel();
// stop waiting.
synchronized(waitOnMe) {
waitOnMe.notify();
}
}
});
dia.show();
// this wait's until someone calls notify
synchronized (waitOnMe) {
try {
waitOnMe.wait();
} catch (InterruptedException e) {}
}
return rcomment;
}
It's problematic though. You could miss the notify() and thus never stop waiting (e.g. when you close the dialog via the "back" button). A much cleaner and safer solution would be to use some Callback mechanism (you call some method in your program from each onClick) to get a value from the dialog.
In you application
the program flows to
return rcomment;
directly after going to
dia.show();
Remember it does not wait for the button to be clicked before it goes to the return statement!!! It goes to return statement directly after the dialog is shown (before the button is clicked)
Try using this string.equals(data) it should find out if the string is the same. Since rcomment is a string. Also like Soham said it will not update only until it is clicked.
I suggest that in the future you should change to Boolean rcomment. Since it only looks like you are doing either true or false status.

Categories

Resources