我的应用有问题。 我有一个名为PetActivity的活动。在这个活动中有一些值......和一个按钮(更新)。此按钮将用户切换到另一个名为UpdateActivity的活动,在该活动中,他可以编辑PetActivity中的值。有一个保存按钮,应该完成此活动并重新打开PetActivity。我在这个动作中遇到错误...(空指针异常)
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.project/com.example.project.PetActivity}: java.lang.NullPointerException
PetActivity onclick代码:
if (v.getId() == R.id.button1updateAP) {
Intent i = new Intent(PetActivity.this, UpdateActivity.class);
Bundle ext = getIntent().getExtras();
String idOfPet = ext.getString(IDR);
i.putExtra(UpdateActivity.ID, idOfPet);
startActivity(i);
finish();
}
UpdateActivity onclick code:
if (v.getId() == R.id.button1saveAU) {
MyDatabaseHelper db = new MyDatabaseHelper(this);
Pet petU = new Pet();
petU.setID(id);
petU.setName(TVname.getText().toString());
petU.setAge((ETage.getText().toString()));
petU.setWeight(ETweight.getText().toString());
db.updatePet(petU);
db.close();
DatabaseWeight dbw = new DatabaseWeight(this);
dbw.addPetWeight(new Pet(petU.getID(), petU.getWeight()));
Intent i2 = new Intent(this, PetActivity.class);
startActivity(i2);
finish();
}
当我尝试这个时,没关系:
Intent i2 = new Intent(this, ListActiv.class);
startActivity(i2);
finish();
此代码已将我切换到List并且我可以更新PetActivity,但我必须直接进入PetActivity。
我会非常感谢任何建议。
谢谢!
答案 0 :(得分:2)
从PetActivity启动UpdateActivity后不需要调用finish(),在完成工作后调用UpdateActivity只需在finish()之前调用setResult()...
您的代码应该用于onClick of MainActivity
if (v.getId() == R.id.button1updateAP) {
Intent i = new Intent(PetActivity.this, UpdateActivity.class);
Bundle ext = getIntent().getExtras();
String idOfPet = ext.getString(IDR);
i.putExtra(UpdateActivity.ID, idOfPet);
startActivityForResult(i,some request code ););
finish();
}
onClick of ChildActivity
if (v.getId() == R.id.button1saveAU) {
MyDatabaseHelper db = new MyDatabaseHelper(this);
Pet petU = new Pet();
petU.setID(id);
petU.setName(TVname.getText().toString());
petU.setAge((ETage.getText().toString()));
petU.setWeight(ETweight.getText().toString());
db.updatePet(petU);
db.close();
DatabaseWeight dbw = new DatabaseWeight(this);
dbw.addPetWeight(new Pet(petU.getID(), petU.getWeight()));
if(/*task completed successfully*/){
setResult(RESULT_OK);
}else{
setResult(RESULT_CANCELED);
}
finish();
}
现在在您的父活动中,您可以在onActivityResult()
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(LOG_TAG, "Inside onActiviy Result : "+resultCode);
if ( resultCode == RESULT_OK ) {
Toast.makeText(this, "Update executed successfully..", Toast.LENGTH_SHORT).show();
}else if ( resultCode == RESULT_CANCELED ) {
Toast.makeText(this, "There was an error", Toast.LENGTH_SHORT).show();
}
}
另请参阅doc ..
中的各种intent标记