Pass bundle to if-statement - java

Activity Claims----> has 2 button and a textView (get the total amount)
Activity Project1 and Petrol-----> one editText and a save button
Activity Claims
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(a1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(a2);
}
});
public void AlertDialogRadio(final int k) {
final CharSequence[] ClaimsModel = {"Project1", "Petrol"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
intent.putExtra("k",k);
startActivityForResult(intent, 0);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
intent.putExtra("k", k);
startActivityForResult(intent, 1);
}
** Either Project1 or Petrol, depends...)**
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
text= (EditText)findViewById(R.id.editText1);
Button save=(Button)findViewById(R.id.button12);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = new Intent();
l="A";
text = text.getText().toString();
returnIntent.putExtra("text", text);
returnIntent.putExtra("l", l);
final int k1 = getIntent().getExtras().getInt("k");
returnIntent.putExtra("k1", k1);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
#Override
public void onBackPressed()
{
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
}
Is it possible to pass a bundle to if statement? I want to pass a value to another cases and finally total up the two values. How can I achieve this? Now I only get the value as and bs, but not value amount. I do believe it need to add a bundle to both if statement...
Continue Claims.java....
public void onActivityResult(int requestCode, int resultCode, Intent data) {
int button = data.getIntExtra("k1", 0); // to check which button was pressed
long a=0;
long as=0;
long bs=0;
String result;
String result1;
if (button == 1) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
String b = data.getStringExtra("l");
as=Long.parseLong(result);
c.setText(" " + b + "------" + "RM " + result);
Toast.makeText(getActivity(),as+"", Toast.LENGTH_LONG).show();
break;
case 1:
result = data.getStringExtra("text");
String b1 = data.getStringExtra("l");
as=Long.parseLong(result);
c.setText(" " + b1 + "------" + "RM " + result);
Toast.makeText(getActivity(),as+"", Toast.LENGTH_LONG).show();
break;
}
if(button==2)
{
switch (requestCode) {
case 0:
result1 = data.getStringExtra("text");
String b = data.getStringExtra("l");
bs=Long.parseLong(result1);
d.setText(" " + b + "------" + "RM " + result1);
Toast.makeText(getActivity(),bs+"", Toast.LENGTH_LONG).show();
break;
case 1:
result1 = data.getStringExtra("text");
String b1 = data.getStringExtra("l");
bs=Long.parseLong(result1);
d.setText(" " + b1 + "------" + "RM " + result1);
Toast.makeText(getActivity(),bs+"", Toast.LENGTH_LONG).show();
break;
}
}
else if(requestCode==CAMERA_REQUEST_CODE)
{
}
long amount=as+bs;
Toast.makeText(getActivity(),amount+"", Toast.LENGTH_LONG).show();
I refer How can i pass a string value, that has been created in an if statement, through a bundle inside another if statement? but the answer is quite unclear for me.
The image for Claims
The toast should display 1 12 13 but I get 1 12 12. It seems like the value 1 cannot be added!

You should store the values you get passed in your onActivityResult in a variable of your Activity, and then directly read these variables for the Toast.
public class Claims{
long a, as, bs;
public void onActivityResult(int requestCode, int resultCode, Intent data) {
int button = data.getIntExtra("k1", 0);
String result;
if (button == 1) {
result = data.getStringExtra("text");
as=Long.parseLong(result);
} else if(button==2) {
result = data.getStringExtra("text");
bs=Long.parseLong(result1);
}
long amount=as+bs;
Toast.makeText(getActivity(),amount+"", Toast.LENGTH_LONG).show();
}
}
You still need to initialise your values according to your standards though.

Related

I want to show a toast error msg if the edittext section is blank when the button is pressed (Android Studio)

I made a simple calculator app in android studio but the app crashes when no value is entered in the edittext section.
I want to show a toast msg when no value is entered in the edittext section.
Please check this issue and guide me how to fix this and add toast.
here n1 and n2 is the id of edittext.
MainActivity (code):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
n1 = findViewById(R.id.n1);
n2 = findViewById(R.id.n2);
add = findViewById(R.id.add);
sub = findViewById(R.id.sub);
multi = findViewById(R.id.multi);
div = findViewById(R.id.div);
tv = findViewById(R.id.tv);
// addition part
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int p,q,r;
p = Integer.parseInt(n1.getText().toString());
q = Integer.parseInt(n2.getText().toString());
r = p+q;
tv.setText("Result is " + r);
Toast.makeText(MainActivity.this, "Successfully Calculated", Toast.LENGTH_SHORT).show();
}
});
//subtraction part
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int p,q,r;
p = Integer.parseInt(n1.getText().toString());
q = Integer.parseInt(n2.getText().toString());
r = p-q;
tv.setText("Result is " + r);
Toast.makeText(MainActivity.this, "Successfully Calculated", Toast.LENGTH_SHORT).show();
}
});
// multiplication part
multi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int p,q,r;
p = Integer.parseInt(n1.getText().toString());
q = Integer.parseInt(n2.getText().toString());
r = p*q;
tv.setText("Result is " + r);
Toast.makeText(MainActivity.this, "Successfully Calculated", Toast.LENGTH_SHORT).show();
}
});
//divison part
div.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int p,q,r;
p = Integer.parseInt(n1.getText().toString());
q = Integer.parseInt(n2.getText().toString());
r = p/q;
tv.setText("Result is " + r);
Toast.makeText(MainActivity.this, "Successfully Calculated", Toast.LENGTH_SHORT).show();
}
});
}
}
Do the same in all the other OnClickListner
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int p,q,r;
if(!n1.getText().toString().equals("") && !n2.getText().toString().equals("")) {
p = Integer.parseInt(n1.getText().toString());
q = Integer.parseInt(n2.getText().toString());
r = (p + q);
Toast.makeText(MainActivity.this, "Successfully Calculated", Toast.LENGTH_SHORT).show();
tv.setText("Result is " + r);
}else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
You could do a preliminary check to see if any text was entered like
if(n1.getText()) ....
Ideally you'd want to surround the ParseInt() with a try{}..catch{} block and handle any errors there to stop the app from crashing.
int n1Value = n1.getText().toString();
int n2Value = n2.getText().toString();
p = n1Value !=null&&!n1Value.isEmpty()? Integer.parseInt(n1Value):0
p = n2Value !=null&&!n2Value.isEmpty()? Integer.parseInt(n2Value):0
Add this in your click listeners. the crash is happening because you don't have any null check.

Calling a method after returning to the first activity

I am a complete newbie in the coding world. Currently, I am trying to develop a quiz app and am stuck with an issue. A little brief:- There are 2 activities 1. Questions activity 2. Score activity. What I want is to display score after each question and change the question when I return to the Questions activity. I have created a method in Questions activity named ChangeQuestion().
The issue I am facing is when the 1st question is answered correctly, the score activity is shown and instead of loading question 2, the question 1 is displayed again.
I am not sure if I am making any sense. Please let me know if any clarification/information is required.
Changequestion method
Part where ChnangeQuestion method is called
you quesNum variable will lose its current value when your activity is destroyed and recreated, so it gets its initial value (which maps to the first question) every time you leave the Question activity and come back.
So, you need to save the value of the current question before the Question activity is destroyed. There are several ways to do this.
One of which you can save it permanently using the SharedPreference.
In your Question activity
initiate the shared preference in onResume() method
SharedPreferences mPreferences;
int quesNum;
onResume() {
super.onResume();
mPreferences = getSharedPreferences("MySahredPrefs", MODE_PRIVATE);
quesNum = sharedPrefs.getInt("CURRENT_QUES", 0); // <<< getting the current question number from the shared preference, and set the default question number to 0
}
And whenever you change the current question value, set it in the SharedPreference, or you can do that in the Question activity onPause() method
#Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.putInt("CURRENT_QUES", quesNum); // <<<<<<<< setting the current question value to the shared preference
preferencesEditor.apply();
}
UPDATE:
Solving it by reserving the value of quesNum into the Score activity with startActivityForResult() instead of startActivity() and return it back to Question activity via onActivityResult()
So change startActivity() at the Questions activity to startActivityForResult(), and put the current question value quesNum to the intent.
public class QuestionsActivity ... {
public static final int CODE = 101;
private void checckAnswer(...) {
// ....
intent.putExtra("QUES_NUM", quesNum);
startActivityForResult(intent, CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CODE && resultCode == RESULT_OK) {
quesNum = data.getExtras().getInt("QUES_NUM");
}
}
}
In the Score activity, use the same intent you sent by the Questions activity by using getIntent(), and this intent already contains the current question which was stored in quesNum in Question activity.
public class ScoreActivity ... {
// ....
Intent intent = getIntent();
setResult(RESULT_OK, intent);
finish();
}
UPDATE 2
In Score activity, after the Handler timer is up, you start a brand-new intent using intent constructor that will result in resetting the questNum to the first question, instead you need to setResult() within the handler.
Also you no longer need to setResult() outside the handler, because you already need some delay provided by the handler.
You also need to add finish() after setResult
So the Score activity code will be:
public class ScoreActivity extends AppCompatActivity {
private Handler mHandler = new Handler();
private Button score5k;
private Button score10k;
private Button score20k;
private int scoreholder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
score5k = (Button) findViewById(R.id.score1);
score10k = (Button) findViewById(R.id.score2);
score20k = (Button) findViewById(R.id.score3);
Bundle extras = getIntent().getExtras();
int score = extras.getInt("Score");
int question = extras.getInt("QUES_NUM");
if (extras != null) {
if (score == 1) {
score5k.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
if (score == 2) {
score5k.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
score10k.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
if (score == 3) {
score5k.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
score10k.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
score20k.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
}
}
} else {
}
}
// Intent intent = getIntent();
// intent.putExtra("Quesnumber", question);
// setResult(RESULT_OK, intent);
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
// Intent intent = new Intent(ScoreActivity.this, QuestionActivity.class);
// startActivity(intent);
setResult(RESULT_OK, getIntent());
finish();
}
}, 4000);
}
}
In Question Activity you're using the wrong key of the Question number, so replace
quesNum = data.getExtras().getInt("Quesnumber");
With
quesNum = data.getExtras().getInt("QUES_NUM");
In checkAnswer() method you call changeQuestion() after both branches of the if/else statement, but you actually want it only in the else branch, so move it to the else branch as below
private void checkAnswer(int selectedOption, View view) {
if (selectedOption == questionList.get(quesNum).getCorrectAns()) {
//Right answer
((Button) view).setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
score++;
Intent intent = new Intent(QuestionActivity.this, ScoreActivity.class);
intent.putExtra("Score", score);
intent.putExtra("QUES_NUM", quesNum);
startActivityForResult(intent, CODE);
} else {
//Wrong answer
((Button) view).setBackgroundTintList(ColorStateList.valueOf(Color.RED));
switch (questionList.get(quesNum).getCorrectAns()) {
case 1:
option1.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 2:
option2.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 3:
option3.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 4:
option4.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
}
changeQuestion();
}
}
The entire Question activity with these changes will be
public class QuestionActivity extends AppCompatActivity implements View.OnClickListener {
public TextView question;
public Button option1;
public Button option2;
public Button option3;
public Button option4;
private List<Question> questionList;
private int score;
private int quesNum;
public static final int CODE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
// setting buttons and text view. Linking with layout file
question = findViewById(R.id.question);
option1 = findViewById(R.id.option1);
option2 = findViewById(R.id.option2);
option3 = findViewById(R.id.option3);
option4 = findViewById(R.id.option4);
score = 0;
option1.setOnClickListener(this);
option2.setOnClickListener(this);
option3.setOnClickListener(this);
option4.setOnClickListener(this);
getQuestionList();
}
private void getQuestionList() {
questionList = new ArrayList<>();
questionList.add(new Question("Question 1", "A", "B", "C", "D", 2));
questionList.add(new Question("Question 2", "B", "C", "D", "A", 2));
questionList.add(new Question("Question 3", "C", "D", "A", "B", 2));
questionList.add(new Question("Question 4", "D", "B", "A", "C", 2));
questionList.add(new Question("Question 5", "A", "C", "B", "D", 2));
questionList.add(new Question("Question 6", "C", "B", "A", "D", 2));
setQuestion();
}
private void setQuestion() {
question.setText(questionList.get(0).getQuestion());
option1.setText(questionList.get(0).getOptionA());
option2.setText(questionList.get(0).getOptionB());
option3.setText(questionList.get(0).getOptionC());
option4.setText(questionList.get(0).getOptionD());
quesNum = 0;
}
#Override
public void onClick(View view) {
int selectedOption = 0;
switch (view.getId()) {
case R.id.option1:
selectedOption = 1;
break;
case R.id.option2:
selectedOption = 2;
break;
case R.id.option3:
selectedOption = 3;
break;
case R.id.option4:
selectedOption = 4;
break;
}
checkAnswer(selectedOption, view);
}
private void checkAnswer(int selectedOption, View view) {
if (selectedOption == questionList.get(quesNum).getCorrectAns()) {
//Right answer
((Button) view).setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
score++;
Intent intent = new Intent(QuestionActivity.this, ScoreActivity.class);
intent.putExtra("Score", score);
intent.putExtra("QUES_NUM", quesNum);
startActivityForResult(intent, CODE);
} else {
//Wrong answer
((Button) view).setBackgroundTintList(ColorStateList.valueOf(Color.RED));
switch (questionList.get(quesNum).getCorrectAns()) {
case 1:
option1.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 2:
option2.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 3:
option3.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 4:
option4.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
}
changeQuestion();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE && resultCode == RESULT_OK) {
quesNum = data.getExtras().getInt("QUES_NUM");
changeQuestion();
}
}
public void changeQuestion() {
if (quesNum < questionList.size() - 1) {
quesNum++;
playAnim(question, 0, 0);
playAnim(option1, 0, 1);
playAnim(option2, 0, 2);
playAnim(option3, 0, 3);
playAnim(option4, 0, 4);
} else {
//Display Score
Intent intent = new Intent(QuestionActivity.this, ScoreActivity.class);
intent.putExtra("Score", score);
startActivityForResult(intent, CODE);
}
}
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 animator) {
}
#SuppressLint("ResourceAsColor")
#Override
public void onAnimationEnd(Animator animator) {
if (value == 0) {
switch (viewNum) {
case 0:
((TextView) view).setText(questionList.get(quesNum).getQuestion());
break;
case 1:
((Button) view).setText(questionList.get(quesNum).getOptionA());
break;
case 2:
((Button) view).setText(questionList.get(quesNum).getOptionB());
break;
case 3:
((Button) view).setText(questionList.get(quesNum).getOptionC());
break;
case 4:
((Button) view).setText(questionList.get(quesNum).getOptionD());
break;
}
if (viewNum != 0) {
((Button) view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#4848FE")));
}
playAnim(view, 1, viewNum);
} else {
}
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
}
}

Sending a few values using Bundle

I'm trying to pass values from MainActivity
buttonCheckAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!allAnswersChecked())
intent.putExtra("KEY_ALL_CHECKED", R.string.text_not_checked);
else if (checkAnswers())
intent.putExtra("KEY_ANSWER", R.string.Good_answer);
else
intent.putExtra("KEY_ANSWER", R.string.Wrong_answer);
Bundle bundle = new Bundle();
bundle.putString("KEY_ALL_CHECKED",getString(R.string.text_not_checked));
startActivity(intent);
}
});
to AnswerActivity (which partly I've already done)
TextView textViewDisplayResult = (TextView) findViewById(R.id.text_view_display_result);
Bundle bundle = getIntent().getExtras();
String name = bundle.getString("KEY_ALL_CHECKED",getString(R.string.text_not_checked));
textViewDisplayResult.setText(name);
But how to send the other two "KEY_ANSWER" values from MainActivity? By simply adding something to this line?
String name = bundle.getString("KEY_ALL_CHECKED",getString(R.string.text_not_checked));
And another question
The "KEY_ALL_CHECKED" has a boolean value in its method
private boolean allAnswersChecked() {
for (boolean radioAnswer : isAnswered) {
if (!radioAnswer) {
return false;
}
}
return true;
}
and in AnswerActivity I pass it using getString. Is that ok? I'm getting a bit confused (the code works).
Thank you in advance.
POST UPDATE
private static int NUMBER_OF_QUESTIONS = 3;
static boolean[] answer = new boolean[NUMBER_OF_QUESTIONS];
static boolean[] checked = new boolean[NUMBER_OF_QUESTIONS];
static boolean[] isAnswered = new boolean[NUMBER_OF_QUESTIONS];
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), fragmentList);
viewPager.setAdapter(adapter);
final Intent intent = new Intent(MainActivity.this, AnswerActivity.class);
buttonCheckAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (allAnswersChecked())
{
if (checkAnswers())
intent.putExtra("KEY_ANSWER", R.string.Good_answer);
else
intent.putExtra("KEY_ANSWER", R.string.Wrong_answer);
}
else
intent.putExtra("KEY_ANSWER", R.string.text_not_checked);
startActivity(intent);
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == (NUMBER_OF_QUESTIONS - 1))
checkSelected();
else if (buttonCheckAnswer.getVisibility() == View.VISIBLE)
buttonCheckAnswer.setVisibility(View.GONE);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public static void checkSelected() {
for (boolean radioChecked : checked) {
if (radioChecked) {
buttonCheckAnswer.setVisibility(View.VISIBLE);
break;
}
}
}
private boolean checkAnswers() {
for (boolean radioAnswer : answer) {
if (!radioAnswer) {
return false;
}
}
return true;
}
private boolean allAnswersChecked() {
for (boolean radioAnswer : isAnswered) {
if (!radioAnswer) {
return false;
}
}
return true;
}
AnswerActivity code
package make.appaplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class AnswerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
TextView textViewDisplayResult = (TextView) findViewById(R.id.text_view_display_result);
String answer = "";
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
if (bundle.containsKey("KEY_ANSWER"))
answer = bundle.getString("KEY_ANSWER");
}
Log.d("SUCCESS", "answer: " + answer);
textViewDisplayResult.setText(answer);
}
}
Here is a bit changed buttonCheckAnswer method. It now gives me text "Good answer" and "Wrong answer" in the right way. Only "You haven't checked all answers" doesn't show at all when needed.
buttonCheckAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (allAnswersChecked()) {
intent.putExtra("KEY_ANSWER", "You haven't checked all answers");
}
if (checkAnswers())
intent.putExtra("KEY_ANSWER", "Good Answer");
else intent.putExtra("KEY_ANSWER", "Wrong Answer");
startActivity(intent);
}
});
In your MainActivity, modify your conditions as below:
buttonCheckAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AnswerActivity.class);
boolean isAllAnswered = allAnswersChecked();
Toast.makeText(getApplicationContext(), "isAllAnswered value is: " + isAllAnswered, Toast.LENGTH_SHORT).show();
if (isAllAnswered)
{
boolean isGoodAnswer = checkAnswers();
Toast.makeText(getApplicationContext(), "isGoodAnswer value is: " + isGoodAnswer, Toast.LENGTH_SHORT).show();
if (isGoodAnswer)
intent.putExtra("KEY_ANSWER", "Good Answer");
else
intent.putExtra("KEY_ANSWER", "Wrong Answer");
}
else
intent.putExtra("KEY_ANSWER", "You haven't checked all answers");
startActivity(intent);
}
});
In your AnswerActivity, get values as below:
String answer = "";
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
if (bundle.containsKey("KEY_ANSWER"))
answer = bundle.getString("KEY_ANSWER");
}
Log.d("SUCCESS", "answer: " + answer);
TextView textViewDisplayResult = (TextView) findViewById(R.id.text_view_display_result);
textViewDisplayResult.setText(answer);
Hope this will help~
Assuming you want to pass all the values, even is you have if..else if..else. "How to pass other two KEY_ANSWER? ..." Why are you using same key for both? Use different keys for both and add both strings to the bundle. Try following code:
Intent intent = new Intent(this, AnswerActivity.class);
Bundle extras = new Bundle();
extras.putString("KEY_ALL_CHECKED","YOUR_STRING_VALUE");
extras.putString("KEY_ANSWER_ONE","YOUR_STRING_VALUE");
extras.putString("KEY_ANSWER_TWO","YOUR_STRING_VALUE");
intent.putExtras(extras);
startActivity(intent);
and when you want to get extras, get three different Strings by their keys as following:
Bundle extras = getIntent().getExtras();
String str1 = extras.getString("KEY_ALL_CHECKED");
String str2 = extras.getString("KEY_ANSWER_ONE");
String str3 = extras.getString("KEY_ANSWER_TWO");
And you will get all strings in str1, str2 and str3.

How to check which button was pressed in startActivityForResult, override onActivityResult method?

I have three button (R.id.1, R.id.2, R.id.3) and three textView(a,b,c). How can I check which button was pressed onActivityResult so that the TextView can be setText accordingly to the button?
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode)
{
case 0:
//check which button was pressed
String b = data.getStringExtra("a");
//Apply setText(b);
}
break;
case 1:
//check which button was pressed
String result1=data.getStringExtra("text");
// Apply setText(result);
break;
case 2:
// check which button was pressed
String b2 = data.getStringExtra("a");
// Apply setText (b2);
break;
Example: In case 0, R.id.1 was pressed, so will be a.setText(b)....
If R.id.1 was pressed, a.setText()
If R.id.2 was pressed, b.setText()
If R.id.3 was pressed, c.setText()
Code
Button button1 = (Button) claims.findViewById(R.id.1);
Button button2 = (Button) claims.findViewById(R.id.2);
Button button3 = (Button)claims.findViewById(R.id.3);
a=(TextView)claims.findViewById(R.id.textView1);
b=(TextView)claims.findViewById(R.id.textView2);
c=(TextView)claims.findViewById(R.id.textView3);
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
button3.setOnClickListener(listener);
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
AlertDialogRadio();
}
};
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"Sunny", "Raining", "Cloudy"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select Weather");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Sunny.class);
startActivityForResult(intent, 0);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Rainy.class);
startActivityForResult(intent, 1);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), Cloudy.class);
startActivityForResult(intent, 2);
}
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode)
{
case 0:
//check which button was pressed
String b = data.getStringExtra("a");
//Apply setText(b);
}
break;
case 1:
//check which button was pressed
String result1=data.getStringExtra("text");
// Apply setText(result);
break;
case 2:
// check which button was pressed
String b2 = data.getStringExtra("a");
// Apply setText (b2);
break;
}
Edited
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivityForResult(intent, requestCode);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivityForResult(intent, requestCode);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), CarMainten.class);
startActivityForResult(intent, requestCode);
} else if (item == 3) {
Intent intent = new Intent(getActivity().getApplicationContext(), Medical.class);
startActivityForResult(intent, requestCode);
} else if (item == 4) {
Intent intent = new Intent(getActivity().getApplicationContext(), Other.class);
startActivityForResult(intent, requestCode);
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(getActivity(), "Not coeted ", Toast.LENGTH_LONG).show();
switch (requestCode) {
case requestCode1:
String result = data.getStringExtra("text");
String b = data.getStringExtra("a");
c.setText(" " + b + "------" + "RM " + result);
Toast.makeText(getActivity(), "Not completed ", Toast.LENGTH_LONG).show();
break;
case requestCode2:
String result1 = data.getStringExtra("text");
String b1 = data.getStringExtra("a");
c.setText(" " + b1 + "------" + "RM " + result1);
break;
case requestCode3:
String result2 = data.getStringExtra("text");
String b2 = data.getStringExtra("a");
c.setText(" " + b2 + "------" + "RM " + result2);
break;
}
}
int requestCode1 = 1;
int requestCode2 = 2;
int requestCode3 = 3;
Button b1 =(Button) findViewById(R.id.button1);
Button b2 =(Button) findViewById(R.id.button2);
Button b3 =(Button) findViewById(R.id.button3);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(requestCode1)
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(requestCode2)
}
});
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(requestCode3)
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == requestCode1){}//button 1
else if(resultCode == requestCode2){}//button 2
else if(resultCode == requestCode3){}//button 3
}
public void AlertDialogRadio(final int requestCode) {
final CharSequence[] ClaimsModel = {"Sunny", "Raining", "Cloudy"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select Weather");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Sunny.class);
startActivityForResult(intent, requestCode);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Rainy.class);
startActivityForResult(intent, requestCode);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), Cloudy.class);
startActivityForResult(intent, requestCode);
}
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
you can check with Request Code.
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
AlertDialogRadio(v.getId());
}
};
public void AlertDialogRadio(int id) {
final CharSequence[] ClaimsModel = {"Sunny", "Raining", "Cloudy"};
switch(id){
case R.id.1:
break;
case R.id.2:
break;
case R.id.3:
break;
}
Bundle bundle = new Bundle();
bundle.putString("key", "value");
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select Weather");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Sunny.class);
startActivityForResult(intent, 0, bundle);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Rainy.class);
startActivityForResult(intent, 1, bundle);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), Cloudy.class);
startActivityForResult(intent, 2, bundle);
}
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle bundle = data.getExtras();
// this can any data that you passed
String anyData = bundle.getString();
switch(requestCode)
{
case 0:
//check which button was pressed
String b = data.getStringExtra("a");
//Apply setText(b);
}
break;
case 1:
//check which button was pressed
String result1=data.getStringExtra("text");
// Apply setText(result);
break;
case 2:
// check which button was pressed
String b2 = data.getStringExtra("a");
// Apply setText (b2);
break;
}

RadioButton value duplicate with each other from different activities

I have this function that call RadioButton value from the Group.java to the Add.java. I use the same function on another activity called Status.java. Now, every time I click from either Group.java or Status.java, the result become duplicate. And every time I click the RadioButton, my EditText will dissappear.
Group.java
RadioGroup radiog1;
RadioButton radio1, radio2, radio3, radio4, radio5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group);
radiog1 = (RadioGroup) findViewById(R.id.radiog1);
radio1 = (RadioButton) findViewById(R.id.radio1);
radio2 = (RadioButton) findViewById(R.id.radio2);
radio3 = (RadioButton) findViewById(R.id.radio3);
radio4 = (RadioButton) findViewById(R.id.radio4);
radio5 = (RadioButton) findViewById(R.id.radio5);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .8), (int) (height * .6));
radio1.setOnClickListener(this);
radio2.setOnClickListener(this);
radio3.setOnClickListener(this);
radio4.setOnClickListener(this);
radio5.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent returnIntent = getIntent();
switch (v.getId()) {
case (R.id.radio1):
returnIntent.putExtra("GroupTag", "" + radio1.getText());
setResult(RESULT_OK, returnIntent);
finish();
break;
case (R.id.radio2):
returnIntent.putExtra("GroupTag","" + radio2.getText());
setResult(RESULT_OK, returnIntent);
finish();
break;
case (R.id.radio3):
returnIntent.putExtra("GroupTag", "" + radio3.getText());
setResult(RESULT_OK, returnIntent);
finish();
break;
case (R.id.radio4):
returnIntent.putExtra("GroupTag", "" + radio4.getText());
setResult(RESULT_OK, returnIntent);
finish();
break;
case (R.id.radio5):
returnIntent.putExtra("GroupTag","" + radio5.getText());
setResult(RESULT_OK,returnIntent);
finish();
break;
}
}}
Status.java
RadioButton rb1, rb2, rb3, rb4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .8), (int) (height * .6));
rb1 = (RadioButton) findViewById(R.id.rb1);
rb2 = (RadioButton) findViewById(R.id.rb2);
rb3 = (RadioButton) findViewById(R.id.rb3);
rb4 = (RadioButton) findViewById(R.id.rb4);
rb1.setOnClickListener(this);
rb2.setOnClickListener(this);
rb3.setOnClickListener(this);
rb4.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent returnIntent = getIntent();
switch (v.getId()) {
case (R.id.rb1):
returnIntent.putExtra("StatusTag", "" + rb1.getText());
setResult(RESULT_OK, returnIntent);
finish();
break;
case (R.id.rb2):
returnIntent.putExtra("StatusTag","" + rb2.getText());
setResult(RESULT_OK, returnIntent);
finish();
break;
case (R.id.rb3):
returnIntent.putExtra("StatusTag", "" + rb3.getText());
setResult(RESULT_OK, returnIntent);
finish();
break;
case (R.id.rb4):
returnIntent.putExtra("StatusTag","" + rb4.getText());
setResult(RESULT_OK, returnIntent);
finish();
break;
}
}}
Add.java
ImageButton ibtn, ibtn2, ibtn3, ibtn4,ibtn5;
TextView tvgroup;
TextView tvstatus;
int groupRequestCode;
int statusRequestCode;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
tvgroup = (TextView) findViewById(R.id.tvgroup);
tvstatus = (TextView) findViewById(R.id.tvstatus);
ibtn = (ImageButton) findViewById(R.id.ibtn);
ibtn2 = (ImageButton) findViewById(R.id.ibtn2);
ibtn3 = (ImageButton) findViewById(R.id.ibtn3);
ibtn4 = (ImageButton) findViewById(R.id.ibtn4);
ibtn5 = (ImageButton) findViewById(R.id.ibtn5);
ibtn.setOnClickListener(this);
ibtn2.setOnClickListener(this);
ibtn3.setOnClickListener(this);
ibtn4.setOnClickListener(this);
ibtn5.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case (R.id.ibtn):
startActivityForResult(new Intent(this, Group.class), groupRequestCode);
break;
case (R.id.ibtn2):
startActivity(new Intent(this, Due_Date.class));
break;
case (R.id.ibtn3):
startActivity(new Intent(this,DueTime.class));
break;
case (R.id.ibtn4):
startActivityForResult(new Intent(this, Status.class), statusRequestCode);
break;
case (R.id.ibtn5):
startActivity(new Intent(this,Assignees.class));
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == groupRequestCode) { // here you come back from Group.java
if(resultCode == RESULT_OK){
// do your stuff here
String textViewName = data.getStringExtra("GroupTag");
tvgroup.setText(textViewName);
}
}
if (requestCode == statusRequestCode) { // here you come back from Status.java
if(resultCode == RESULT_OK){
// do your stuff here
String status = data.getStringExtra("StatusTag");
tvstatus.setText(status);
}
}
}}
The result :
Any kind of help would really be appreciated.
I suggest you to use startActivityForResult() method to pass data between activities.
So you need to change your code like that:
In Add.java
1) Remove this code:
Bundle extra = getIntent().getExtras();
if (extra != null) {
String textViewName = extra.getString("SomeTag");
tvgroup.setText(textViewName);
}
Bundle extra2 = getIntent().getExtras();
if (extra2 != null) {
String status = extra2.getString("SomeTag");
tvstatus.setText(status);
}
2)
Change startActivity(new Intent(this,Group.class));
to startActivityForResult(new Intent(this,Group.class), groupRequestCode);
Also startActivity(new Intent(this,Status.class));
to startActivityForResult(new Intent(this,Status.class), statusRequestCode);
PS: groupRequestCode should be different from statusRequestCode ( for example 1 and 2).
3) Overrid onAcitivtyResult() method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == groupRequestCode) { // here you come back from Group.java
if(resultCode == RESULT_OK){
// do your stuff here
String textViewName = data.getStringExtra("GroupTag");
tvgroup.setText(textViewName);
}
}
if (requestCode == statusRequestCode) { // here you come back from Status.java
if(resultCode == RESULT_OK){
// do your stuff here
String status = data.getStringExtra("StatusTag");
tvstatus.setText(status);
}
}
}
PS: you can use switch instead of if blocs if you have many requestcode.
In Group.java
Change
Intent intent = new Intent(Group.this, Add.class);
intent.putExtra("SomeTag", "" + radio1.getText());
startActivity(intent);
to
Intent returnIntent = getIntent();
returnIntent.putExtra("GroupTag","" + radio1.getText());
setResult(RESULT_OK,returnIntent);
finish();
=> Do the same thing for the rest of the RadioButtons
In Status.java
Change
Intent intent2 = new Intent(Status.this, Add.class);
intent2.putExtra("SomeTag", "" + rb2.getText());
startActivity(intent2);
to
Intent returnIntent = getIntent();
returnIntent.putExtra("StatusTag","" + rb2.getText());
setResult(RESULT_OK, returnIntent);
finish();
=> Do the same thing for the rest of the RadioButtons

Categories