onActivityResult no shows what it should - android

I'm trying to return an EditText that has one Activity to a first Activity but when I push the button to finish de second Activity and onActivityResult is call the TextView that should show the text in the EditText save, no shos nothing.
Here's the Intent creation and the starts of the second Activity:
Intent myInt = new Intent(ActivityLoaderActivity.this, ExplicitlyLoadedActivity.class);
startActivityForResult(myInt, GET_TEXT_REQUEST_CODE);
Here's how I save the EditText in ExplicitlyLoadedActivity.java:
private void enterClicked() {
Log.i(TAG,"Entered enterClicked()");
// TODO - Save user provided input from the EditText field
Editable res = mEditText.getText();
// TODO - Create a new intent and save the input from the EditText field as an extra
Intent returnIntent = new Intent();
returnIntent.putExtra("result", res);
// TODO - Set Activity's result with result code RESULT_OK
setResult(RESULT_OK,returnIntent);
// TODO - Finish the Activity
finish();
}
And here's is the code of onActivityResult:
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String res = data.getStringExtra("result");
mUserTextView.setText(res);
}
}
In the debug mode, I can see that res has the text that I put in the EditText but it don't shos nothing in the aplication.
This is the code of mUserTextView:
private TextView mUserTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loader_activity);
// Get reference to the textView
mUserTextView = (TextView) findViewById(R.id.textView1);
This is the full code of onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "Entered onActivityResult()");
// TODO - Process the result only if this method received both a
// RESULT_OK result code and a recognized request code
// If so, update the Textview showing the user-entered text.
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String res = data.getStringExtra("result");
mUserTextView.setText(res);
}
}
}

if (requestCode == 1) {
if(resultCode == RESULT_OK){
String res = getIntent.getStringExtra("result");
mUserTextView.setText(res);
}
}
try that piece of code
and make sure GET_TEXT_REQUEST_CODE==1

I've tried the same code as you describe above, it works well. Since res is really received in onActivityResult you should check your mUserTextView related code.

Related

Setting text view from another activivty using intent extras

I am trying to get a text view to update after a user has typed in a string from another result. When using this method below I get what appears to be the edit text's code address. Something like "android.widget.Edittext(b142f388 etc." regardless of what the user types in on the other activity. What am I missing here?
String collected from user:
private void enterClicked() {
Log.i(TAG,"Entered enterClicked()");
//Save user provided input from the EditText field
String result = mEditText.toString();
//Create a new intent and save the input from the EditText field as an extra
Intent i = new Intent(ExplicitlyLoadedActivity.this, ActivityLoaderActivity.class);
i.putExtra("RESULT_STRING", result);
//Set Activity's result with result code RESULT_OK
setResult(RESULT_OK, i);
//Finish the Activity
finish();
}
Activity Result:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "Entered onActivityResult()");
// RESULT_OK result code and a recognized request code
// If so, update the Textview showing the user-entered text.
if ( resultCode == RESULT_OK){
if(requestCode == GET_TEXT_REQUEST_CODE){
String userData = data.getStringExtra("RESULT_STRING");
mUserTextView.setText(userData);
}
}
}
String result = mEditText.getText().toString();
First apply this and check result
You need to use getText() method to get text from editText:
Try using this code: String result = mEditText.getText().toString();
private void enterClicked() {
Log.i(TAG,"Entered enterClicked()");
//Save user provided input from the EditText field
String result = mEditText.getText().toString();
//Create a new intent and save the input from the EditText field as an extra
Intent i = new Intent(ExplicitlyLoadedActivity.this, ActivityLoaderActivity.class);
i.putExtra("RESULT_STRING", result);
//Set Activity's result with result code RESULT_OK
setResult(RESULT_OK, i);
//Finish the Activity
finish();
}
Instead :
private void enterClicked() {
Log.i(TAG,"Entered enterClicked()");
//Save user provided input from the EditText field
String result = mEditText.toString();
//Create a new intent and save the input from the EditText field as an extra
Intent i = new Intent(ExplicitlyLoadedActivity.this, ActivityLoaderActivity.class);
i.putExtra("RESULT_STRING", result);
//Set Activity's result with result code RESULT_OK
setResult(RESULT_OK, i);
//Finish the Activity
finish();
}

Why does onActivityResult fail to enter method?

I have an activity B called by an activity A.
In activity A:
intent = new Intent (MainActivity.this, SelectionActivity.class);
startActivityForResult(intent, RESULT_OK);
In activity B (it's about a ListView when items are clicked):
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView tv = (TextView)arg0.getChildAt(arg2);
String key = tv.getText().toString();
Intent myIntent = new Intent();
myIntent.putExtra("genre", key);
setResult(RESULT_OK,myIntent);
finish();
}
And I override the onActivityResult method like this in A:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data != null) {
Bundle b = data.getExtras();
String str = b.getString("genre");
Log.v("nope","loaded ! " + str);
r.LoadGenre(str);
}
Log.v("nope"," not loaded ! ");
}
}
But I'm never reaching any of these Log.v messages.
LogCat is clear, no errors. When running, A, it starts B perfectly, when items are clicked on B, B closes perfectly to get back to A.
You do need to pass request code to the startActivityForResult() method.
The "request code" identifies your request. When you receive the result Intent, the callback provides the same request code so that your app can properly identify the result and determine how to handle it.
In your case you didn't checking received result with requestcode
So check requestCode also in your onActivityResult method.So Change
startActivityForResult(intent, RESULT_OK);
to
startActivityForResult(intent, 200);
and
if (resultCode == RESULT_OK) {
to
if (requestCode == 200 && resultCode == RESULT_OK) {

Use onactivityresult android

I want to call a method from mainactivity in other activities. For that, I've researched a lot and found that using OnActivityResult is the best option. Can anyone please explain how to use this method with the help of an example? I've gone through similar questions but found them confusing.
Thanks!
EDIT:I have a custom dialog activity in my app. It asks the users whether they want to start a new game or not and it has two buttons yes and no. I want to implement the above method only to get the pressed button.
Define constant
public static final int REQUEST_CODE = 1;
Call your custom dialog activity using intent
Intent intent = new Intent(Activity.this,
CustomDialogActivity.class);
startActivityForResult(intent , REQUEST_CODE);
Now use onActivityResult to retrieve the result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String requiredValue = data.getStringExtra("key");
}
} catch (Exception ex) {
Toast.makeText(Activity.this, ex.toString(),
Toast.LENGTH_SHORT).show();
}
}
In custom dialog activity use this code to set result
Intent intent = getIntent();
intent.putExtra("key", value);
setResult(RESULT_OK, intent);
finish();
Start the Activity:
you do need to pass an additional integer argument to the startActivityForResult() method.You may do it by defining a constant or simply put an integer.The integer argument is a "request code" that identifies your request. When you receive the result Intent, the callback provides the same request code so that your app can properly identify the result and determine how to handle it.
static final int ASK_QUESTION_REQUEST = 1;
// Create an Intent to start SecondActivity
Intent askIntent = new Intent(FirstActivity.this, SecondActivity.class);
// Start SecondActivity with the request code
startActivityForResult(askIntent, ASK_QUESTION_REQUEST);
Return The Result:
After completing your work in second activity class simply set the result and call that activity where it comes from and lastly don't forget to write finish() statement.
// Add the required data to be returned to the FirstActivity
sendIntent.putExtra(Result_DATA, "Your Data");
// Set the resultCode to Activity.RESULT_OK to
// indicate a success and attach the Intent
// which contains our result data
setResult(RESULT_OK, sendIntent);
// With finish() we close the SecondActivity to
// return to FirstActivity
finish();
Receive The Result:
When you done with the subsequent activity and returns, the system calls your activity's onActivityResult() method. This method includes three arguments:
#The request code you passed to startActivityForResult().
#A result code specified by the second activity. This is either RESULT_OK if the operation was successful or RESULT_CANCELED if the operation failed
#An Intent that carries the result data.
#Override
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 == ASK_QUESTION_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
final String result = data.getStringExtra(SecondActivity.Result_DATA);
// Use the data - in this case display it in a Toast.
Toast.makeText(this, "Result: " + result, Toast.LENGTH_LONG).show();
}
}
}
This is my example.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Image_Request_Code && resultCode ==RESULT_OK && data != null && data.getData() != null) {
FilePathUri = data.getData();
try {
// Getting selected image into Bitmap.
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
// Setting up bitmap selected image into ImageView.
SelectImage.setImageBitmap(bitmap);
// After selecting image change choose button above text.
ChooseButton.setText("Image Selected");
}
catch (IOException e) {
e.printStackTrace();
}
}*strong text*
if (requestCode == 2000)
{
if (resultCode == Activity.RESULT_OK)
{
try {
Uri selectedImages = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImages,
filePathColumn,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
receivedImageBitmap = BitmapFactory.decodeFile(picturePath);
imageView.setImageBitmap(receivedImageBitmap);
}
catch (Exception e)
{
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}

Pass data from one activity to another [duplicate]

This question already has answers here:
How to pass a value from one Activity to another in Android? [duplicate]
(7 answers)
Closed 9 years ago.
In Activity1, I input some data like name and address. When I click the next button, there will be another input form. What I want to do is, when I click BACK, I will return to Activity1 and the data I entered there previously is shown.
HELP please :)
=============
UPDATED: Activity1
private void startActivityForResult()
{
TextView textname = (TextView) findViewById(R.id.username);
TextView textaddress = (TextView) findViewById(R.id.useraddress);
Intent intent = new Intent(this, GetInformation.class);
//intent.putExtras(getIntent());
intent.putExtra("username", textname.getText().toString());
intent.putExtra("useradd", textaddress.getText().toString());
startActivityForResult(intent, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
TextView textname = (TextView) findViewById(R.id.username);
TextView textaddress = (TextView) findViewById(R.id.useraddress);
textname.setText(data.getStringExtra("returnname").toString());
textaddress.setText(data.getStringExtra("returnadd").toString());
}
Activity2
private void startActivityForResult()
{
final String username;
final String useraddress;
Intent intent = getIntent();
//intent.putExtras(getIntent());
username = getIntent().getStringExtra("username");
useraddress = getIntent().getStringExtra("useradd");
intent.putExtra("returnname", username);
intent.putExtra("returnadd", useraddress);
setResult(0, intent);
}
There's a simple way to do this in Android : startActivityForResult. Basically, when you launch the activity, you say that you are expecting a result. The other activity can then add information that will be returned to the starting activity. Here's a very simple code sample from the official doc :
public class MyActivity extends Activity {
...
static final int PICK_CONTACT_REQUEST = 0;
protected boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
// When the user center presses, let them pick a contact.
startActivityForResult(
new Intent(Intent.ACTION_PICK,
new Uri("content://contacts")),
PICK_CONTACT_REQUEST);
return true;
}
return false;
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
// A contact was picked. Here we will just display it
// to the user.
startActivity(new Intent(Intent.ACTION_VIEW, data));
}
}
}
}
You can get a much more complete description of all this on the Activity page in the official doc (section Starting Activities and Getting Results).
Save Activity1 state in method onSaveInstanceState, and then in method
void onCreate(Bundle savedInstanceState)
you can restore state, using savedInstanceState.
Or, if you want pass entered data to second activity, you can place data in intent.
Sample:
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putExtra("Key", "Value");
startActivityForResult(i, 0);
in Second Activity you can get data:
getIntent().getStringExtra("Key");
To return result from second activity:
Intent data = new Intent();
data.put("key", "value");
setResult(RESULT_OK, data);
then you can retrieve data in first activity using
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
data.getStringExtra("key");
}

Multiple onActivityResult for 1 Activity

So I have a very simple app I am working on. It's purpose is to collect asset data from 1 pc, and 1 or 2 monitors.
My form contains 3 edittext views, and 3 buttons (one for each asset I am collecting data for). The buttons invoke startActivityForResult for the barcode scanner, then I want to pass the result to the associated edittext view based on which button was pressed (example: press "scan" button to the right of "Asset - PC" edittext, scan and return data to it's associated edittext. Then if you press the button "scan" thats next to the "Asset - Mon1" edittext, return data to "Asset - Mon1" edittext.... and so on...)
With the code I have here, all the items work, just not as intended. Pressing any of the "scan" buttons always returns the result to the first edittext view "Asset - PC".
public class TestShit extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void assetPcClick(View view) {
Intent intent1 = new Intent("com.google.zxing.client.android.SCAN");
intent1.setPackage("com.google.zxing.client.android");
intent1.putExtra("SCAN_MODE", "ONE_D_MODE");
startActivityForResult(intent1, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents1 = intent.getStringExtra("SCAN_RESULT");
String format1 = intent.getStringExtra("SCAN_RESULT_FORMAT");
EditText assetPC = (EditText) findViewById(R.id.assetPC);
assetPC.setText(contents1);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
public void assetMon1Click(View view) {
Intent intent2 = new Intent("com.google.zxing.client.android.SCAN");
intent2.setPackage("com.google.zxing.client.android");
intent2.putExtra("SCAN_MODE", "ONE_D_MODE");
startActivityForResult(intent2, 0);
}
public void onActivityResult2(int requestCode, int resultCode, Intent intent2) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents2 = intent2.getStringExtra("SCAN_RESULT");
String format2 = intent2.getStringExtra("SCAN_RESULT_FORMAT");
EditText assetMon1 = (EditText) findViewById(R.id.assetMon1);
assetMon1.setText(contents2);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
public void assetMon2Click(View view) {
Intent intent3 = new Intent("com.google.zxing.client.android.SCAN");
intent3.setPackage("com.google.zxing.client.android");
intent3.putExtra("SCAN_MODE", "ONE_D_MODE");
startActivityForResult(intent3, 0);
}
public void onActivityResult3(int requestCode, int resultCode, Intent intent3) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents3 = intent3.getStringExtra("SCAN_RESULT");
String format3 = intent3.getStringExtra("SCAN_RESULT_FORMAT");
EditText assetMon2 = (EditText) findViewById(R.id.assetMon2);
assetMon2.setText(contents3);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
}
Any suggestions on how I can better manage my multiple "ActivityForResult" and "onActivityResult" 's ?
My fix, thank you for all your help!
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents1 = intent.getStringExtra("SCAN_RESULT");
String format1 = intent.getStringExtra("SCAN_RESULT_FORMAT");
EditText assetPC = (EditText) findViewById(R.id.assetPC);
assetPC.setText(contents1);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
String contents1 = intent.getStringExtra("SCAN_RESULT");
String format1 = intent.getStringExtra("SCAN_RESULT_FORMAT");
EditText assetMon1 = (EditText) findViewById(R.id.assetMon1);
assetMon1.setText(contents1);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
if (requestCode == 2) {
if (resultCode == RESULT_OK) {
String contents1 = intent.getStringExtra("SCAN_RESULT");
String format1 = intent.getStringExtra("SCAN_RESULT_FORMAT");
EditText assetMon2 = (EditText) findViewById(R.id.assetMon2);
assetMon2.setText(contents1);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
In your startActivityForResult, don't use 0's on both calls... use different numbers like 0 & 1... then you can implement a switch in your onActivityResult method with the requestCode. If the requestCode = 0 then the first method has returned, if it is 1, then the second has returned. This should be the same for more calls.
public void onActivityResult(int requestCode, int resultCode, Intent intent){
switch(requestCode){
case 0: // Do your stuff here...
break;
case 1: // Do your other stuff here...
break;
case etc:
break;
}
}
The calls should be something like this then:
(For the first time)
startActivityForResult(intent1, 0);
(For the second time)
startActivityForResult(intent2, 1);
(for the third time)
startActivityForResult(intent3, 2);
(for the nth time)
startActivityForResult(intentn, n - 1);
Or, you could declare static int values to use, instead of the more unrecognisable int values.
While you startActivityForResult you send a requestcode with it,
this should be different(unique) for your every activity you are starting from your button, say button 1 starts activity request code 1, button 2 requestcode = 2, and button 3 request code =3, then for your parent activity you must have only one onActivityResult()
in this function take a switch case , scan requestcodes, requestcode = 1 will give result from first activity and request code =2 gives for activity 2 and so on...
There's nothing in Android that is ever going to recognize and call methods named onActivityResult2 or onActivityResult3. Those are just method names you made up that are going to be ignored by the system.
You need to change your code such that you pass a different request code when you call startActivityForResult(). (requestCode is the 2nd parameter to that method)
Then in onActivityResult check the requestCode to see which activity you are getting the result from, and handle accordingly.

Categories

Resources