After entering the details in EditText in child activity when I go back to parent activity and comes back to child activity the EditText value is becoming blank. I have used below mentioned code, but no use.
Below mentioned is childactivity.java details.
Can anyone help in this.
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class NotesActivity extends AppCompatActivity {
String typedText;
EditText inputTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
inputTxt = (EditText) findViewById(R.id.notes1);
}
@Override
protected void onPause() {
super.onPause();
typedText = inputTxt.getText().toString();
}
@Override
protected void onResume() {
super.onResume();
inputTxt.setText(typedText);
}
}
When you destroy the activity even if you are setting typedText
to something it will become null
because the next time you launch this activity from other, a new instance will be created and old data will be lost. You have to store data with persistent storage options. https://developer.android.com/guide/topics/data/data-storage.html
To store data in SharedPreferences you can modify following code.
private final String PREFS_NAME = "packageName";
SharedPreferences sharedPref = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("typedText", inputTxt.getText().toString());
editor.commit();
And to retrieve the value you can do as following.
SharedPreferences sharedPref = getSharedPreferences(PREFS_NAME, 0);
String typedValue = sharedPref.getString("typedText", "defaultValue/null");
In parent call startActivityForResult(getApplicationContext(), NotesActivity.class) to call child activity which is NotesActivity.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
String typedText = "" + extras.getString("TypedText");
}
}
In the Child activity use below function to return 'typedText'
private void returnText() {
Intent result = new Intent();
String typedText = inputTxt.getText().toString();
result.putExtra("TypedText", typedText);
setResult(RESULT_OK, result);
}
@Override
protected void onPause() {
super.onPause();
returnText();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.