startActivity for result does not called on fragment - java

I'am try to use start Activity for result to pick photo from gallery but it does not called on fragment
I checked most solutions but no one work for me
please help me
newsImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent=new Intent(Intent.ACTION_PICK);
intent.setType("image*//*");
getActivity().startActivityForResult(intent,GALLERY_INTENT);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==GALLERY_INTENT && resultCode== Activity.RESULT_OK){
Uri uri=data.getData();
StorageReference filePath=mStorage.child("Photos").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
downloadUri=taskSnapshot.getDownloadUrl();
Picasso.with(getActivity().getApplicationContext()).load(downloadUri).fit().centerCrop().into(newsImg);
Toast.makeText(getActivity().getApplicationContext(),"success",Toast.LENGTH_SHORT).show();
publishBtn.setEnabled(true);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity().getApplicationContext(),"fail",Toast.LENGTH_SHORT).show();
}
});
}

Try using this and then find out, before giving my answer I would suggest you to be please do some research or search the exact thing in short form like you want to use the use the gallery intent, just use the image picker in android or gallery intent in android. For going from the fragment we use the getContext() rather than using ActivityIntent like MainActivity.this.
For Calling the startActivity for result do like this :
private final int REQUEST_CODE = 1
class ImagePicker extends Fragment{
/*here we are calling the start activity for result
supposing you know how to use the gallery intent so just giving you
the answer what you want */
Intent intent = new Intent(getContext(), YourClass.class);
startActivityForResult(intent, REQUEST_CODE);
}
And in onActivityResult() you get the result in the same Fragment or Activity after finishing this.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
//get your gallery image uri data here
}
}
Hope it helps and please refer to this link to read more about the how to get the data in the same Activity.
About startAcitivityForResult in android
Hope that helps! Thanks
EDITS
Since your code seems fine for gallery intent but I think there is problem with your gallery intent. Try this also and see if it works.
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, RESULT_CODE;
Here specifically I have used the inten.setType("image/*") and one more thing, make this simple, do not use getActivity.startActivityForResult() just make it simple, startAcitivityForResult() will also work fine and use getContext() despite of doing getActivity().getApplicationContext(). Try amending this thins things and tell me whether it works or not!

Related

How to upload and save an image from gallery. startActivityForResult deprecated

I'm currently learning how to use android studio in java and am trying to make a social media app. I am currently creating an edit profile page where the user would update their details and upload a profile picture.
I have been following tutorials online and all of the ones I have come across use the startActivityForResult method. It has been crossed out and wont call the method as it is deprecated. But I don't know what to use instead.
`ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//open gallery
Intent OpenGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(OpenGalleryIntent, 1000);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #androidx.annotation.Nullable Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1000){
if(resultCode == Activity.RESULT_OK){
Uri imageUri = data.getData();
ProfileImage.setImageURI(imageUri);
UploadImageToFirebase(imageUri);
}
}
}
private void UploadImageToFirebase(Uri image){
StorageReference fileRef = storageReference.child("Profile.jpg");
fileRef.putFile(image).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(Edit_Profile.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
}
});![enter image description here](https://i.stack.imgur.com/padRc.jpg)`
I know there is an alternative but I don't understand how it works.
startActivityForResult is indeed deprecated in later versions of AndroidX Activity and Fragment APIs (while I believe you can still use it despite of warning). New way to get result from activity is registerForActivityResult.
In your code you would need to create a launcher, which will handle result (selected image)
private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK
&& result.getData() != null) {
Uri photoUri = result.getData().getData();
//use photoUri here
}
}
);
and then launch this launcher in onClickListener
profileImage.setOnClickListener(view -> {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
launcher.launch(intent);
});
Yes startActivityForeResult is deprecated.
Now you can use ActivityResultLauncher for the callbacks
https://developer.android.com/training/basics/intents/result#java

My application crashes when getting uri from user

I have a problem. I want to get the user of my app to select an audio file from storage using ACTION_GET_CONTENT, and my mainActivity crashes at that point.
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,1);
audioPath = intent.getData().getPath(); //This is were the crash happens
audio = Uri.parse(audioPath);
}
I'm new in android programming and there is surely something that I fail to understand. The error is as follows: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getPath()' on a null object reference
You have to override on Activity Result in your activity. DO NOT use the same intent like you have done. You have to use the Intent returned in onActivityResult method. So your code should be:
This should be your method to Pick an Audio
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,1); //This 1 is your request code remember it
}
Then Override the onActivityResult method as
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
//The intent from this method is the one you need to get data from!
if (requestCode == 1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
audioPath = intent.getData().getPath();
audio = Uri.parse(audioPath);
}
}
}
For more information on this method and receiving data from Activity Result check this official training from Android. Happy Coding!

App Crashing After Selecting Picture From Gallery

So whenever I select a picture from the gallery in my app, it crashes. Here is the code for the button to the gallery and selected picture to the imageview.
pickImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
}
private void openGallery() { //opens the gallery
Intent gallery =
new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
Uri imageUri = data.getData();
imageView2.setImageURI(imageUri);
}
}
Please comment if you need more information, I desperately need help, as this is a very major roadblock for me.
Without the Logs, I can recommend on the following:
Make sure that pickImageButton isn't null.
Make sure that imageView2 isn't null.
Make sure that in manifest your Activity is in:
android:launchMode="singleTop"

onActivityResult doesn't get called within Dialog Fragment

So, I've read some threads about this, but I can't get this to work.
Basically I have this Dialog in which the user chooses to take a new pic or select a pic from their gallery. Here is the code:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setCancelable(true)
.setItems(R.array.galeria_camera_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int userChoice) {
if (userChoice == 1) {
// take photo
}
if (userChoice == 0) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 1);
}
}
});
return builder.create();
}
And then, the onActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//choose file from gallery
}
Can anyone help? Before I have to re-read 10 pages worth of theory again... I'm quite new to this kind of things (onResult). Thank you.
Try implementing something like this in the activity where the dialog fragment is fired from:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.myFragmentId);
fragment.onActivityResult(requestCode, resultCode, data);
The underlining activity is what will receive onActivityResult, so u should be able to 'point' it towards onActivityResult of the dialog fragment.
The easy way to fix this is to move your fragment's onActivityResult into your activity, or you can use your activity's onActivityResult to call a method in your fragment.
I looked at my code and apparently I managed to get around this by calling this.getActivityForResult from my fragment, and then the result returned to my fragment, but I'll be honest with you: I don't remember writing this.
Ok, these two things made it work:
getActivity().startActivityForResult(galleryIntent, 1); You have to add getActivity()
As you guys said, you have to declare the onActivityResult() in the Activity itself.
Thanks guys!

Refresh text EditText after finish()

I created a 'New File' activity using
startActivityForResult(new Intent(MainActivity.this, NewFile.class),1);
The NewFile activity lets users set certain options for their text file then after clicking a button a string is saved to a static variable in my StringBuilder class and finish(); is called. How can I load this new string into the MainActivity's EditText? onCreate() is only called when the activity is first created right?
Do it on onResume or onActivityResult. It would be ideal though onActivityResult since you've used startActivityForResult, before finishing the other activity you set the setResult(int resultCode, Intent data) if you have intent to sent back or if none setResult(int resultCode). I think it is better to put the string which will be used to update your EditText as extra in the intent, then set the text using that string in onActivityResult method.
#Override
protected void onResume() {
super.onResume();
et.setText(DocumentBuilder.docText);
}
in your class NewFile.java :
String strName = "toto";
Intent intent = new Intent();
intent.putExtra("name", "toto");
setResult(1, intent);
finish();
in your MainActivity.java :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// Handle successful result
String name = intent.getStringExtra("name");
editText.setText(name);
}
}
}
refer this tutorial for more explanations

Categories