My application crashes when getting uri from user - java

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!

Related

How to pass Parceable in an intent?

I am having a problem receiving the extras that are coming in with my intent from a different activity. When I run the code and use break points at the line where the object is actually being created I can see it being created using the debugger. I can see the object being put in the putExtra() function.
Upon arrival at the resulting activity though using the function getParceableExtra() always returns null upon receiving the intent.
//In the receving activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 1){
if(resultCode == Activity.RESULT_OK){
Intent extras = getIntent();
if(extras != null){
Goals addToList = extras.getParcelableExtra(GOAL_PASSING);
if(addToList != null)
mGoal.add(addToList);
}
}
}
}
//In the sending activity
incrementMGoal = (findViewById(R.id.create_goal_button));
incrementMGoal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent returnIntent = new Intent();
Goals newGoal = new Goals(GT,GD,GDueDate);
returnIntent.putExtra(MainActivity.GOAL_PASSING,newGoal);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
I expect when I create the intent to pass putExtra and then receive it to be put in a array. I am just receiving null however.
The Problem is that your code takes the wrong intent and not of the onActivityResult parameter data
Goals addToList = data.getParcelableExtra(GOAL_PASSING);
so instead you should do this
Goals addToList = data.getParcelableExtra(GOAL_PASSING);

startActivity for result does not called on fragment

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!

Android activity does not finish and does not launch previous activity

I have 2 Activities the main activity I have called Map activity and the second that I have called Question activity when the app launch the Map activity is shown then you click the play button and the Question activity is launched with StartActivityForResult(), then when you have answered the question right the Question activity should be destroyed and created again and check the number of right answered questions and change the layout. then if you have scored 5 then Question activity should be destroyed and the Map activity will be shown but this is not happen. Here is my code
Map.class
public void OnClick_Question(View v){
Intent i = new Intent(MapActivity.this, QuestionActivity.class);
startActivityForResult(i, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(SharedPrefs.TAG, "OnActivityResult Entry");
if (resultCode == RESULT_OK) {
Log.d(SharedPrefs.TAG, "MAPActivity OnActivityResult Entry resultCode");
AssignContentView(requestCode);
}
}
Question.class
public void Next() {
Intent i = new Intent(this, QuestionActivity.class);
startActivity(i);
finish();
}
public void LevelUp() {
Log.e(SharedPrefs.TAG, "LevelUp");
super.finish();
finish(); /*This don't happen*/
}
When I see LogCat shows me this message:
09-01 11:23:03.911 901-1485/? W/ActivityManager﹕ startActivity called from finishing ActivityRecord{43386100 u0 com.example.gbb/.QuestionActivity t50 f}; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { cmp=com.example.gbb/.QuestionActivity }
Why I am doing this, is because I want to change the layout of Map Activity depending in your score.
What I'm doing wrong?
I had the same problem. I solved it by adding android:launchMode="singleTask" in the Android Manifest. Hope it works for you too.
I solved this by turning off Instant Run and re-running my code.
You can try the below code:
We need to keep the request code to be in global and static variable to access in onActivityResult method
private static final int REQUEST_CODE = 111;
public void OnClick_Question(View v){
Intent i = new Intent(MapActivity.this, QuestionActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d(SharedPrefs.TAG, "OnActivityResult Entry");
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE:
Log.d(SharedPrefs.TAG, "MAPActivity OnActivityResult Entry resultCode");
AssignContentView(requestCode);
break;
default:
break;
}
}
}
I think there is no problem in your Map class, the problem is in second class.i.e., you need to set the RESULT_OK in that intent and then you can check if (resultCode == RESULT_OK) in onActivityResult method. Below you can find the code for that
Intent intent = new Intent();
setResult(activity.RESULT_OK, intent);
finish();
Hope this is helpful:)

finishAndRemoveTask() available on API 21

I would terminate my app and cancel it from the list of recent task.
finishAndRemoveTask() is available only on API 21.
What should I use on API lower than 21??
Make an intent to the first activity in the stack and finish the current activity:
Intent intent = new Intent(this, FirstActivity.class);
intent.putExtra(EXTRA_FINISH, true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
And, in the onResume method of the FirstActivity, something like this to finish the last activity in the stack (and hopefully removing the app from the recent apps list):
if (getExtras() != null && getIntentExtra(EXTRA_FINISH, false)) {
finish();
}
I had a similar use case where I needed to finish all activities. Here is one way to do it without finishAndRemoveTask().
Make all your activities extend a base class with the following things in it:
private Boolean mHasParent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mHasParent = extras.getBoolean("hasParent", false);
}
}
// Always start next activity by calling this.
protected void startNextActivity(Intent intent) {
intent.putExtra("hasParent", true);
startActivityForResult(intent, 199);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == 199 && resultCode == FINISH_ALL) {
finishAllActivities();
}
}
protected void finishAllActivities() {
if (mHasParent) {
// Return to parent activity.
setResult(FINISH_ALL);
} else {
// This is the only activity remaining on the stack.
// If you need to actually return some result, do it here.
Intent resultValue = new Intent();
resultValue.putExtra(...);
setResult(RESULT_OK, resultValue);
}
finish();
}
Simply call finishAllActivities() in any activity, and all the activities will unwind. Ofcourse if you don't care what result the last activity returns, the code can be made much simpler.

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