Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

android - back to previous activity with intent

I have two activity, and when I press enter on first activity, it will open second activity, it contains a ListView and when I choose an item from ListView, it will get its value and bring back to first activity

this is what I've tried;

on second activity

listPerasat.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
     public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            NamaPrst = ((TextView) view.findViewById(R.id.txtListNamaPrst)).getText().toString();
            Intent i = new Intent();
            i.putExtra("NAMA_PERASAT", NamaPrst);
            finish();
        }
    });
}

on first activity

edtText.setText(getIntent().getStringExtra("NAMA_PERASAT")); // inside onCreate

or

public void onActivityResult(int requestCode,int resultCode, Intent data)
{
    edtText.setText(getIntent().getStringExtra("NAMA_PERASAT"));
}

but nothing happen. how can I get intent and back to previous activity?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to call startActivityForResult() for this. So in your first Activity something like

Intent i = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(i, SOME_REQUEST_CODE); // you give SomeRequesSOME_REQUEST_CODE an int value

then in your onItemClick() you need to call setResult() and send back the Intent. This will call onActivityResult() in your first Activity

listPerasat.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
 public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        NamaPrst = ((TextView) view.findViewById(R.id.txtListNamaPrst)).getText().toString();
        Intent i = new Intent();
        i.putExtra("NAMA_PERASAT", NamaPrst);
        setResult(RESULT_OK, i);
        finish();
    }
});
}

In onActivityResult() in your first Activity, don't call getIntent(). This will try to use the Intent that originally started your first Activity. Instead, use the Intent you passed back

@Override
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
    edtText.setText(data.getStringExtra("NAMA_PERASAT"));
}

See this answer for another example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...