Issue
Whenever I move from 1st activity to 2nd acitivity and then come back to 1st activity the value given in 1st activity goes null , even when I'm passing the value back and forth through intent .
Activity - 1
String date = getIntent().getStringExtra("date");
String name = getIntent().getStringExtra("name");
textView1.setText(date);
textView2.setText(name);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent= new Intent(Main.this,date.class);
intent.putExtra("name1", name);
startActivity(intent);
}
});
Activity - 2
calendarView=(CalendarView)findViewById(R.id.calendarView);
String name1 = getIntent().getStringExtra("name1");
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
String date = dayOfMonth+"-"+month+"-"+year;
Intent intent = new Intent(date.this , Main.class);
intent.putExtra("date", date);
intent.putExtra("name", name1);
startActivity(intent);
}
});
Solution
You are not getting the data back because you are starting a new activity rather than getting back to your previous activity From your first activity ,start activity for result
int LAUNCH_SECOND_ACTIVITY = 1
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);
from your second activity return the result
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
finaly on your first activity,receive the results from the second activity on onActivityResult
Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LAUNCH_SECOND_ACTIVITY) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
// Write your code if there's no result
}
}
} //onActivityResult
Answered By - Code Demon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.