setResult in intent para parent Activity passing - android

i am not understanding what is going on in this piece of code. Need help please.
Intent i = new Intent(getApplicationContext(),
RSSNewsReaderPBActivity.class);
// send result code 100 to notify about product update
setResult(100, i);
startActivity(i);
and why use int value in it what it do.
This is method of the code
protected String doInBackground(String... args) {
String url = args[0];
rssFeed = rssParser.getRSSFeed(url);
Log.d("rssFeed", " " + rssFeed);
if (rssFeed != null) {
Log.e("RSS URL",
rssFeed.getTitle() + "" + rssFeed.getLink() + ""
+ rssFeed.getDescription() + ""
+ rssFeed.getLanguage());
RSSDatabaseHandler rssDb = new RSSDatabaseHandler(
getApplicationContext());
WebSite site = new WebSite(rssFeed.getTitle(),
rssFeed.getLink(), rssFeed.getRSSLink(),
rssFeed.getDescription());
rssDb.addSite(site);
Intent i = new Intent(getApplicationContext(),
RSSNewsReaderPBActivity.class);
// send result code 100 to notify about product update
setResult(100, i);
startActivity(i);
return null;
} else {
runOnUiThread(new Runnable() {
public void run() {
textViewMessage
.setText("Rss url not found. Please check the url or try again");
}
});
}
return null;
}

In this case, the setResult is wrongly used : setResult must be called before finishing an activity, it will inform the parent activity that your current one has worked well or if it had a problem (considering the parent activity has started the new one with startActivityForResult)
Let's say you have an ActivityOne that will launch an ActivityTwo:
ActivityOne:
Intent intent = new Intent(this, ActivityTwo.class);
startActivityForResult(intent, MY_REQUEST_CODE);
in ActivityTwo at the moment you want to close the activity:
if(everything_is_ok)
setResult(1);
else
setResult(0);
finish();
In ActivityOne, you will get notified that ActivityTwo has been finished:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == MY_REQUEST_CODE)
{
if(resultCode == 1)
//everything went fine
else
//something went wrong
}
}
Hope this helps!

Related

Can't get string informations from another intent

I searched a lot and tried things but the onActivityResult function isn't launched when the intent from which I try to get a string information is closed.
I use Visual Studio to write this application, this is my code :
The click event that opens the activity where users can type strings :
private void Btn_Valid_Click(object sender, EventArgs e)
{
----
Intent intent = new Intent(this, typeof(activity_OF_TransfertChxChmb));
StartActivityForResult(intent, 0);
----
}
The function in the openned Intent that should return the string information :
private void Validate()
{
string stringToPassBack = tb_Store.Text;
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.PutExtra("result", stringToPassBack);
SetResult(Result.Ok, intent);
Finish();
}
And the onActivityResult function that should be launched in the first activity:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
base.onActivityResult(requestCode, 0, data);
if (requestCode == 0)
{
if (resultCode == -1) // Ok
{
string result = data.GetStringExtra("result");
}
if (resultCode == 0) // Canceled
{
//Write your code if there's no result
}
}
}
I am missing something, but can't figure out what.
Thank you for your help.
You are adding the extra via:
intent.PutExtra(Intent.ExtraText, stringToPassBack);
Your key is Intent.ExtraText.
You are retrieving the extra via:
string result = data.GetStringExtra("result");
Your key is "result".
So, perhaps Intent.ExtraText does not equal "result". You need to use the same key in both places.

Inconsistent Response of two different startActivityForResult From An AppCompatActivity

I have a class that extends AppCompatActivity. Within this activity I do two different calls to two startActivityForResult methods which are hooked to two button listeners. The first one calls a camera intent like so:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
and the second one calls another AppCompatActivity which holds a Google Map to wit:
Intent getLatLongIntent = new Intent(Form.this, MapsLatLongActivity.class);
startActivityForResult(getLatLongIntent, LATLONG_REQUEST);
The first startActivityForResult works fine and I can manipulate the response from the camera intent in the onActivityResult method. What is puzzling is that the same onActivityResult does not get triggered when I close the child activity of the second call using this code:
Intent intent = new Intent();
intent.putExtra("brdgHouseLat", latitude);
intent.putExtra("brdgHouseLong", longitude);
setResult(RESULT_OK, intent);
finish();
Below is my code for the onActivityResult method:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
himgres.setImageBitmap(photo);
} else if (requestCode == LATLONG_REQUEST && resultCode == Activity.RESULT_OK) {
latitude = data.getDoubleExtra("brdgHouseLat", 0);
longitude = data.getDoubleExtra("brdgHouseLong", 0);
Log.v(TAG, "and form has a lat = " + latitude);
Log.v(TAG, "and a long = " + longitude);
}
}
Needless to say I have goggled for solutions on this and have checked into my manifest (I haven't set any flags); fragments (no fragments here), etc.
Am starting to think that maybe SharedPreferences will be a better option but am just puzzled of the inconsistency of the responses. Any help will be appreciated
=========================================================================
Here are the three methods of the second activity relevant to this question:
#Override
public void onBackPressed() {
super.onBackPressed();
packLatLong();
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home: {
packLatLong();
}
}
return (super.onOptionsItemSelected(menuItem));
}
private void packLatLong() {
if (latitude != 0 && longitude != 0) {
Log.v(TAG, "packing this lat = " + latitude);
Log.v(TAG, "packing this long = " + longitude);
Intent intent = new Intent();
intent.putExtra("brdgHouseLat", latitude);
intent.putExtra("brdgHouseLong", longitude);
setResult(RESULT_OK, intent);
finish();
}
}
Please note that pressing either the back button as well as the home button in the action bar triggers the packLatLong method
I ended up solving this problem with some hints from #Pavneet_Singh:
Here is the solution:
In the method:
#Override
public void onBackPressed() {
super.onBackPressed();
packLatLong();
}
remove the call to super as it always returns a RESULT_CANCEL even if you set it to RESULT_OK.
This answer helped me on this -- https://stackoverflow.com/a/35241952/1637525.
I also changed
setResult(RESULT_OK, intent);
to
setResult(Activity.RESULT_OK, intent);

onActivityResult - resultCode is always 0

I have problem with onActivityResult, whatever I'm doing I can't get resultCode right.
I know that there are similar questions but at the end they didn't help me and I couldn't fix it
MainActivity: method which will open new Activity Popup.class
public void openShopView(){
Intent intent = new Intent(this, Popup.class);
Bundle b = new Bundle();
b.putString("which", "ShopMain");
intent.putExtras(b);
startActivityForResult(intent, 1);
}
Second Activity: method which will open yet another Activity Popup.class just with different layout
shop_c1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getIntent());
Bundle b = new Bundle();
b.putString("which", "ShopBuildings");
intent.putExtras(b);
startActivity(intent);
finish();
}
});
Third Activity: and there is method which should setResult and close Activity
building2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("LOG_NEW: ", "" + getCurrentBuildingTable(1) + ", " + checkSlotTable(1));
if(getCurrentBuildingTable(1) && checkSlotTable(1) == -1) {
Intent returnIntent = getIntent();
returnIntent.putExtra("result", 1);
setResult(RESULT_OK, returnIntent);
finish();
}else if (checkSlotTable(1) == -1){
Log.i("LOG_NEW: ", "Building already exist");
}
else{
Log.i("LOG_NEW: ", "Not enough resources");
}
}
});
At the end there is onActivityResult() from MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("LOG_RES: ", "Checking.. " + requestCode + ", " + resultCode);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result = data.getStringExtra("result");
Log.i("LOG_RES: ", result);
}
}
}
Whatever I'm doing I can't start if(resultCode == RESULT_OK) loop and resultCode is always 0..
Thanks for help
setResult must be called in Second Activity, since intent of second activity was passed in startActivityForResult.
However, you can delegate the result code of Third Activity to Second Activity, then to third.
Change your Second Activity to something like this:
shop_c1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getIntent());
Bundle b = new Bundle();
b.putString("which", "ShopBuildings");
intent.putExtras(b);
startActivityForResult(intent,1);
//Remove finish from here
}
});
then also add this in Second Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1){
setResult(resultCode,data);
}
finish();
}

Passing data from second activity to first activity

I am trying to pass Bundle from second activity to the first(launch) activity. In order not to get NPE on launch, I am checking if bundle != null, however, it looks, like even after returning from second activity with Bundle, it still doesn't run the "if" body.
Here is my part of code of first activity
Bundle bundle = getIntent().getExtras();
if (bundle!=null) {
Player player = new Player();
player.setStatus(bundle.getInt("Status"));
player.setName(bundle.getString("Name"));
addPlayerToList(player);
Log.e("Player with a name " + player.getName(), "Has been created");
}
And code of second activity
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEditText.getText().toString();
if (defaultRadioButton.isChecked()) {
status=0;
} else if (driverRadioButton.isChecked()) {
status=1;
} else {
Toast.makeText(getApplicationContext(), "Suka viberi galochku", Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(getApplicationContext(),StartActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("Status",status);
bundle.putString("Name", name);
Log.d("Object " + name, "Status: " + status);
startActivity(i);
}
});
Thanks for any help/advice
Use startActivityForResult() for this situation.
1) You open second activity from the first using this method, not startActivity()
2) Do whatever you want in the second activity
3) Set result bundle
4) Finish activity
5) Open bundle in the first activity
In your case it will look like:
1) Call second activity like this:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, REQUEST_SECOND_ACTIVITY); // request code const
2-4)
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEditText.getText().toString();
if (defaultRadioButton.isChecked()) {
status=0;
} else if (driverRadioButton.isChecked()) {
status=1;
} else {
Toast.makeText(getApplicationContext(), "Suka viberi galochku", Toast.LENGTH_SHORT).show();
}
final Intent returnIntent = new Intent();
returnIntent.putExtra("Status", status); // set values
returnIntent.putExtra("Name", name);
setResult(Activity.RESULT_OK, returnIntent); // set result code
finish(); // finish this activity and go back to the previous one
}
});
5) Override this method in the first activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case REQUEST_SECOND_ACTIVITY: // same request code const
if(resultCode == Activity.RESULT_OK){
Player player = new Player();
player.setStatus(data.getIntExtra("Status"));
player.setName(data.getStringExtra("Name"));
addPlayerToList(player);
}
break;
}
}
try Intent.putExtra() instead of putting data into a bundle, and use Intent.getStringExtra() to get a String data;
In your code, there is no code to put your bundle into intent. actually you never pass the bundle to first activity. you can use this answer to solve your problem.
good luck!

Android. on button click, jump to an onActivity result function. IT IS POSSIBLE?

i have button which have attribute android:onClick="atnDuom".
There is that function
public void atnDuom(View view)
{
finish();
}
and there is onActivityResult function in the same activity.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
DOP = new DatabaseOperations(ctx);
Intent returnIntent = new Intent();
user_name = data.getStringExtra("tarpVard");
user_lastname = data.getStringExtra("tarpPav");
institucijos_pavadinimas = data.getStringExtra("tarpInst");
padalinio_pavadinimas = data.getStringExtra("tarpPad");
pareigos = data.getStringExtra("tarpPar");
mob_tel = data.getStringExtra("tarpMob");
el_pastas = data.getStringExtra("tarpEl");
setResult(RESULT_OK,returnIntent);
DOP = new DatabaseOperations(ctx);
if(newVard.equals("")||newPav.equals("")||newInst.equals("")||newPad.equals("")||newPar.equals("")||newMob.equals("")||newEl.equals(""))
{
Toast.makeText(getBaseContext(), R.string.prashome, Toast.LENGTH_LONG).show();
}
else
{
DOP.updateUserInfo(DOP, user_name, user_lastname, institucijos_pavadinimas, padalinio_pavadinimas, pareigos, mob_tel, el_pastas, newVard, newPav, newInst, newPad, newPar, newMob, newEl);
Toast.makeText(getBaseContext(), "Duomenys atnaujinti", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
It is possible to execute function onActivityResult whithout doing anything in atnDuom function?
Finish() close activity and onActivityResult doesnt work :)
You are using data from the intent, if you want to go to onActivityResult from atnDuom you will need to create a new Intent and push all the data needed
Intent newIntent = new Intent();
newIntent.putExtras(...);
onActivityResult(REQUEST_CODE, RESULT_OK, newIntent);

Categories

Resources