retrieve value from second activity - java

In my MainActivity, I launch a second activity:
Button button = (Button) findViewById(R.id.btnPush);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Intent nowStart = new Intent(getApplicationContext(), AddPillScheduleActivity.class);
startActivityForResult(nowStart, RESULT_OK);
//startSecond();
}
});
Then inside my Second Activity, I would like to return a value back to the main activity.
Intent i=new Intent();
i.putExtra("ANSWER", ans);
setResult(RESULT_OK,i);
finish();
That seems to execute fine, but back in my MainActivity, I would like to grab the value. This is where I am having trouble. My debugger never stops on my onActivityResult, which is:
#Override
protected void onActivityResult(int requestCode ,int resultCode ,Intent data ) {
super.onActivityResult(requestCode, resultCode, data);
String name = getIntent().getExtras().getString("ANSWER");
if (resultCode == RESULT_OK) {
Toast.makeText(this, name, Toast.LENGTH_LONG).show();
}
Can someone shed a little light? Thanks.

You're not getting the value from the right intent, the one that comes with the method. Modify your code to the following:
#Override
protected void onActivityResult(int requestCode ,int resultCode ,Intent data ) {
super.onActivityResult(requestCode, resultCode, data);
String name = data.getStringExtra("ANSWER");
if (resultCode == RESULT_OK) {
Toast.makeText(this, name, Toast.LENGTH_LONG).show();
}
}
Use the getStringExtra method as you put a String in your intent and not a bundle. Also, not the best practice use the same code for the requestCode and resultCode.

String name = getIntent().getExtras().getString("ANSWER");
is accessing the wrong intent. getIntent() returns the intent that started the activity. You want
String name = data.getExtras().getString("ANSWER");
Also, the second parameter of startActivityForResult() is a request code, so using RESULT_OK -- althought it still works -- is confusing.

Related

StartActivityForResult, but activity finishes

I am trying to use Adobe Image Edit SDK to edit a photo then redirect to another activity, from my custom camera activity.
This works from another activity, simply by creating the Image edit Intent, using startActivityForResult, then treating the "Done" callback in said activity, in the method onActivityResult.
Intent imageEditorIntent = new AdobeImageIntent.Builder(mContext)
.setData(selectedImageUri)
.withToolList(tools)
.withOutput(new File(mLastSavedFilePath))
.build();
startActivityForResult(imageEditorIntent, 2);
and then
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 2) { // i get here
However, when I do this from my Custom Camera Activity, the activity ends when I click "done" in the image edit sdk (its onDestroy is called) before it gets to the result
Intent intent = FileUtils.getInstance().SavePhoto(data, mContext); //this returns an AdobeImageIntent
startActivityForResult(intent, 1);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//this never gets called, because activity finishes, but why?
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
So why is the activity finishing, if the other one does not?
Turns out this was my fault, I did not notice I had android:noHistory="true"
in the manifest for the second activity

onActivityResult in Fragment can't access UI elements

I have a button in Fragment when I press it I open a new activity for result but When I return back to my fragment I found all UI element = null
Please find the code
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), MyActivity.class);
getActivity().startActivityForResult(intent, "3030");
}
});
when choose a value from activity I should back to fragment and set data to textview in the activity.
Intent intent = Activity.this.getIntent();
intent.putExtra("categoryId", id);
intent.putExtra("categoryName", name);
setResult(RESULT_OK, intent);
finish();
and I have put that in the activity that contains the fragment
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 3030 && resultCode == RESULT_OK) {
Fragment fragment = mTabFragments.get(MyFragment.class.getName());
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
and in fragment
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 3030 && resultCode == Activity.RESULT_OK) {
int categoryId = data.getIntExtra("categoryId", 0);
String categoryName = data.getStringExtra("categoryName");
mChooseCategoryTextView.setText(categoryName);
}
}
the problem now that mChooseCategoryTextView is null
Can anyone tell me what is the problem?
To get result in fragment
startActivityForResult(intent,REQ_CODE);
not
getActivity().startActivityForResult(intent,REQ_CODE);
I think the question how you initialise this view?
Since your lunching another activity so your whole fragment my be reconstruct or only onViewCreated recalled again.
So my guess is that you don't reinitialize or override mChooseCategoryTextView reference in one of fragment callbacks.
Try to add more logs and check what's happening for this reference
I believe the error is in the line
Fragment fragment = mTabFragments.get(MyFragment.class.getName());
I assume mTabFragments in an adapter of some sort? I'd have to look at it's code to be sure, but it sounds like it's not returning the right fragment. Make sure that the reference it's returning is the same as the fragment that is being shown on screen.

Android, Get result from third activity

In first activity, there is empty ListView and Button.
When I press button, it starts second activity that has ListView of categories.
After I click into one of listElements it will start third activity that has ListView with elements that are belong to my chosen category.
When I choose element of third ListView it must send me back to first activity, where my chosen element is added to my empty ListView
Use Intent.FLAG_ACTIVITY_FORWARD_RESULT like this:
FirstActivity should start SecondActivity using startActivityForResult().
SecondActivity should start ThirdActivity using this:
Intent intent = new Intent(this, ThirdActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivity(intent);
finish();
This tells ThirdActivity that it should return a result to FirstActivity.
ThirdActivity should return the result using
setResult(RESULT_OK, data);
finish();
At that point, FirstActivity.onActivityResult() will be called with the data returned from ThirdActivity.
Though I'd implore you to change your architecture design, it is possible to do it like this:
File ActivityOne.java
...
startActivityForResult(new Intent(this, ActivityTwo.class), 2);
...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && data != null) {
//Collect extras from the 'data' object
}
}
...
File ActivityTwo.java
...
startActivityForResult(new Intent(this, ActivityTwo.class), 3);
...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && data != null) {
setResult(resultCode, data);
finish();
}
setResult(RESULT_CANCELLED);
}
...
File ActivityThree.java
...
//Fill the Intent resultData with the data you need in the first activity
setResult(RESULT_OK, resultData);
finish();
...

How does the Intent passed from the onActivityResult argument work with my application?

#Override
public void onActivityResult(int reqCode, int resultCode, **Intent data**){
super.onActivityResult(reqCode, resultCode, **data**);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = **data**.getData();
Cursor c = getContentResolver().query(**contactData**, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// TODO Whatever you want to do with the selected contact name.
//ImageView imageView = (ImageView)findViewById(R.id.imageView);
//Picasso.with(this).load("https://cms-assets.tutsplus.com/uploads/users/21/posts/19431/featured_image/CodeFeature.jpg").into(imageView);
FragmentManager FM = getFragmentManager();
FragmentTransaction FT = FM.beginTransaction();
FragmentActivity F1 = new FragmentActivity();
FT.add(R.id.frame_layout, F1);
FT.commit();
}
}
break;
}
}
Can someone explain how the data variable in the onActivityResult argument is used to make this code work?
I see that the variable is used to call getData() but I'm confused as to how this variable is connected to the Intent outside of this method.
Furthermore, what exactly does calling data.getData() do ?
Basically I'm trying to understand this snippet of the code
public void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
Could anyone help me make sense of it?
The data variable is the Intent that you have specified in the closing Activity. When you want to finish the Activity you called with startActivityForResult(), you should call setResult().
As first parameter, you should set the result code (RESULT_OK, RESULT_CANCELED, ...). You can also add a second one which should be an Intent and which will contain the information you want to receive in onActivityResult(). And that is the data variable in onActivityResult().
If you want to know more about getData(), you can check this : http://developer.android.com/reference/android/content/Intent.html#getData()
Take a look here : Click me and than the first answer
At the link you can see that you can give the Intent data a bundle or extras, which you get with your getData() method.
Let's assume that the called Activity (started by startActivityForResult()) sets the result before finishing as follows:
Intent data = new Intent();
data.putExtra ("aValue", 42);
getActivity().setResult(Activity.RESULT_OK, data);
finish();
In order to get the value in the calling activity, use
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
int aValue = data.getIntExtra("aValue", -1);
....
}
}
This example is based on an int, however, there are a lot of other value types can be passed. See Androids Intent documentation.
p.s.: let me add that it works in the same way with void Intent.setData(Uri) and Uri Intent.getData() instead of putExtra(...) and getExtra(...)

how to handle a getIntent() method with java nullpointerexception

I have 2 activities in my application, Activity1 and Activity2.When the app launches Acitivity1 is the the one that is called.Clicking on a button in Activity1 should take you to Activity2.
In Acivity2,some data processing is done then i send back data to Activity1 using an intent like this:
Intent in=new Intent(getApplicationContext(), Activity1.class);
in.putExtra("data", data);
startActivity(in);
Then getting back to Activity1 i obtain the intent data:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
String data =(getIntent().getExtras().getString("data"));
The problem here is that the first time the app launches it checks for the intent data and it does not exist so i get the nullpointerexception error.how can i make sure it checks for the intent data when Activity2 is the previous class?
You can check if the intent is existing using:
getIntent().hasExtra("data");
This will return you a boolean.
Also if oyu want to return some datas to the first activity, your should start the second one with startActivityForResult
if (extras != null) {
if (extras.containsKey("data")) {
boolean hasData = extras.getBoolean("data", false);
// TODO: Do something with the value of "data".
}
}
put a check over it
if(getIntent().getExtras()!=null){
String data =(getIntent().getExtras().getString("data"));
}
Follow the following steps
1: from your activity1's button click call as follow
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
2: In your Activity2 set the data which you want to return back to Activity1 as follow and if you don't want to return back don't set anything.
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
if you don't want to return data:
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
3: now again in your Activity1 handle the return data as follow
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
EDIT:
and if you strictly want to use your own method as in your question try this:
in your Activity1 you obtain the intent data as:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
String data ="default value";
try{
data =(getIntent().getExtras().getString("data"));
}catch(Exception e){
}
}
use ActvityForResult.
replace these codes.
in ACTVITY1:
put this after onCreate:
#Override
protected void onActivityResult(int requestCode ,int resultCode ,Intent data ) {
super.onActivityResult(requestCode, resultCode, data);
String name =data.getStringExtra("data");
if(resultCode == RESULT_OK){
switch(requestCode){
case 2:
if(resultCode == RESULT_OK){
Toast.makeText(this, name, Toast.LENGTH_LONG).show();
}
}
}
in ACTIVITY2:
Intent intent=new Intent();
intent.putExtra("data",data);
setResult(2,intent);
finish();

Categories

Resources