我有下一个活动:
活性1
//declare
private static final int SAVE_DATA_FROM_ACTIVITY = 203;
//........... not important code
//button to open second Activity
public void btn_openSecondActivity(View view)
{
Intent intent = new Intent(Activity2.this, Activity1.class);
startActivityForResult(intent, SAVE_DATA_FROM_ACTIVITY);
}
}
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if (requestCode == SAVE_DATA_FROM_activity)
{
name= data.getStringExtra("Name");
}
}
//....... not important code
活性2
On Second Activity我有两个按钮:
// ............
//declare
private static final int OK_RESULT_CODE = 1;
//Cancel button
public void btn_cancel(View view)
{
finish();
}
//Save button
public void btn_save (View view)
{
Intent intent = new Intent();
intent.putExtra("Name",et_name.getText().toString());
setResult(OK_RESULT_CODE, intent);
finish();
}
问题
当我单击“保存”按钮时,所有工作都很完美,但是当我单击“取消”按钮时出现问题,然后报告错误:
Failure delivering result ResultInfo{who=null, request=203, result=0, data=null} to activity {com.example.alvaro.project/com.alvaro.project.Activity1}: java.lang.NullPointerException
我理解这个问题,当我取消时不是相同的结果代码,但我不知道如何解决它
有什么建议吗?
答案 0 :(得分:1)
您在onActivityResult
方法中遇到问题。你没有检查结果。
更改您的条件:
if (requestCode == SAVE_DATA_FROM_activity)
为:
if (resultCode == OK_RESULT_CODE && requestCode == SAVE_DATA_FROM_activity)
答案 1 :(得分:1)
更改此
if (requestCode == SAVE_DATA_FROM_activity)
{
name= data.getStringExtra("Name");
}
到
if (requestCode == SAVE_DATA_FROM_activity&&resultCode==RESULT_OK)
{
name= data.getStringExtra("Name");
}
和
您的取消方法就像
public void btn_cancel(View view)
{
setResult(RESULT_CANCELED);
finish();
}
而不是 OK_RESULT_CODE 使用Android默认确定 Activity.RESULT_OK
答案 2 :(得分:0)
检查您是否设置了结果
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if (requestCode == SAVE_DATA_FROM_activity && resultCode = Activity2.OK_RESULT_CODE)
{
name= data.getStringExtra("Name");
} else {
//probably btn_cancel pressed
}
}
答案 3 :(得分:0)
检查onActivityResult
中的resultCode protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if (resultCode == 1/*OK_RESULT_CODE from Second Activity */ && requestCode == SAVE_DATA_FROM_activity)
{
name= data.getStringExtra("Name");
}
}
答案 4 :(得分:0)
<强>活性1 强>
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SAVE_DATA_FROM_activity) {
if (resultCode == Activity.RESULT_OK) {
name = data.getStringExtra("Name");
} else if (resultCode == Activity.RESULT_CANCELED){
// TODO something
}
}
}
<强>活性2 强>
删除字段OK_RESULT_CODE
//Cancel button
public void btn_cancel(View view) {
setResult(Activity.RESULT_CANCELED, new Intent());
finish();
}
//Save button
public void btn_save(View view) {
Intent intent = new Intent();
intent.putExtra("Name", et_name.getText().toString());
setResult(Activity.RESULT_OK, intent);
finish();
}