我的Android开发遇到了一个令人毛骨悚然的问题-每当我调用 Notepadv3.java: Stack trace:startActivityForResult(this, Notepadv3.class);
时,我的应用都会直接跳过它,而不启动新活动,也不从中返回任何结果。好像代码不在那里!
当我将this
更改为mContext
(在课程开始时我已将mContext
定义为Context mContext;
)时,应用程序崩溃并显示NullPointerException
。
我在不同的类中使用了完全相同的代码布局,并且它运行完美。
我已验证自己在清单中正确声明了活动。
我花了几个小时在stackoverflow上寻找答案,并查找了无数如何进行此特定活动的示例,但都无济于事。我正在学习如何编写Android应用程序,因此已经使用了Google的记事本教程作为我的应用程序的基础。感谢您提前提供的帮助!
代码和堆栈跟踪如下:
NoteEdit.java :(出于可读性的考虑,我已经摘录了一些不相关的代码)
ojit_pre
public class NoteEdit extends Activity implements OnClickListener {
Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit);
setTitle(R.string.edit_item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_BARCODE) {
if (resultCode == RESULT_OK) {
barcode = (intent.getStringExtra("SCAN_RESULT"));
new updateBarcodeField().execute("");
} else if (resultCode == RESULT_CANCELED) {
}
}else if (requestCode == REQUEST_NEW) {
System.out.println("REQUEST_NEW onActivityResult().");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
@Override
protected void onPause() {
super.onPause();
saveState();
}
private void saveState(){
System.out.println("saveState()");
doorCall();
mDbHelper.open();
String title = mTitleText.getText().toString();
String barcode = mBarcodeText.getText().toString();
String price = mPriceText.getText().toString();
Intent requestNew = new Intent(mContext, Notepadv3.class);
if (returnCode == 1){
System.out.println("returnCode is 1. Calling validateFields()...");
String errors = validateFields(title);
if (errors.length() > 0) {
Toast.makeText(this, "Oops! Need a title!", duration).show();
System.out.println("Calling Notepadv3...");
startActivityForResult(requestNew, REQUEST_NEW);
}
}
if (returnCode == 2){
System.out.println("returnCode == 2 - Cancelling activity");
}else{
if (title.matches("")){
System.out.println("Variable is null. Returning...");
doorCall();
mDbHelper.close();
return;
}else{
System.out.println("Checking mRowId for null");
if (mRowId == null) {
Toast.makeText(this, "Success, product saved successfully", duration).show();
System.out.println("Switching activity to 'NotesDbAdapter'");
long id = mDbHelper.createNote(title, barcode, price);
mRowId = id;
}else{
System.out.println("mRowId is not null. Calling updateNote");
mDbHelper.updateNote(mRowId, title, barcode, price);
}
}
}
System.out.println("saveState() Finished");
if (doorCall()==true){
System.out.println("Database is Open");
}else{
System.out.println("Database is Closed");
}
}
}
最佳答案
首先,如果使用mContext,则应在onCreate方法中对其进行初始化:
mContext=getApplicationContext();
//I recommend using the application context for avoiding memory leaks
不要从onPause方法开始活动。