onActivityResult shows null for intent-data [duplicate] - java

I'm new to android . This might be the simplest question of all !! but I couldn't figure out whats gone wrong here,
I was trying to create a basic example for passing values through intent.So I need to pass data to Main Activity when I close my Second Activity here is the code
IntentTest1(MainActivity)
public void onClick(View arg0) {
// TODO Auto-generated method stub
MyClass.myToast("Clicked",getApplicationContext());
Intent myIntent = newIntent(getApplicationContext(),SecondPage.class);
startActivityForResult(myIntent,0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == 0 && resultCode == RESULT_OK)
if(data.hasExtra("title"))
{
MyClass.myToast(""+resultCode+""+requestCode, getApplicationContext());
String str = data.getExtras().getString("title").toString();
titleText.setText(str);
}
super.onActivityResult(requestCode, resultCode, data);
}
SeconPage
public void finish()
{
Intent returnIntent = new Intent(getApplicationContext(),Intenttest1.class);
returnIntent.putExtra("Welcome Back!!","title");
setResult(RESULT_OK, returnIntent);
// below was for tosting and it works!!
MyClass.myToast("finally",getApplicationContext());
super.finish();
}
I think there is some mistake in receiving the intent ,I couldn't figure out.
Answers and Advises are needed
thanks in advance

The first problem is when you create your Intent to send back to the first Activity. Since you are using startActivityForResult() you want to use an empty constructor. So change
Intent returnIntent = new Intent(getApplicationContext(),Intenttest1.class);
to
Intent returnIntent = new Intent();
The second problem is that you have your key/value pair backwards in your Extras. The key, which is what you look for with getStringExtra() etc... should be the first in the pair. So this
returnIntent.putExtra("Welcome Back!!","title");
should be
returnIntent.putExtra("title", "Welcome Back!!");
Off-topic
I would consider using relevant names as your params. For example, I would change your onClick() from
public void onClick(View arg0)
to
public void onClick(View view)
view, v, or something similar makes more sense since the argument actually is a view and it will be more readable
I would also recommend using the Activity Context for your Intent which you can get from the argument (the View) passed into onClick(). So change it to
public void onClick(View v)
{
MyClass.myToast("Clicked",getApplicationContext());
Intent myIntent = newIntent(v.getContext(),SecondPage.class);
startActivityForResult(myIntent,0);

You have to use
if(data.hasExtra("Welcome Back!!"))
instead of
if(data.hasExtra("title"))
in onActivityResult. Welcome Back!! is the key and title is the value for that key in your extras.

try this code:
Intent returnIntent = new Intent(getApplicationContext(),Intenttest1.class);
returnIntent.putExtra("Key name here in ur case title","Value name");
setResult(RESULT_OK, returnIntent);
// below was for tosting and it works!!
MyClass.myToast("finally",getApplicationContext());
super.finish();
}

Related

Android onActivityResult() not firing

I am aware of the plenty of questions similar to this one, yet none of the solutions mentioned there work for me, and I'm not quite sure why.
I have the following setup:
Launching from MainActivity.java:
Button b = findViewById(R.id.btn_b);
b.setOnClickListener(new View.onClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Activity2.class);
startActivityForResult(intent, 0);
}
});
Returning values from Activity2.java:
#Override
public onBackPressed() {
System.out.println("Here"); // this can be seen in the logcat
Intent retIntent = new Intent();
// putExtra some return values
setResult(RESULT_OK, retIntent);
finish();
}
Receiving data back at MainActivity.java:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("Returning"); // this doesn't fire at all
if (data != null) { // I know there will be no other activities, and I want to act on whatever result I get
// extract and do something with data
}
}
I really don't understand what is going on here. Can someone please help explain, and how it can be fixed? I'll be happy to provide more information if needed.
Thank you for your time.
change this line in your MainActivity.java to
startActivityForResult(intent, 1);
and then in the method onBackPressed() call the method setResult like this
setResult(RESULT_OK);
then in the onActivityResult method write this condition.
if (resultCode == Activity.RESULT_OK) {//place your logic here}
Please let me know if this worked for you.

Start activity for result not work, between different activities

I have the main page where the photo is loaded, depending on what the array on the other page contains, in order to synchronize them I used StartActivityForResult();.
It will works like this: MainActivity has a photo, i press showMore button(open showMoreActivity), at showMoreActivity change text and after i finish showMoreActivity, MainActivity load the new photo depends on new text, but real it doesn`t change photo.
Can you help me? Where the mistake is?
buttonShowMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ShowMore.class);
onStop();
getActivity().startActivityForResult(intent, 1);
}
});
onClick button ShowMore Listener
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {return;}
String dataStringExtra =data.getStringExtra("name1");
Picasso.get().load( dataStringExtra + ".jpg").into(imageViewFirstOfCurrentList);
}
onActivityResult method
Intent intent = new Intent();
intent.putExtra("name1", List.get(0).toString());
setResult(RESULT_OK, intent);
finish();
when close showMore Activity
try removing call to onStop() in your onClick() method

Use onActivityResult to call a function

I have an PopUpActivity which pops up a window and i'm very satisfied with that.
However, I want to be able to return information from the popup window back to the parent activity, but also be able to call a function on the parent activity once the popup window is closed. Could someone help me?
Here is my code in the PopUpActivity:
public void closePopUpAndSendResultBack(){ // and how can i pass data to the previous activity?
//https://developer.android.com/training/basics/intents/result
Intent data = new Intent();
data.putExtra("data", "yo");
//startActivityForResult(data, 1); // gives me the error : android.content.ActivityNotFoundException: No Activity found to handle Intent { (has extras) }
setResult(Activity.RESULT_OK, data);
finish();
}
and here is my parent(MainActivity) function that I want to get called once the popUpWindow is closed:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
nameTextField.setText(""); // how can i get Yo inside here?
showTheButton(); // and how can this function get called?
}
}
}}
Also, here is how I make that window Pop up from my Mainactivity:
theOkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pop_up_that_window = new Intent(MainActivity.this,PopActivity.class);
pop_up_that_window.putExtra("first", "Velkommen du der!");
startActivity(pop_up_that_window);
}
});
}
Could someone help me please?
In MainActivity use:
theOkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pop_up_that_window = new Intent(MainActivity.this,PopActivity.class);
pop_up_that_window.putExtra("first", "Velkommen du der!");
MainActivity.this.startActivityForResult(pop_up_that_window, 1);
}
});
And still in MainActivity in onActivityResult() use this code:
String yo = data.getStringExtra("data")
nameTextField.setText(yo);

Meaning of a code related to GALLERY_REQUEST

I have used the following code to get a picture from the gallery in an app on clicking a button. It works fine but I just wanted to know the meaning of the codes used. Could someone help me in it?
private ImageButton mSelectImage;
public static final int GALLERY_REQUEST =1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mSelectImage = (ImageButton)findViewById(R.id.imageSelect);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
Uri imageUri = data.getData();
mSelectImage.setImageURI(imageUri);
}
}
This is the requestCode. It helps you to identify from which Intent you came back. For example if you have two or more intent for camera request and for the Contact request.Whenever the subsequently called finish and need to pass data back to Acivity, now you need to identify in your onActivityResult from which intent call you are returning from and put your handling logic accordingly.
public static final int CAMERA_REQUEST = 101;
public static final int CONTACT_VIEW = 202;
#Override
public void onCreate(Bundle savedState)
{
super.onCreate(savedState);
// For CameraRequest you would most likely do
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// For ContactReqeuest you would most likely do
Intent contactIntent = new Intent(ACTION_VIEW, Uri.parse("content://contacts/people/1"));
startActivityForResult(contactIntent, CONTACT_VIEW);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == Activity.RESULT_CANCELED) {
// code to handle cancelled state
}
else if (requestCode == CAMERA_REQUEST) {
// code to handle data from CAMERA_REQUEST
}
else if (requestCode == CONTACT_VIEW) {
// code to handle data from CONTACT_VIEW
}
}
GALLERY_REQUEST is a request code which is used like token, imagine you go into mall with bag, but they can't let you in with the bag so you have to put your bag outside the mall and guy will gives you a token, so when you will come back you give him that token and he will give your bag.
This token is managed just because you are not the only one who came with the bag there may be more, as the rule all person have to put their bag outside mall, but how to identify which bag belongs to which person,they used token.
Just like that request code is used, you may going to several other apps via implicit intent from your activity but when you came back, one method called for all intent: onActivityResult now you have request code to identify that from which activity is user coming from.

Can I pass an Intent extra on finish()?

I'm wondering, is it possible to send information to the activity that I return to after calling finish()?
For example, I have an Activity SendMessageActivity.class which allows the user to post a message to their feed. Once that message has been saved to the server, I call finish(). Should I instead just start my MainActivity.class with a new Intent? Or is it better for life cycle development to just finish SendMessageActivity.class?
I don't see the point of starting a new activity since closing the current one will always bring you back to MainActivity.class. How can I just send a String extra after finishing the current Activity?
Use onActivityResult.
This might help you to understand onActivityResult.
By using startActivityForResult(Intent intent, int requestCode) you can start another Activity and then receive a result from that Activity in the onActivityResult() method.So onActivityResult() is from where you start the another Activity.
onActivityResult(int requestCode, int resultCode, Intent data) check the params here. request code is there to filter from where you got the result. so you can identify different data using their requestCodes!
Example
public class MainActivity extends Activity {
// Use a unique request code for each use case
private static final int REQUEST_CODE_EXAMPLE = 0x9988;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an Intent to start AnotherActivity
final Intent intent = new Intent(this, AnotherActivity.class);
// Start AnotherActivity with the request code
startActivityForResult(intent, REQUEST_CODE_EXAMPLE);
}
//-------- When a result is returned from another Activity onActivityResult is called.--------- //
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// First we need to check if the requestCode matches the one we used.
if(requestCode == REQUEST_CODE_EXAMPLE) {
// The resultCode is set by the AnotherActivity
// By convention RESULT_OK means that what ever
// AnotherActivity did was successful
if(resultCode == Activity.RESULT_OK) {
// Get the result from the returned Intent
final String result = data.getStringExtra(AnotherActivity.EXTRA_DATA);
// Use the data - in this case, display it in a Toast.
Toast.makeText(this, "Result: " + result, Toast.LENGTH_LONG).show();
} else {
// AnotherActivity was not successful. No data to retrieve.
}
}
}
}
AnotherActivity <- This the the one we use to send data to MainActivity
public class AnotherActivity extends Activity {
// Constant used to identify data sent between Activities.
public static final String EXTRA_DATA = "EXTRA_DATA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
final View button = findViewById(R.id.button);
// When this button is clicked we want to return a result
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create a new Intent as container for the result
final Intent data = new Intent();
// Add the required data to be returned to the MainActivity
data.putExtra(EXTRA_DATA, "Some interesting data!");
// Set the resultCode to Activity.RESULT_OK to
// indicate a success and attach the Intent
// which contains our result data
setResult(Activity.RESULT_OK, data);
// With finish() we close the AnotherActivity to
// return to MainActivity
finish();
}
});
}
#Override
public void onBackPressed() {
// When the user hits the back button set the resultCode
// to Activity.RESULT_CANCELED to indicate a failure
setResult(Activity.RESULT_CANCELED);
super.onBackPressed();
}
}
Note : Now check in MainActivity you startActivityForResult there you specify a REQUEST_CODE. Let's say you want to call three different Activities to get results.. so there are three startActivityForResult calls with three different REQUEST_CODE's. REQUEST_CODE is nothing but a unique key you specify in your activity to uniquely identify your startActivityForResult calls.
Once you receive data from those Activities you can check what is the REQUEST_CODE, then you know ah ha this result is from this Activity.
It's like you send mails to your lovers with a colorful covers and ask them to reply in the same covers. Then if you get a letter back from them, you know who sent that one for you. awww ;)
You can set result of an activity, which allow you to data into an initent.
In your first activity, call the new one with startActivityForResult() and retrieve data in method onActivityResult. Everything is in documentation.
try this:
in First Activity:
Intent first = new Intent(ActivityA,this, ActivityB.class);
startActivityForResult(first, 1);
Now in Second activity: set Result during finish()
Intent intent = new Intent();
intent.putExtra("result",result); //pass intent extra here
setResult(RESULT_OK,intent);
finish();
First activity Catch the result;
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 1
if(requestCode==1)
{
String message=data.getStringExtra("result");
//get the result
}
}
If you call finish() to avoid that the user go back to SendMessageActivity.class, you can set this flags to your intent:
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
This will open the MainActivity and remove the SendMessageActivity from the activities stack.

Categories

Resources