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
Related
I'am trying to read the barcode via Zxing in fragment
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_caddie, container, false);
etCodigo = v.findViewById(R.id.etCodigo);
btnLeerCodigo = v.findViewById(R.id.btnLeerCodigo);
btnLeerCodigo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
escanear();
}
});
text = "";
return v;
}
public void escanear() {
IntentIntegrator intent = IntentIntegrator.forSupportFragment(FragmentCaddie.this);
//IntentIntegrator intent = new IntentIntegrator(getActivity());
intent.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
intent.setPrompt("ESCANEAR CODIGO");
intent.setCameraId(0);
intent.setBeepEnabled(false);
intent.setBarcodeImageEnabled(false);
intent.initiateScan();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Toast.makeText(getContext(), "Cancelaste el escaneo", Toast.LENGTH_SHORT).show();
} else {
text = text + " + " + result.getContents().toString() ;
etCodigo.setText(text);
escanear();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
The issue is it doesn't access the onActivityResult
The hosting activity overrides onActivityResult(), but it did not make a call to super.onActivityResult() for unhandled result codes. Apparently, even though the fragment is the one making the startActivityForResult() call, the activity gets the first shot at handling the result. This makes sense when you consider the modularity of fragments. Once I implemented super.onActivityResult() for all unhandled results, the fragment got a shot at handling the result.
Check this out:
onActivityResult is not being called in Fragment
I hope to be useful for u :)
The solution was quiet simple the onActivityResult that i implemented was Overrided from the parent activity
The solution is to call the fragment onActivityResult from the parent activity
private static final int BARECODE_REQUEST = 114910;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BARECODE_REQUEST) {
super.onActivityResult(requestCode,resultCode,data);
}
}
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);'
I have a Fragment which contains a Progressbar. I retrieve it in onCreateView() method where setVisibility() works fine.
Now, when I try to set visibility of the same progressbar (declared in fragment at class level) inside onActivityResult() nothing happens. Here is the code.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE_PROFILE_VIDEO_PATH){
if(resultCode == Activity.RESULT_OK) {
String profileVideoPath = data.getExtras().getString(ProfileVideoRecordingActivity.VIDEO_PROFILE_PATH);
Log.d("DEBUG", profileVideoPath);
//Upload to server
File profileVideo = new File(profileVideoPath);
if(profileVideo.exists()) {
pbarVideoUpload.setVisibility(View.VISIBLE);
FireBaseWrapper fileUploader = new FireBaseWrapper();
String serverFolderPath = "videoprofile";
String contentType = "video/mp4";
FireBaseAfterUpload afterUpload = new FireBaseAfterUpload() {
#Override
public void onSuccess(String uploadURL) {
Log.d("DEBUG", "Successfully uploaded video to server");
Log.d("DEBUG", uploadURL);
pbarVideoUpload.setVisibility(View.GONE);
ProfileService profileService = new ProfileService(TAG) {
#Override
protected void onPreServiceCall() {
}
#Override
protected void onPostServiceCall() {
}
#Override
public void afterSuccess(Object object) {
ReturnCode successCode = (ReturnCode) object;
if(successCode.getSuccess()){
Log.d("DEBUG", "Profile Video URL updated in DB");
}else{
Log.d("DEBUG", "Profile Video URL NOT updated in DB");
}
}
#Override
public void afterError() {
Log.d("DEBUG", "Profile Video URL NOT updated in DB");
}
};
profileService.updateVideoPath(uploadURL);
}
#Override
public void onProgress(String data) {
}
#Override
public void onFaliure() {
Log.d("DEBUG", "Error! Didn't upload");
pbarVideoUpload.setVisibility(View.GONE);
}
};
try {
fileUploader.upload(profileVideo, profileVideo.getName(), serverFolderPath, afterUpload, contentType, false);
}catch (FileNotFoundException e){
Log.e("DEBUG", "FileNotFoundException", e);
}
}
}
}
}
I tried calling setVisibility() inside an Handler and also on UI thread using runOnUiThread(). Both approaches didn't work.
How can I control visibility of progressbar inside onActivityResult() of Fragment?
I need it as I am uploading a file inside onActivityResult() and need to display progress.
I think you onActivityResult not triggered as it is in fragment. Please use the below code in your activity which hold the fragment.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Fragment fragment = (Fragment) getSupportFragmentManager().findFragmentByTag(fragmentTag);
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, intent);
}
}
put this
pbarVideoUpload.setVisibility(View.GONE);
Inside this also like I mentioned,
#Override
public void afterSuccess(Object object) {
ReturnCode successCode = (ReturnCode) object;
if(successCode.getSuccess()){
pbarVideoUpload.setVisibility(View.GONE);
Log.d("DEBUG", "Profile Video URL updated in DB");
}else{
Log.d("DEBUG", "Profile Video URL NOT updated in DB");
}
}
Fragments onCreate() was called after onActivityResult(). Hence the views were getting reinitialized and progressbar was not displayed.
Created a static variable isVideoUploading. Set its values appropriately in onActivityResult() and used it to show/hide progressbar in onCreate().
This solved half the problem. The progressbar was now visible when uploading started.
Second half of the problem was to hide the progressbar on complete of firebase async upload method. Problem was that since upload was being done in background thread which started in onActivityResult() there was no way for onCreateView() to fire again after upload was complete.
For this I sent a broadcast intent using LocalBroadcastManager when upload was complete and registered it in the same fragment. Once broadcast was received I hid the progressbar.
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
}
}