当按下后退按钮时按下时,父动作会在按下子动作时按下动作栏主页箭头按钮时崩溃

时间:2017-06-28 15:48:38

标签: android nullpointerexception transparency

当按下后退按钮时,当按下操作栏主页箭头按钮时,父活动会从子活动中崩溃。

父活动从Launcher Activity接收额外的意图,并使用该对象设置其视图。然后它启动一个子活动结果,当子活动调用完成或从导航器按下后退按钮时它不会使父活动崩溃但是当我按下操作栏箭头(R.id.home)图标时,父活动崩溃了mSomeObjectWhichHasANameProperty的NullPointerException。我怎么能避免这种情况。

public class ParentActivity extends AppCompatActivity{
    Object mSomeObjectWhichHasANameProperty;
    TextView mNameView;
    Button mSomeButton;
    protected void onCreate(Bundle savedInstanceState {
        mSomeObjectWhichHasANameProperty=getIntent().getParcelableExtra("object_key");
        mNameView = (TextView) findViewById(R.id.name);
        mNameView.setText(mSomeObjectWhichHasANameProperty.getName());
        mSomeButton = (Button) findViewById(R.id.button);
        mSomeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChildActivity.start(this, SOME_REQUEST_CODE);
            }
        });
    }
}


public class ChildActivity extends AppCompatActivity{
    public static void start(Activity context, int requestCode) {
        Intent intent = new Intent(context, ChildActivity.class);
        context.startActivityForResult(intent, requestCode);
    }
    Button mSomeButton;
    protected void onCreate(Bundle savedInstanceState {
        mSomeButton = (Button) findViewById(R.id.button);
        mSomeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(1);
                finish();
            }
        });
    }
}

2 个答案:

答案 0 :(得分:0)

将其添加到ChildActivity中的清单:

android:parentActivityName=".ParentActivity"

答案 1 :(得分:0)

我不确定这行代码是否可以运行:ChildActivity.start(this, SOME_REQUEST_CODE);

应为this.startActivityForResult(Intent, RequestCode)