Image on ImageView lost after Activity is destroyed - android

I am trying to make an app where I can let a user select a picture to display on their profile. I am able to browse and set their selected image on imageview. But the image is lost once the the activity is destroyed. I tried to implement onSaveInstanceState but still it's the same. I'm wondering if I am using it correctly. I hope you can help a newbie like me. Thanks in advance. Here's the code that I'm using:
public class AccountFragment extends Fragment implements OnClickListener {
private LoginDataBaseAdapter loginDataBaseAdapter;
Bitmap image;
Bitmap bitmap;
String picture_location;
TextView textTargetUri;
ImageView targetImage;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_account, container, false);
textTargetUri = (TextView) rootView.findViewById(R.id.targeturi);
targetImage=(ImageView) rootView.findViewById(R.id.profpic);
targetImage.setOnClickListener(new ImageView.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}});
if (savedInstanceState != null) {
//if there is a bundle, use the saved image resource (if one is there)
image = savedInstanceState.getParcelable("BitmapImage");
targetImage.setImageBitmap(image);
textTargetUri.setText(savedInstanceState.getString("path_to_picture"));
}
return rootView;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putParcelable("BitmapImage", bitmap);
savedInstanceState.putString("path_to_picture", picture_location);
}
#Override
public void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
Uri targetUri = data.getData();
picture_location = targetUri.toString();
textTargetUri.setText(targetUri.toString());
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}}
By the way, you may have noticed that instead of using the onRestoreInstanceState after oncreate, I tried to use the different approach. I found an answer from another question that you can also implement it inside the oncreate. I used it since whenever I declare the function onRestoreInstanceState I am being asked to remove the #Override annotation.
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
image = savedInstanceState.getParcelable("BitmapImage");
targetImage.setImageBitmap(image);
textTargetUri.setText(savedInstanceState.getString("path_to_picture"));
}

Using onSaveInstanceState and onCreate/onRestoreInstanceState is for short term activity state preservation - but not to be used for persistent storage of the application's data.
You can read about onSaveInstanceState here
You can read about persistent storage here
codeMagic suggested using SharedPrefs (see persistent storage link) for your long-term persistent storage. If you wanted to do this, I would suggest saving the image URI (the link has a good example of how to do so) in you onActivityResult method, and then call a method to read the SharedPref and load the image that you can call from onCreate as well as from onActivityResult.
You may also want to store your own copy of the image/bitmap in your application's own internal storage (see persistent storage link).

if you are not finishing the activity, you can use onSavedInstance() to store the picture_location value and bind it back either in onCreate(SavedInst)/onRestore() from the picture_location value.

In case of Bitmaps Instance State is not the suggested way to persist info about the selected image.
You can find the explanation here: Handling configuration Changes
I blogged extensively about it here: Retain selected Image during Screen Rotation
Below I paste my implementation of the illustrated solution:
1 - Create a Fragment and configure it to be retained in memory
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class ImageRetainingFragment extends Fragment {
private Bitmap selectedImage;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
public void setImage(Bitmap selectedImage) {
this.selectedImage = selectedImage;
}
public Bitmap getImage() {
return this.selectedImage;
}
}
2 - Use it in your Activity
private static final String FRAGMENT_NAME = "imageFragment";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
initializeImageRetainingFragment();
tryLoadImage();
}
private void initializeImageRetainingFragment() {
// find the retained fragment on activity restarts
FragmentManager fragmentManager = getSupportFragmentManager();
this.imageRetainingFragment = (ImageRetainingFragment) fragmentManager.findFragmentByTag(FRAGMENT_NAME);
// create the fragment and bitmap the first time
if (this.imageRetainingFragment == null) {
this.imageRetainingFragment = new ImageRetainingFragment();
fragmentManager.beginTransaction()
// Add a fragment to the activity state.
.add(this.imageRetainingFragment, FRAGMENT_NAME)
.commit();
}
}
private void tryLoadImage() {
if (this.imageRetainingFragment == null) {
return;
}
Bitmap selectedImage = this.imageRetainingFragment.getImage();
if (selectedImage == null) {
return;
}
ImageView selectedImageView = (ImageView)findViewById(R.id.selectedImage);
selectedImageView.setImageBitmap(selectedImage);
}

1)// manifest.xml
2)//public class MainActivity extends AppCompatActivity implements LocationListener{...
SharedPreferences.Editor editor;
3)//protected void onCreate(Bundle savedInstanceState){ ...
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 3);
}
4)//SHARED PREFERENCES
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", getApplicationContext().MODE_PRIVATE);
editor = pref.edit();
5)//SET IMAGE PATH
if (pref.getString("mydraw", null) != null) {
img6.setImageURI(Uri.parse(pref.getString("mydraw", null)));
} else {
//set default image
img6.setImageResource(R.drawable.poseidon);
}
6)//protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {...
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
img6.setImageURI(data.getData());
//save URI as string
editor.putString("mydraw", data.getData().toString());
editor.commit(); // commit changes
}
}

Related

bugger in fragment is not tracking OnActivityResult method

I know I this question maybe asked before still I wanted to put my question up for all ,I need to make a scanner feature in my application , I am using a botton navigation in my project and due to that i am making more than one fragments on the same activity . Now in that fragment I need to call an ImageButton on the click of which camera activity has to open and after clicking the picture(or scanning lets suppose a QR code) it should go to the same fragment and return the scanned value. It worked in case of new activity but not working in fragment.
this is what I am doing
public class HomeFragment extends Fragment implements View.OnClickListener {
ImageButton btnScanner;
private TextView textViewName, textViewAddress;
//qr code scanner object
private IntentIntegrator qrScan;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_home, container, false);
textViewName=(TextView)root.findViewById(R.id.textViewName);
textViewAddress=(TextView)root.findViewById(R.id.textViewAddress);
btnScanner=(ImageButton)root.findViewById(R.id.scannerBtn);
btnScanner.setOnClickListener(this);
qrScan = new IntentIntegrator(getActivity());
return root;
}
private void initViews(){
}
//Getting the scan results
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
//if qrcode has nothing in it
if (result.getContents() == null) {
Toast.makeText(getContext(), "Result Not Found", Toast.LENGTH_LONG).show();
} else {
//if qr contains data
try {
//converting the data to json
JSONObject obj = new JSONObject(result.getContents());
//setting values to textviews
textViewName.setText(obj.getString("name"));
textViewAddress.setText(obj.getString("address"));
} catch ( JSONException e) {
e.printStackTrace();
//if control comes here
//that means the encoded format not matches
//in this case you can display whatever data is available on the qrcode
//to a toast
Toast.makeText(getContext(), result.getContents(), Toast.LENGTH_LONG).show();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onClick(View view) {
qrScan.initiateScan();
}
}
Here I am using the instance of a library class intentIntegrator.
I have also vited to
https://stackoverflow.com/questions/44622311/how-can-i-call-onactivityresult-inside-fragment-and-how-it-work/44622487#:~:text=if%20you%20call%20startActivityForResult(),deliver%20result%20to%20desired%20fragment.%20%7D&text=super.,-onActivityResult%20()%20will and
onActivityResult is not being called in Fragment yet my problem is not resolved

Restore fragment state after ActivityResult

I'm working on a fragment which displays a list of images. It has a button for "add image" that starts an intent for result with these values.
type: "image/*"
action: Intent.ACTION_GET_CONTENT
The problem is: after the user picks an image and returns to the fragment, all the other images in the list (stored in some ArrayList<> on the code) are gone.
I've overridden the method onSaveInstanceState(Bundle) and saved the list inside the bundle. The thing is, there's no way to restore it back.
I thought of overriding onViewStateRestored(Bundle) but it didn't work. When I put some Log.d() on all "onXXX" methods, I found that only these three are executed every time I add a file (actual order):
onPause()
onSaveInstanceState(Bundle)
//now the image picker opens up
//user picks the image
onResume()
//image picker closes and fragment is now on screen
I thought of using some "getXXX" method at onResume() but I can't find one that's useful. What can I do?
EDIT: Here is my code (without irrelevant stuff).
#Override public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.d("debugaff", "oncreate");
setRetainInstance(true);
this.attachments = (ArrayList<Attachment>) getActivity().getIntent().getSerializableExtra(ExtraKeys.ATTACHMENTS);
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
Log.d("debugaff", "oncreateview");
rootView = inflater.inflate(R.layout.fragment_attachments_form, container, false);
//....
if(savedInstanceState == null){
getLoaderManager().initLoader(0, null, this);
} else {
attachmentsRvAdapter.setItems((List<Attachment>) savedInstanceState.getSerializable(ExtraKeys.TEMP_ATTACHMENTS));
}
//....
return rootView;
}
#Override public void onResume(){
super.onResume();
Log.d("debugaff", "onresume");
hideKeyboard();
}
#Override public void onPause(){
super.onPause();
setRetainInstance(true); //called this to make it 100% redundant (already called it at onCreate)
Log.d("debugaff", "onpause");
}
#Override public void onViewStateRestored(#Nullable Bundle savedInstanceState){
Log.d("debugaff", "onviewstaterestored");
if(savedInstanceState == null){
getLoaderManager().initLoader(0, null, this);
} else {
attachments.addAll((List<Attachment>) savedInstanceState.getSerializable(ExtraKeys.TEMP_ATTACHMENTS));
attachmentsRvAdapter.setItems(attachments);
}
super.onViewStateRestored(savedInstanceState);
}
I have just mimic your situation and found no error (list saves the new value with old values in the list). The only problem I can think of is you are not initializing your list correctly. What I did was to initialized the list in the onCreate() method and when I pick another Image it saves that image in the same list with the previous image still in the list. There is no need to save the list separately in the savedInstanceBundle. Here is my Fragment code:
public class SelectListFragment extends Fragment {
private static final int PICK_IMAGE_REQUEST = 11;
public SelectListFragment() {
// Required empty public constructor
}
List listOfImagesSelected;
Button selectButton;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listOfImagesSelected=new ArrayList<Bitmap>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_select_list, container, false);
selectButton = view.findViewById(R.id.selectButton);
selectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//I am retrieving the Bitmap from the intent and saving into the list
if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
//making the bitmap from the link of the file selected
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
listOfImagesSelected.add(bitmap);
}catch (Exception e){
}
}
}
}
I can share the Complete Working Code of my Project if needed. For better understanding of the Fragment LifeCycle please review this Image
To use onViewStateRestored, you need to call 'setRetainInstance(true);'

Save the state of a Circleimageview inside a fragment

I have fragments with a circleimageview inside used as a profile image that is saved later in a database correctly.
My problem is to save the state of the imageview with onSaveInstanceState and onPause/onStop to keep their state before saving them in the database and after, for example, performing a screen rotation.
This is my code
public class MyFragment extends Fragment implements View.OnClickListener {
private CircleImageView mPhoto;
private byte[] bytes = null;
private Bitmap photo = null;
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if(bytes!=null) {
outState.putByteArray("bytes", bytes);
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
LayoutInflater lf = getActivity().getLayoutInflater();
view = lf.inflate(R.layout.my_fragment,container,false);
mPhoto = (CircleImageView) view.findViewById(R.id.photo);
view.findViewById(R.id.photo).setOnClickListener(this);
if(savedInstanceState!=null){
if(savedInstanceState.containsKey("bytes")){
bytes = savedInstanceState.getByteArray("bytes");
if(bytes != null) {
//but with a screen rotation the image is not restored
photo = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
mPhoto.setImageBitmap(photo);
}
}
}
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.photo:
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
try {
startActivityForResult(Intent.createChooser(i, "Select Picture"), 0);
}catch (ActivityNotFoundException ex){
ex.printStackTrace();
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==0 && resultCode == Activity.RESULT_OK) {
Uri path = data.getData();
Bitmap tmp = null;
try {
tmp = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), path);
} catch (IOException e) {
e.printStackTrace();
}
if(tmp != null) {
mPhoto.setImageBitmap(photo);
bytes = getBitmapAsByteArray(photo);
//tested, bytes is not null and the photo are restored correctly when saved on the database
}
}
}
#Override
public void onResume() {
super.onResume();
bytes = getActivity().getIntent().getByteArrayExtra("bytes");
if(bytes != null) {
//here bytes is null
photo = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
mPhoto.setImageBitmap(photo);
}
}
#Override
public void onStop() {
super.onStop();
if(bytes!=null)
getActivity().getIntent().putExtra("bytes",bytes);
}
}
in this way the image is not maintained during a screen rotation, how to correctly implement onsavedInstanceState, onStop and onResume?
Put code before super() method.
#Override
public void onStop() {
if(bytes!=null)
getActivity().getIntent().putExtra("bytes",bytes);
super.onStop();
}
Easiest way Use ViewModel with your fragment.
Refer: https://developer.android.com/topic/libraries/architecture/viewmodel.html
Update:
Step1: Add View Model dependency in build.gradle
def lifecycle_version = "2.0.0"
implementation "androidx.lifecycle:lifecycle viewmodel:$lifecycle_version"
Step 2: Create a ViewModel for Fragment
public class MyFragmentViewModel extends ViewModel {
}
Step 3: Set ViewModel in MyFragment
public class MyFragment extends Fragment {
public void onStart() {
MyFragmentViewModel userModel = ViewModelProviders.of(getActivity()).get(MyFragmentViewModel.class);
}
}

Restore listener after Activity recreate (pass photo to a custom view returning from camera)

I have an activity with a fragment. Inside a fragment I have 2 custom views. A custom view contains an ImageView and a listener. Listener can transform, show a photo in ImageView and upload the photo.
I want to take a photo from camera, return it to the fragment, pass to a view through listener (then show and upload inside the view). Everything works right until the activity is destroyed after camera becomes visible. So, after returning from camera, I restore the fragment, get photo in onActivityResult and try to pass to a view by listener. But a listener is null, and i don't know what view it is attached to.
How can I pass a photo to a view after recreating an activity?
Listener:
public interface Listener {
void onPhotoObtained(#Nullable Uri uri);
}
Custom view:
public class CustomView extends RelativeLayout implements Listener {
#BindView(R.id.imageview) ImageView image;
private PhotoManager photoManager;
public void setPhotoManager(#NonNull PhotoManager photoManager) {
this.photoManager = photoManager;
}
#Override
public void onPhotoObtained(#Nullable Uri uri) {
// transform and show image
}
#OnClick(R.id.imageview)
void onPhotoButtonClicked() {
photoManager.requestPhoto(this);
}
}
Fragment:
public class MainFragment extends Fragment implements PhotoManager {
#BindView(R.id.view1) CustomView view1;
#BindView(R.id.view2) CustomView view2;
// A list of listeners to communicate with custom views.
// When a user clicks an ImageView, this fragment starts a camera to obtain a photo.
private SparseArray<Listener> listeners;
private int lastRequestId;
private Uri uri;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_main, container, false);
binder = ButterKnife.bind(this, view);
listeners = new SparseArray<>();
if (savedInstanceState == null) {
lastRequestId = 0;
uri = null;
} else {
lastRequestId = savedInstanceState.getInt(BUNDLE_REQUEST_ID);
uri = savedInstanceState.getParcelable(BUNDLE_KEY_URI);
// How to create a listener list?
}
view1.setPhotoManager(this);
view2.setPhotoManager(this);
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ReceivingPhotoDialogFragment.CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (uri != null) {
// listeners become empty after fragment reinitialization
Listener listener = listeners.get(lastRequestId);
if (listener != null)
listener.onPhotoObtained(uri);
}
}
}
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
bundle.putInt(BUNDLE_REQUEST_ID, lastRequestId);
bundle.putParcelable(BUNDLE_KEY_URI, uri);
super.onSaveInstanceState(outState);
}
#Override
public void requestPhoto(#NonNull Listener listener) {
listeners.put(++lastRequestId, listener);
// Request new photo with lastRequestId
showCamera(lastRequestId);
}
private void showCamera(int requestId) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getContext().getPackageManager()) != null) {
File file = null;
try {
file = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
uri = null;
if (file != null) {
uri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(BUNDLE_REQUEST_ID, requestId);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(timeStamp, ".jpg", storageDir);
}
}
A second listener to initialize first:
public interface PhotoManager {
void requestPhoto(#NonNull Listener listener);
}
I still struggle with the activity lifecycle, so this may not be the best answer.
What I do is make my listener as a static variable. This allows the variable to exist in the class instead of the instance of the class which clears when destroyed.
I think, You do not need to re-initialise listener for that,
What you need is add a property named configChanges in your AndroidManifest.xml file for that activity which has this MainFragment
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:screenOrientation="portrait"/>
Add these tag configChanges and then run your code.

Passing String from Activity back to running Fragment in Android

There are a few posts about similar problems but I just don't get the wright answers and I hope that anyone can help me.
Situation:
I have a MainActivity that contains several Fragments. In one Fragment I start a CameraActivity with an intent. When the user has taken the picture, the CameraActivity gets closed with finish() and we return back to the previous Fragment.
Goal:
I give the Picture a certain name and would like to pass this name from the CameraActivity to the Fragment.
Problem:
Even though I call finish() in the CameraActivity and the screen returns back to the previous Fragment, the method onSaveInstanceState(Bundle outstate) is never called. Why is that?
Or how could I solve the problem otherwise?
Here is my code:
public class CameraActivity extends Activity {
// more code here
String imageFileName;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// some methods here
finish(); // finish the current Activity and get back to previous Fragment
}
// more code here
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.d(TAG_LOG, "onSaveInstanceState() called"); // is never called!
outState.putString("imageFileName", imageFileName);
super.onSaveInstanceState(outState);
}
}
And in the Fragment I do this:
public class MapFragment extends Fragment implements View.OnClickListener {
// more code here
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
// some methods here
if (savedInstanceState != null) {
String imageFileName = getArguments().getString("imageFileName");
Log.d(TAG_LOG, "image filename: " + imageFileName);
}
return view;
}
// more code here
}
Any help is highly appreciated!
You should take a look at startActivityForResults. Here is a short example (haven't tried it but you will get the idea) :
Fragment
Intent intent = new Intent(MainActivity.this,CameraActivity.class);
getActivity().startActivityForResult(intent,RESULT_PIC_TAKEN); // you may start an activity from another activity, not a fragment
CameraActivity
Intent results = new Intent();
results.putExtra("com;yourpackage.PIC_NAME", picName);
setResult(CameraActivity.RESULT_OK,results);
finish();
Back to MainActivity (since you called getActivity())
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RESULT_PIC_TAKEN) {
if(resultCode == Activity.RESULT_OK){
Bundle results = data.getExtras();
String picName = results.getString("com.yourpackage.PIC_NAME");
// code, and send what you want to the fragment
}
}
}
Hope this will help you!
Start the CameraActivity using startActivityForResult(), once you get the string to pass back in your previous screen, just create an Intent that will contain that string, and in your MainActivity, implement:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
Get the string from the intent, and pass it to your fragment.
onSaveInstanceState is used for other purposes.

Categories

Resources