Christian Eric Paran
Christian Eric Paran

Reputation: 1010

Android Getting Results from another activity

I have a problem with my code. I want to pass a String from the SecondActivity to FirstActvity. Note that the FirstActivity is not visible but its still open. when the SecondActivity is finish it passes a String to the FirstActivity.

My problem here is that when the SecondActivity ended and goes to FirstActivity, the whole application closes.

FirstActivity to SecondActivity:

Intent  intent = new Intent(MainActivity.this, FileChooser.class);
startActivityForResult(intent, 0);

SecondActivity to FirstActivity:

Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("filePath", "/sdcard/path1");
setResult(0);
finish();

FirstActivity Result:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //TODO handle here.         
    Intent intent = getIntent();        
    this.filePath = intent.getExtras().getString("filePath");
}

What is wrong with the code?

Upvotes: 1

Views: 1857

Answers (4)

Barış Çırıka
Barış Çırıka

Reputation: 1570

try this example.It solves your problem.

Upvotes: 0

stan0
stan0

Reputation: 11807

When you set the result of your SecondActivity, you only set the result code. Instead of setResult(0) use setResult(0,intent)

Also, in your FirstActivity's onActivityResult get the extra from the data argument - this.filePath = data.getExtras().getString("filePath");

Upvotes: 2

Luca
Luca

Reputation: 43

Try to use

data.getExtras().getString("filePath");

instead of

intent.getExtras().getString("filePath");`

Upvotes: 2

Carlos Landeras
Carlos Landeras

Reputation: 11063

Try with Bundle:

First Activity;

public void onClick(View v) {
        Intent intent = new Intent(v.getContext(), FIRSTACTIVITY.class);
        Bundle bundle = new Bundle();
        bundle.putString("filePath","/sdcard/path1");
        intent.putExtras(bundle);               
        startActivity(intent);
    }

Second Activity:

public void activity_value() {
    Intent i = getIntent();
    Bundle extras=i.getExtras();
    if(extras !=null) {           
        value = extras.getString("filePath");
    }
}

Upvotes: 0

Related Questions