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);'
Related
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
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.
I want to create simple communication Listener between Fragment and Activity, after define listener in Activity and implemented that from Fragment I get NullPointerException when I send String from Activity to Fragment, I want to send data from onActivityResult.
My activity is:
public class ActivityMain extends FragmentActivity {
public IonGetBarcodeFromScannerListener ionGetBarcodeFromScannerListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
G.currentActivity = this;
G.context = getBaseContext();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
Log.e("barcode is: ", scanContent);
doSendBarcode(scanContent);
}
else{
Log.e("No scan data received! ", "");
doSendBarcode("");
}
}
public void doSendBarcode(String barcode){
ionGetBarcodeFromScannerListener.getBarcode(barcode);
}
public void setBarcodeListener(IonGetBarcodeFromScannerListener l){
ionGetBarcodeFromScannerListener = l;
}
public interface IonGetBarcodeFromScannerListener {
public void getBarcode(String barcode);
}
}
i get NullPointerException for this line:
ionGetBarcodeFromScannerListener.getBarcode(barcode);
My Fragment:
public class FragmentAddNewWayBill extends Fragment implements ActivityMain.IonGetBarcodeFromScannerListener{
private PtrClassicFrameLayout mPtrFrame;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
G.currentActivity = FragmentAddNewWayBill.this.getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_new_waybill, container, false);
return view;
}
#Override
public void getBarcode(String barcode) {
Toast.makeText(G.currentActivity, "salam: " + barcode, Toast.LENGTH_SHORT).show();
}
}
I guess you are trying for activity and fragment communication in opposite way as I think interface will be defined in fragment and it's implementation will be done in activity. See http://developer.android.com/training/basics/fragments/communicating.html for more details
Seems you are never calling setBarcodeListener() so the field is never set, and therefore null.
-- update --
You could call it inside the fragment's onAttach() by using the return value from .getActivity().
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
}
}
I'm probably doing this in the wrong place, but currently I have a DialogFragment that represents a dialog with a camera button (among other things) and I'm using the built-in camera app (calling via an Intent) that returns to the DialogFragment's onActivityResult().
This all works great, but my goal is to find an attachments LinearLayout in my dialog and essentially attach a copy of the captured image to it. e.g. you takes some pics and they appear in the dialog's "attachments" section.
The issue appears to be that when the DialogFragment's onActivityResult() is triggered, I'm unable to get the its view, it's null:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST && resultCode == Activity.RESULT_OK) {
try {
LinearLayout attachments = (LinearLayout) getView().findViewById(R.id.landmarkAttachmentView); // <- getView() is null
I threw in a debug log in a couple of suspect methods I thought might trigger when the camera returned, that had the DialogFragment's view available, but none of them logged:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "Creating landmark dialog view");
if(getView() == null) Log.d(TAG, "No view!");
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void show(FragmentManager manager, String tag) {
Log.d(TAG, "Show landmark dialog view");
if(getView() == null) Log.d(TAG, "No view!");
super.show(manager, tag);
}
#Override
public void onViewStateRestored(Bundle savedInstanceState) {
Log.d(TAG, "Restored landmark dialog view");
if(getView() == null) Log.d(TAG, "No view!");
super.onViewStateRestored(savedInstanceState);
}
public void onResume() {
Log.d(TAG, "Resume landmark dialog view");
if(getView() == null) Log.d(TAG, "No view!");
super.onResume();
}
#Override
public void onStart() {
Log.d(TAG, "Start landmark dialog view");
if(getView() == null) Log.d(TAG, "No view!");
super.onStart();
}
Only onStart and onResume triggered but this.view was null. How can I get my DialogFragment's view after it's returned from another activity/fragment?
Thanks!
You need to override onCreateView(), create your view there and return it back. Then it will be available in other methods too.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.<your_view_layout>, container, false);
}
Here is more documentation and an example:
http://developer.android.com/reference/android/app/DialogFragment.html