Android: Saving and Restoring data when switching between Activities - android

I am trying to save some data in "MainActivity" when switching to another activity, and restoring that data as I switch back to it.
In "MainActivity": (restoring data)
protected void onCreate(Bundle savedInstanceState) {
// do usual stuff
restoreData();
}
In "MainActivity": (switching to "StatusActivity"):
Bundle data = saveData();
Log.d(TAG, "Sending data to status activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), StatusActivity.class);
intent.putExtras(data);
startActivity(intent);
In "StatusActivity":
Bundle data = getIntent().getExtras();
Log.d(TAG, "Sending data to main activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtras(data);
startActivity(intent);
My saveData() function:
private Bundle saveData() {
Log.d(TAG, "Started saving state");
Bundle data = new Bundle();
// store stuff in the bundle
return data;
}
My restoreData() function:
private void restoreData() {
Log.d(TAG, "Started restoring state");
Bundle data = getIntent().getExtras();
// restore stuff in the bundle
}
LogCat:
My bundle is fine when sending to StatusActivity:
Sending data to status activity intent:
Bundle[{obj0=Bundle[{timeSinceLastPooped=3224, hunger=5,
id=2130837505, timeSinceLastHungerUpdate=3224,
timeSinceLastFed=0, timeSinceLastHappinessUpdate=3224,
timeSinceLastEvolution=3224, posY=0.0, posX=0.0,
isDead=false, happiness=5, evolutionStage=0, type=pet}],
time=7.794168E7}]
But then sending back to MainActivity:
Sending data to main activity intent: Bundle[mParcelledData.dataSize=648]
What do I do with mParcelledData to get the original bundle back? Thanks!
Answer:
In "MainActivity": (restoring data)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == 1) {
if(resultCode == RESULT_OK) {
restoreData(intent);
}
}
}
In "MainActivity": (switching to "StatusActivity"):
Bundle data = saveData();
Log.d(TAG, "Sending data to status activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), StatusActivity.class);
intent.putExtras(data);
startActivityForResult(intent, 1);
In "StatusActivity":
Bundle data = getIntent().getExtras();
Log.d(TAG, "Sending data to main activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtras(data);
setResult(RESULT_OK, getIntent());
finish();

You can use onRestoreInstanceState() witch is called after onStart(), whereas onCreate() is called before onStart().
Use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putInt("value", value);
}
And restore the value in onCreate():
public void onCreate(Bundle bundle) {
if (bundle!= null){
value = bundle.getInt("value");
}
}

Related

Passing data from second activity to first activity

I am trying to pass Bundle from second activity to the first(launch) activity. In order not to get NPE on launch, I am checking if bundle != null, however, it looks, like even after returning from second activity with Bundle, it still doesn't run the "if" body.
Here is my part of code of first activity
Bundle bundle = getIntent().getExtras();
if (bundle!=null) {
Player player = new Player();
player.setStatus(bundle.getInt("Status"));
player.setName(bundle.getString("Name"));
addPlayerToList(player);
Log.e("Player with a name " + player.getName(), "Has been created");
}
And code of second activity
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEditText.getText().toString();
if (defaultRadioButton.isChecked()) {
status=0;
} else if (driverRadioButton.isChecked()) {
status=1;
} else {
Toast.makeText(getApplicationContext(), "Suka viberi galochku", Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(getApplicationContext(),StartActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("Status",status);
bundle.putString("Name", name);
Log.d("Object " + name, "Status: " + status);
startActivity(i);
}
});
Thanks for any help/advice
Use startActivityForResult() for this situation.
1) You open second activity from the first using this method, not startActivity()
2) Do whatever you want in the second activity
3) Set result bundle
4) Finish activity
5) Open bundle in the first activity
In your case it will look like:
1) Call second activity like this:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, REQUEST_SECOND_ACTIVITY); // request code const
2-4)
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEditText.getText().toString();
if (defaultRadioButton.isChecked()) {
status=0;
} else if (driverRadioButton.isChecked()) {
status=1;
} else {
Toast.makeText(getApplicationContext(), "Suka viberi galochku", Toast.LENGTH_SHORT).show();
}
final Intent returnIntent = new Intent();
returnIntent.putExtra("Status", status); // set values
returnIntent.putExtra("Name", name);
setResult(Activity.RESULT_OK, returnIntent); // set result code
finish(); // finish this activity and go back to the previous one
}
});
5) Override this method in the first activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case REQUEST_SECOND_ACTIVITY: // same request code const
if(resultCode == Activity.RESULT_OK){
Player player = new Player();
player.setStatus(data.getIntExtra("Status"));
player.setName(data.getStringExtra("Name"));
addPlayerToList(player);
}
break;
}
}
try Intent.putExtra() instead of putting data into a bundle, and use Intent.getStringExtra() to get a String data;
In your code, there is no code to put your bundle into intent. actually you never pass the bundle to first activity. you can use this answer to solve your problem.
good luck!

How can I send data to ble device from second or third activity of the same program

I can send data from the first activity but on repeating the same procedure on the second activity to send data to ble device is not successful. How can I send data from second activity?
use this to save
Intent intent = new Intent(FirstScreen.this, SecondScreen.class)
intent .putExtra(strName, keyIdentifer );
use this to get
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
If you just want to send data to the next activity, use
Intent intent = new Intent(FirstActivity.this, SecondActivity.class)
intent.putExtra("id_for_value", value);
startActivity(intent);
And recover it with
value= getIntent().getExtras().getString("id_for_value");//if it is a string
OR
If you want to send data back from the Second activity back to the Previous, you have to use start activity for results
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 2)//where 2 is the request code
finish();
Again in the FirstActivity, overide this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String result=data.getStringExtra("ResultId");
}
}
And in your PreviousActivity, you pass the data like this
Intent intent=new Intent();
intent.putExtra("ResultId",message);
setResult(2,intent);
finish();

Loading instance of an Activity from saved state while using IntentService

I have an Activity, from there I start a task (consider like uploading multiple files to server) using IntentService. Once each and every upload is completed I send back the result of upload to Activity using ResultReceiver. I'm getting the result back to an Activity and updating the UI.
While uploading the files, I close my Activity. IntentService is still running and returning the result. But Activity is not alive to receive the result as it was destroyed. Now again I open the Activity I want to continue to show the uploading progress. But it's not happening. I'm sharing the code what I have done.
MyResultReceiver.java
public class MyResultReceiver extends ResultReceiver {
private Receiver receiver;
public MyResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
this.receiver = receiver;
}
public interface Receiver {
public void onReceiveResult(int resultCode, Bundle resultData);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (receiver != null) {
receiver.onReceiveResult(resultCode, resultData);
}
}
}
MainActivity.java
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
resultReceiver = new MyResultReceiver(new Handler());
resultReceiver.setReceiver(new MyResultReceiver.Receiver() {
#Override
public void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == RESULT_OK) {
isCompleted = resultData.getBoolean("IsCompleted");
textView.setText(resultData.getString("Message"));
}
}
});
Intent intent = new Intent(MainActivity.this, MyIntentService.class);
intent.putExtra("receiver", resultReceiver);
startService(intent);
}
MyIntentService.java
#Override
protected void onHandleIntent(final Intent intent) {
for (int count = 0; count <= i; count--) {
ResultReceiver receiver = intent.getParcelableExtra("receiver");
i -= 1;
Bundle bundle = new Bundle();
if (count == i)
bundle.putBoolean("IsCompleted", true);
else
bundle.putBoolean("IsCompleted", false);
bundle.putString("Message", "This is " + i);
receiver.send(Activity.RESULT_OK, bundle);
Log.i("Intent Service", "This is " + i);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In the above code all I'm trying to display the decremented count in TextView.
I have tried using onSaveInstanceState, but according to the documentation it just saves only when OS decides. In my case I want to store this data all time and restore it whenever the activity is re-created.
Any help or reference will be encouraged.
EDIT : How I tried to store and restore the instance
Intent intent = new Intent(MainActivity.this, MyIntentService.class);
if (savedInstanceState != null) {
intent.putExtra("receiver", savedInstanceState.getParcelable("savedReceiver"));
} else
intent.putExtra("receiver", resultReceiver);
startService(intent);
I tried something like this. But didn't help. And I can't use savedInstanceState as it will not be called all the time. Hope this help!

do you know this? about android intent

My source code is as follows:
in MainActivity:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case LOGIN_ACTIVITY_REQUEST_CODE:
{
if(resultCode == RESULT_OK){
Bundle bd = new Bundle();
bd = data.getBundleExtra("bundle");
}
}
default:
{
Log.d(DEBUG_ACTIVITY_CLASS_NAME, "ERROR : onActivityResult - unknown activity code");
}
}
}
And second activity's code is:
public void returnToGameActivity(Bundle bundle) {
Intent intent = new Intent();
intent.putExtra("bundle", bundle);
this.setResult(RESULT_OK, intent);
finish();
}
But i can't receive data 'bd' of Bundle type in onActivityResult() in MainActivity. Why?
But in this case, i can get data of bd:
in second activity,
putExtra("string", "test string");
and in MainActivity,
String str = getStringExtra("string");
Why i can't get data in bundle type?
To transfer a Bundle element from one activity to other,use the following code:
Intent i=new Intent(First.this,Second.class);
//i.putExtra("mylist",amt);
Bundle b = new Bundle();
b.putSerializable("bundleinterest", (Serializable) amtint);
b.putSerializable("bundleobj", (Serializable) amt);
i.putExtras(b);
startActivity(i);
In Second.class:
Bundle bn = new Bundle();
bn = getIntent().getExtras();
getobj = new ArrayList<CompoundAmount>();
getinterestobj=new ArrayList<CompoundIntAmount>();
getobj = (ArrayList<CompoundAmount>) bn.getSerializable("bundleobj");
getinterestobj = (ArrayList<CompoundIntAmount>) bn.getSerializable("bundleinterest");
Explanation:
Use Serializable or Parcelable interfaces while transferring Bundles.
Your set-get class must implements Serializable as:
public class CompoundIntAmount implements Serializable {
private final String amt;
public CompoundIntAmount(String amt){
this.amt = amt;
}
public String getIntAmount() {
return amt;
}
}
Here CompoundAmount and CompoundIntAmount are custom set-get classes which must implement Serializable(like the one above).

How to send datafrom one activity to another in Android? [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 8 years ago.
My app has 2 activites.
The first activity is just a simple form where a user enters course information(class title, professor..etc.) the first activity passes the data which is supposed to be stored in a list.
In the second activity. The problem is that only the first course gets stored in the list, after the first time nothing new gets added to the second activity.
How can i do this ?
In your first activity :
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("login", jObj.getString(KEY_LOGIN));
intent.putExtra("mdp", jObj.getString(KEY_MDP));
intent.putExtra("prenom", jObj.getString(KEY_PRENOM));
intent.putExtra("nom", jObj.getString(KEY_NOM));
intent.putExtra("mail", jObj.getString(KEY_MAIL));
intent.putExtra("tel", jObj.getString(KEY_TEL));
startActivity(intent);
In your second activity :
Intent intent = getIntent();
if (intent != null) {
login = intent.getStringExtra("login");
mdp = intent.getStringExtra("mdp");
items.add(intent.getStringExtra("login"));
items.add(intent.getStringExtra("prenom"));
items.add(intent.getStringExtra("nom"));
items.add(intent.getStringExtra("mail"));
items.add(intent.getStringExtra("tel"));
}
Generally you can pass data from one Activity to another with an Intent like this:
In your first Activity:
// Create your Intent
Intent intent = new Intent(context, TargetActivity.class);
// Now you can add extras to the intent, you identify extras with a String key
intent.putExtra("text", someString);
intent.putExtra("amount", someInteger);
// Then you start your Activity with this Intent
startActivity(intent);
In your second Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Only get data from Intent when the Activity is new
if(savedInstanceState == null) {
Intent intent = getIntent();
// Now you read the values from the Intent
String someString = intent.getStringExtra("text");
int someInteger = intent.getIntExtra("amount", 0);
}
}
hey its simple look at the code
for sending
Intent i = new Intent(getApplicationContext(), Confirmation.class)
i.putExtra("name",etName.getText().toString()));
i.putExtra("pass",etPass.getText().toString());
startActivity(i);
for recieving in next activity
Bundle extras = getIntent().getExtras();
String strEmployeeID="";
if (extras != null)
{
String value = extras.getString("name");
String value1 = extras.getString("pass");
//
Toast.makeText(getBaseContext(), value, Toast.LENGTH_LONG).show();
strEmployeeID = value;
strEmployeePass = value1;
}
just simply do it like that:
passing data from 1st activity to 2nd activity:
Intent intent = new Intent(yourafirstctivity.this,Yoursecondactivity.class);
intent.putExtra("yourkey", yourvalue);
intent.putExtra("yourkey", yourvalue);
intent.putExtra("yourkey", yourvalue);
startActivity(intent);
and get the data from 1st activity to 2nd activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.yourlayout);
String yourstring = getIntent().getExtras().getString("yourkey");
String yourstring = getIntent().getExtras().getString("yourkey");
String yourstring = getIntent().getExtras().getString("yourkey");
}
if you want to send data between two Activities .You must call following one,
startActivityForResult(getcontext(), SecondActivity.class);
On calling this,Activity starts the second.In turn, second response to this intent and reply back with necessary data.
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
if (mParent == null) {
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
mStartedActivity = true;
}
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
Following one you must call this on the First Activity (from where the intent called).It helps to recieves the reply data from second Activity.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(!isFeatureInstalled(getContext()))
return;
if(requestCode == GET_REMINDER_DETAILS && resultCode == Activity.RESULT_OK)
{
mFilled = true;
fillDataFromIntent(data);
checkALertRequired.setChecked(true);
}
}

Categories

Resources