I keep losing data when pressing the back button after going back from activity 2 to 1.
when passing the data to activity 2 I'm using
intent = new Intent(getApplicationContext(), secondactivity.class);
startActivity(intent);
to launch the second activity. is it possible not to lose the data without using sharedpreference when pressing the back button?
CodePudding user response:
You can store your data in the Application class and use it everywhere
Create a class:
public class MyCustomApplication extends Application {
String myData = "";
}
in manifest add class name as android:name
<application
android:name=".MyCustomApplication"
android:icon="@drawable/icon"
android:label="@string/app_name"
...>
access it like this from any activity
String myData = ((MyCustomApplication)getApplication()).myData;
((MyCustomApplication)getApplication()).myData = "new value";
CodePudding user response:
Create a new class
public class myClass{
public static String myData;
}
In your activity
myClass.myData = "Set a text";
Then call it everywhere in you activity
String myData = myClass.myData;
CodePudding user response:
When launching your second activity, you can specify that you are expecting a result from the activity:
int LAUNCH_SECOND_ACTIVITY = 1
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);
Then, in your second activity, you can override the onBackPressed()
@Override public void onBackPressed() { Intent data = new Intent(); // add data to Intent setResult(Activity.RESULT_OK, data); super.onBackPressed(); }
Possible duplicate of How do I pass data between activities when I press back button in Android?