switch-case does not work properly - java

i the below posted code, when I leave the field ip blank/empty and give values to the other fields, the toast always gives message the KATimer is invalid or missing.
i expected to see a toast showing with a message indicating the empty field,but the below code, if any field is empty, it always says KATimer is invalid or empty.
why that is happeneing, i am missing something
Code:
btnStubView_Connect:
btnStubView_Connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (isValidMQTTConfigs(etStubView_ip) &&
isValidMQTTConfigs(etStubView_port) &&
isValidMQTTConfigs(etStubView_ClientID) &&
isValidMQTTConfigs(etStubView_KATimer)) {
Log.d(TAG, "#btnStubView_ConnectListener(): all entries are valid");
setCSession(cbStubView_CS.isChecked()); // set the current state of the cleanSession checkBox.
addToContentValues();
Log.d(TAG, "#btnStubView_ConnectListener(): all entries added toContentValues");
} else {
Log.w(TAG, "#btnStubView_ConnectListener(): one or more entry(s) is invalid or left blank.");
}
}
});
isValidMQTTConfigs:
protected boolean isValidMQTTConfigs(View view) {
// TODO Auto-generated method stub
boolean valid = false;
String viewName = "";
switch(view.getId()) {
case R.id.etSubView_ip:
viewName = "IP";
if (isDuly( ((EditText) view).getText().toString())) {
this.setIP(((EditText) view).getText().toString());
return valid = true;
}
case R.id.etSubView_port:
viewName = "Port";
if (isDuly( ((EditText) view).getText().toString())) {
this.setPort(((EditText) view).getText().toString());
return valid = true;
}
case R.id.etSubView_clientID:
viewName = "clientID";
if (isDuly( ((EditText) view).getText().toString())) {
this.setClienID(((EditText) view).getText().toString());
return valid = true;
}
case R.id.etSubView_KATimer:
viewName = "KAtimer";
if (isDuly( ((EditText) view).getText().toString())) {
this.setKATimer(((EditText) view).getText().toString());
return valid = true;
}
}
Log.w(TAG, "#checkMQTTConfigs(): " + viewName + " is invalid or missing");
Toast.makeText(getActivity(), viewName + " is invalid or missing", Toast.LENGTH_SHORT).show();
return valid;
}
isDuly:
private boolean isDuly(String text) {
// TODO Auto-generated method stub
if (text.trim().equals("")) {
return false;
} else {
return true;
}
}

You are not using break; after every case which causes the cases below to execute even if you do not want them to. For eg, this is correct :-
switch(int){
case 1:
break;
case 2:
break;
}
and this will cause unexpected output though it is not wrong:-
switch(int){
case 1:
case 2:
}
Omitting break will cause execution of case 2 after executing case 1.

You seem to be missing several break statements.
Switch(X){
case 1: doOne();
case 2: doTwo();
case 3: doThree();
}
the waterfall flow makes sure that if X is 2, both doTwo and doThree will be executed. If X is 1, all three methods will be executed.
If you want only the linked method to be called, change the code into:
Switch(X){
case 1: doOne(); break;
case 2: doTwo(); break;
case 3: doThree(); break;
}

Related

Why is the text in TextViews changing two times when I am calling it only once at a time?

I know setText just changes the text only once but I can't seem to find the reason why the text in it changes before I move on to the next question in the quizActivity
What I have made is an app with one activity in it which has a quiz in it, a question is displayed along with 4 options. When the user selects an option, if that option is correct then it becomes green and red otherwise and additionally, I then open a dialog box showing whether the answer was right or wrong and then the question is changed when the user clicks Next on the dialog box.
But what is happening that when the user selects an option, in between the process of clicking the option and then clicking next on the dialog box, the text in the questions and the options changes and I can't seem to figure out why is that happening. In total, the question and options change two times when they should change only once, the unexpected change is when the user clicks on an option and the dialog box opens.
Here's the code:
#Override
public void onClick(View view) {
int selectedOption = 0;
switch (view.getId()) {
case R.id.option_1_tile:
selectedOption = 1;
break;
case R.id.option_2_tile:
selectedOption = 2;
break;
case R.id.option_3_tile:
selectedOption = 3;
break;
case R.id.option_4_tile:
selectedOption = 4;
break;
default:
}
checkAnswer(selectedOption, view);
}
Here's the function which checks the answer:
private void checkAnswer(int selectedOption, View view) {
if (selectedOption == selected_questions.get(quesNum).getAnswer()) {
//Right Answer
(view).setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
quizReference.child(selected_questions.get(quesNum).getId()).child("correct_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getCorrect_attempts()) + 1));
quizReference.child(selected_questions.get(quesNum).getId()).child("total_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getTotal_attempts()) + 1));
score++;
correctDialog();
} else {
//Wrong Answer
(view).setBackgroundTintList(ColorStateList.valueOf(Color.RED));
quizReference.child(selected_questions.get(quesNum).getId()).child("total_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getTotal_attempts()) + 1));
switch (selected_questions.get(quesNum).getAnswer()) {
case 1:
options[0].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 2:
options[1].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 3:
options[2].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 4:
options[3].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
}
wrongDialog ();
}
}
Here's the function which changes the question:
private void changeQuestion() {
resetColor ();
if (quesNum < selected_questions.size() - 1) {
quesNum++;
playAnim(question, 0, 0);
playAnim(option1_text, 0, 1);
playAnim(option2_text, 0, 2);
playAnim(option3_text, 0, 3);
playAnim(option4_text, 0, 4);
qCount.setText(String.valueOf(quesNum + 1) + "/" + String.valueOf(selected_questions.size()));
} else {
// Go to Score Activity
Intent intent = new Intent(quizActivity.this, scoreActivity.class);
intent.putExtra("SCORE", String.valueOf(score) + "/" + String.valueOf(selected_questions.size()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Here's the function which sets the text and animation:
private void playAnim(final View view, final int value, final int viewNum) {
view.animate().alpha(value).scaleX(value).scaleY(value).setDuration(500)
.setStartDelay(100).setInterpolator(new DecelerateInterpolator())
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
if (value == 0) {
switch (viewNum) {
case 0:
((TextView) view).setText(selected_questions.get(quesNum).getQuestion());
break;
case 1:
((TextView) view).setText(selected_questions.get(quesNum).getOption1());
break;
case 2:
((TextView) view).setText(selected_questions.get(quesNum).getOption2());
break;
case 3:
((TextView) view).setText(selected_questions.get(quesNum).getOption3());
break;
case 4:
((TextView) view).setText(selected_questions.get(quesNum).getOption4());
break;
}
if (viewNum != 0)
(view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#E99C03")));
playAnim(view, 1, viewNum);
}
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
Here's the code for the dialog boxes:
public void wrongDialog() {
final Dialog dialogWrong = new Dialog(quizActivity.this);
dialogWrong.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogWrong.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogWrong.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogWrong.setContentView(R.layout.dialog_wrong);
dialogWrong.setCancelable(false);
dialogWrong.show();
TextView wrongText = (TextView) dialogWrong.findViewById(R.id.wrongText);
Button buttonNext = (Button) dialogWrong.findViewById(R.id.dialogNext);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogWrong.dismiss();
//reset the color of buttons back to white
resetColor();
//Change question
changeQuestion();
}
});
}
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(quizActivity.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();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
Button buttonNext = (Button) dialogCorrect.findViewById(R.id.dialogNext);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//reset the color of buttons back to white
resetColor();
//it will increment the question number
changeQuestion();
}
});
}
I have tried to explain it to my best ability though I would be glad to answer any additional information/code you may want. Also, this is the link for the project if you have the time to run it and understand the problem better.
I have checked your code. you have placed an addValueEventListener in setUpdates method. When you select an option, you update the firestore database by setting fields like total attempts. As a result, eventListener gets triggered and "selectQuestionSet" function is called.
Hence, every time you select an option, selectQuestionSet function is called. You should make sure that its called only once at the start.

While sliding my finger over a button or object, the object acts as if it were getting pushed?

I tried to explain my issue through image, what i am looking for.
I tried
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = MotionEventCompat.getActionMasked(event);
switch (action) {
case (MotionEvent.ACTION_DOWN):
// Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE):
// Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP):
// Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_CANCEL):
// Log.d(DEBUG_TAG,"Action was CANCEL");
return true;
case (MotionEvent.ACTION_OUTSIDE):
// Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
// "of current screen element");
return true;
default:
return super.onTouchEvent(event);
}
I worked on ACTION_DOWN & ACTION_MOVE but didn't find what I am looking for

how to use onClick function within a condition or calling it in a function? Android

i want to use my PlayerClick(view v) inside a if condition . but it gives me null Exception. it has to retrieve button id.
//Main Code where i wan to call
while (gameLoop > 0){
while(PlayerClick(null) != 1){
if( WinnerCheck(currentUser.getSymbolValue()) == 1 || WinnerCheck(currentUser.getSymbolValue()) == 0 ){
return currentUser;
}
if (gameLoop % 2 == 0)
currentUser = me;
else
currentUser = opponent;
}
gameLoop--;
}
Function Is here
public int PlayerClick(View v) {
//
switch(v.getId()){
case R.id.btnone:
return -1;
case R.id.btntwo:
return -1;
}
return 1;
}
Aim to do this just to pause a while loop while right button is being clicked
im using android:onclick = "PlayerClick" for four buttons in XML
i want to use my PlayerClick(view v) inside a if condition . but it
gives me null Exception.
Because you are passing null to PlayerClick method.
To get it work you should pass Button view which is pressed by user as parameter in PlayerClick method.
findViewById(android.R.id.yourlayout) pass this in PlayerClick()
like
PlayerClick(findViewById(android.R.id.yourlayout))
Do
button.setOnClickListener(this);
Let your activity implement OnClickListener
And when you get onClick(View v) of activity, do as below
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_nativex:
PlayerClick(v);
break;
default:
break;
}
}
public int mPlayerClick;
public void PlayerClick(View v) {
int viewId = v.getId();
if (viewId == R.id.btnone) { mPlayerClick = -1; }
if (viewId == R.id.btntwo) { mPlayerClick = -1; }
else mPlayerClick = 1;
}
And then.
while (gameLoop > 0){
while(mPlayerClick != 1){
...
I don't understand what you are trying to do though, so this might be wrong. This way mPlayerClick will be set to 1 (and stop your loop) only if the user clicks on some button that is not either btnone or btntwo.
Of course all of your buttons need to call PlayerClick() on click.

How to set values for Radio button in android?

I am getting the value from DB and setting it to the respective button in the below format. Is there any optimised way to do the same. All these radio buttons are inside a radio group.
if (bundlevalue.get(3).equalsIgnoreCase("Mr.")) {
rg_nametitle.check(R.id.mr);
} else if (bundlevalue.get(3).equalsIgnoreCase("Mrs.")) {
rg_nametitle.check(R.id.mrs);
} else if (bundlevalue.get(3).equalsIgnoreCase("Ms.")) {
rg_nametitle.check(R.id.ms);
} else {
rg_nametitle.check(R.id.messrs);
}
You can try as follows...
String value = bundlevalue.get(3)
Resources res = getResources();
if (value.equalsIgnoreCase("Mr.") || value.equalsIgnoreCase("Mrs.") || value.equalsIgnoreCase("Ms.")) {
String[] splitedValue = value.toLowerCase ().split(".");
int id = res.getIdentifier(splitedValue[0], "id", getContext().getPackageName());
rg_nametitle.check(id);
} else {
rg_nametitle.check(R.id.messrs);
}
In case if you use XML attribute like this :
<RadioGroup
...
...
android:checkedButton="#+id/IdOfTheRadioButtonInsideThatTobeChecked"
... >....</RadioGroup>
or you can use switch-case statement like this :
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
}
Use switch statement. Although, there is nothing big difference in using if-else or switch, you can go ahead with whichever is more readable to you.
public enum Title
{
Mr, Mrs, Ms;
}
String title = bundlevalue.get(3).equalsIgnoreCase("Mr.");
switch(Title.valueOf(title)) {
case Mr:
rg_nametitle.check(R.id.mr);
break;
case Ms:
rg_nametitle.check(R.id.ms);
break;
case Mrs:
rg_nametitle.check(R.id.mrs);
break;
default:
break;
}

why getEdgeFlags() always return 0

I want to detect the touch edge in onTouchEvent function for my view, but getEdgeFlags() always return 0 in my Nexus S 4.1.1, anyone can help me? thanks advance.
#Override
public boolean onTouchEvent(MotionEvent event) {
int edgeFlags = event.getEdgeFlags();
//edgeFlags alway 0!
switch (edgeFlags) {
case MotionEvent.EDGE_LEFT:
Log.i("tag", "EDGE_LEFT");
break;
case MotionEvent.EDGE_RIGHT:
Log.i("tag", "EDGE_RIGHT");
break;
case MotionEvent.EDGE_TOP:
Log.i("tag", "EDGE_TOP");
break;
case MotionEvent.EDGE_BOTTOM:
Log.i("tag", "EDGE_BOTTOM");
break;
default:
Log.i("tag", "" + edgeFlags);
break;
}
return super.onTouchEvent(event);
}
I solved the problem with add four button to trigger four direction!

Categories

Resources