How to make an intent and launch an activity in onActivityResult()? - android

I am trying to launch an activity after a user has selected a photo. I was trying to do this:
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent selectImageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
selectImageIntent.setType("image/*");
startActivityForResult(selectImageIntent, 1);
Intent goToActivityIntent = new Intent(view.getContext(), SendPhotoChangeActivity.class);
goToActivityIntent.putExtra("email", email);
goToActivityIntent.putExtra("donorEmail", donorEmail);
goToActivityIntent.putExtra("orderId", orderId);
goToActivityIntent.putExtra("uriString", uriString);
view.getContext().startActivity(goToActivityIntent);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
uriString = data.getData().toString();
}
}
But I realised that with this code, the code for launching the activity (SendPhotoChangeActivity) executes before the user selects the image, crashing the app because the uriString variable is null.
I tried simply copy/pasting the code into onActivityResult(), but the view variable (in view.getContext()) was, of course, not recognized in onActivityResult().
I am thinking of simply replacing view.getContext() by getApplicationContext() in onActivityResult(). Is this the right thing to do? If not, please tell me how I can start an activity in onActivityResult().

If you are in Activity then you can just use this as Context
Intent goToActivityIntent = new Intent(this, SendPhotoChangeActivity.class);
If you are in a Fragment then you can obtain Context by calling getContext()
Intent goToActivityIntent = new Intent(getContext(), SendPhotoChangeActivity.class);
And use that code inside onActivityResult() as you were trying to.

set an integer code for the act of selecting a picture like REQUEST_CODE_TAKE_PICTURE so you know that has happened, this works ok in Kotlin, I assume that works as well with java:
if (requestCode == REQUEST_CODE_TAKE_PICTURE && resultCode == Activity.RESULT_OK) {
Intent goToActivityIntent = new Intent(view.getContext(),SendPhotoChangeActivity.class);
goToActivityIntent.putExtra("email", email);
goToActivityIntent.putExtra("donorEmail", donorEmail);
goToActivityIntent.putExtra("orderId", orderId);
goToActivityIntent.putExtra("uriString", uriString);
view.getContext().startActivity(goToActivityIntent);
if (data == null) {
//Display an error
println("error accuered at onActivityResult ")
return
}

Have you tried this simpler one:
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent selectImageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
selectImageIntent.setType("image/*");
startActivityForResult(selectImageIntent, 1);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
uriString = data.getData().toString();
Intent goToActivityIntent = new Intent(view.getContext(), SendPhotoChangeActivity.class);
goToActivityIntent.putExtra("email", email);
goToActivityIntent.putExtra("donorEmail", donorEmail);
goToActivityIntent.putExtra("orderId", orderId);
goToActivityIntent.putExtra("uriString", uriString);
startActivity(goToActivityIntent);
}
}
Just call
startActivity(goToActivityIntent);
to call the activity.
This assumes you are calling it from your activity or fragment. If this doesn't meet your requirements, let me know. There are other ways to implement this.

Related

Activity always returns RESULT_CANCELLED despite manually setting the result as RESULT_OK

I am writing a component that allows user to pick a location based on the place indicated by the location picker. One of the requirements is to send the LatLng object back from the map activity to the activity that called the former. The problem is that returned result code is always RESULT_CANCELLED, despite setting it explicitly to RESULT_OK. Here's the code:
Calling activity:
public void getLocationBtn(View view) {
Intent i = new Intent(this, PickLocationActivity.class);
startActivityForResult(i, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
location = data.getParcelableExtra("location");
Log.d(TAG, "gotLocation: " + location);
}
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Location not chosen", Toast.LENGTH_SHORT).show();
}
}
}
Called activity:
btnFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
centerLatLang = mMap.getProjection().getVisibleRegion().latLngBounds.getCenter();
Button doneBtn = findViewById(R.id.locationPickerDoneBtn);
doneBtn.setEnabled(true);
}
});
}
public void doneBtn(View view) {
Intent returnIntent = new Intent();
returnIntent.putExtra("location", centerLatLang);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
btnFind get the coordinates, doneBtn confirms user's choice and comes back to the previous activity.
I have already tried replacing Intent returnIntent = new Intent(); with getIntent(), but it didn't work; the returned bundle was null.
it happen when your activity is using singleTask launch mode. so i recommand if you have below line in your manifest activity tab please remove it.
android:launchMode="singleInstance"

onActivityResult Intent is null when passing Intent from Adapter

I am facing a strange issue while returning to an Activity with a Result, I am passing an Intent for startActivityForResult from an Adapter like this :
Intent i = new Intent(activity, EditInfoActivity.class);
i.putExtra("id", list.get(position).getID());
activity.startActivityForResult(i, 100);
and in second Activity i.e. in EditInfoActivity in my case on a Button click I am setting Result for first activity like this:
Intent i = getIntent();
i.putExtra("isDataChange", isDataChange);
setResult(100, i);
finish();
In Activity's onActivityResult method I am able to get result code but getting Intent null.
Why? anybody have any idea on this please share.
in Activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
//Here data is null and app crash
if (data.getExtras() != null && data.getBooleanExtra("isDataChange", false)) {
recreate();
}
}
}
First, you need to start the Activity with a REQUEST_CODE:
// Here we set a constant for the code.
private final int REQUEST_CODE = 100;
Intent i = new Intent(activity, EditInfoActivity.class);
i.putExtra("id", list.get(position).getID());
activity.startActivityForResult(i, REQUEST_CODE);
Then you need to send RESULT_OK when finishing EditInfoActivity:
Intent i = getIntent();
i.putExtra("isDataChange", isDataChange);
setResult(RESULT_OK, i);
finish();
Then handle the result on your first activity with this:
Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// REQUEST_CODE is defined as 100
if (resultCode == RESULT_OK && requestCode == 100) {
// do process
}
}
setResult TAKES RESULT_CODE instead of REQUEST_CODE.
Replace your code with this, May be it will solve your problem.
setResult(RESULT_OK, i);
And in yout onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
//Here data is null and app crash
if (data != null && data.getBooleanExtra("isDataChange", false)) {
recreate();
}
}
}
Two mistakes. You are passing the intent that was used to launch the activity you are finishing. Use new Intent() instead.
When setting activity result you should use result codes, not a request code setResult(RESULT_OK) alternatively RESULT_CANCELED and handle the response accordingly.

onActivityResult return null getExtra value after return back from permission dialogue

Here is my code:
final Intent intent = new Intent(this, SelectWidgetActivity.class);
startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK ) {
String selectedName = data.getStringExtra(SelectWidgetActivity.SELECTED_WIDGET);
if(!mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, info.provider)) {
Intent bindIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
bindIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
bindIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider);
bindIntent.putExtra(SelectWidgetActivity.SELECTED_WIDGET, selectedName);
startActivityForResult(bindIntent, REQUEST_BIND_APPWIDGET);
}
}
}
I put String on the first call of startActivityForResult and on the second call I'm trying to get the same string, but getting null. For example on the first call selectedName="Calendar", the second call onActivityResult() selectedName=null
Any ideas?
you must be even checking for the requestCode in onActivityResult that you send when you are making this call
startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
Try this
if (requestCode == REQUEST_CREATE_APPWIDGET && resultCode == Activity.RESULT_OK) {
//do your work here;
}

FragmentActivity onActivityResult data is null

I know there are several questions about this, but I don't found a solution for my problem.
I have ActivityA which extends AppCompatActivity. It starts an ActivityB
Activity A
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("data", data);
startActivityForResult(intent, 1);
....
#Override
protected void onActivityResult(int requestCode, int result, Intent intent) {
super.onActivityResult(requestCode, result, intent);
if (requestCode != 1) { // check code
return;
}
if (intent == null) { // HERE INTENT IS NULL
return;
}
}
Activity B
// code called when an asynctask is done
Intent i = new Intent();
i.putExtra("dataone", "test");
i.putExtra("datatwo", objet);
setResult(RESULT_OK, i);
finish();
I don't understand why intent is null in onActivityResult() method.
Two things. I would refactor your code like the following:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// example
// String myString = intent.getString("myStringFrom2ndActivity")
}
}
}
and also make sure that you are calling the right RESULT_OK. It should be something like Activity.RESULT_OK.

What is Intent from onActivityResult Parameters

Here is my first activity code from where I call the second Activity:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
startActivityForResult(new Intent("chap.two.Chapter2Activity2"),request_Code);
}
return false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_Code) {
if (resultCode == RESULT_OK)
Toast.makeText(this,data.getData().toString(),Toast.LENGTH_SHORT).show();
}
}
And here is a code of chap.two.Chapter2Activity2:
Button n = (Button) findViewById(R.id.btn_OK);
n.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent data = new Intent();
//---get the EditText view---
EditText txt_username =(EditText) findViewById(R.id.txt_username);
//---set the data to pass back---
data.setData(Uri.parse(txt_username.getText().toString()));
setResult(RESULT_OK, data);
//---closes the activity---
finish();
}
});
here I see that setResult(RESULT_OK, data) has two arguments but
onActivityResult(int requestCode, int resultCode, Intent data) has three and I want know how onActivityResult gets value for third parameter? How it works can anyone tell me? Why isn't this error ?
When you call Activity.startActivityForResult(), you set the requestCode. Later, this request code is needed by onActivityResult() in order to determine what Activity is sending data to it. We don't need to supply requestCode again on setResult() because the requestCode is carried along.
The data is intent data returned from launched intent. We usually use this data when we set extras on the called intent.
Consider this example:
CALL SECOND ACTIVITY
Intent i = new Intent(MainActivity.this, CheckActivity.class);
startActivityForResult(i, REQUEST_CODE_CHECK);
ON SECOND ACTIVITY, SET INTENT RESULT
getIntent().putExtra("TADA", "bla bla bla");
setResult(RESULT_OK, getIntent());
finish();
BACK TO FIRST ACTIVITY, ONACTIVITYRESULT()
if(requestCode == REQUEST_CODE_CHECK && resultCode == RESULT_OK){
text1.setText(data.getExtras().getString("TADA") );
}
There you go. You should now understand what is Intent data and how to set and fetch the value.
Third parameter is Intent, which you sent from the sub-Activity(Second Activity, which is going to finish).
If you want to perform some calculations or fetch some username/password in sub-activity and you want to send the result to the main activity, then you place the data in the intent and will return to the Main activity before finish().
After that you will check in onActivityResult(int, int, Intent) in main activity for the result with Intent parameter.
Example::
MainActivity:
public void onClick(View view) {
Intent i = new Intent(this, subActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("username") && data.hasExtra("password")) {
String username = data.getExtras().getString("username");
String password = data.getExtras().getString("password");
}
}
subActivity::
#Override
public void finish() {
// Create one data intent
Intent data = new Intent();
data.putExtra("username", "Bla bla bla..");
data.putExtra("password", "*****");
setResult(RESULT_OK, data);
super.finish();
}

Categories

Resources