使用SQLite数据"Attempt to invoke virtual method '...' on a null object reference"的Android应用程序



我正在编写一个安卓应用程序,但在定位错误时遇到问题。我正在尝试从SQLite数据库获取数据。该应用程序正常运行,直到我调用该活动并崩溃。

这是我的代码:

error on line mTerm = mDBHelper.getTerm(((Term( i.getSerializableExtra("term"((.getTermId(((

错误: 尝试调用虚拟方法 'int com.example...Term.getTermId((' 在空对象引用上

活动

public class TermDetailsActivity extends AppCompatActivity {
private Term mTerm;
private DBOpenHelper mDBHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_term_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Term Details");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDBHelper = new DBOpenHelper(this);
Intent i = getIntent();
mTerm = mDBHelper.getTerm(((Term) i.getSerializableExtra("term")).getTermId());
setTextViews();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
menu.findItem(R.id.edit).setVisible(true);
return true;
}
private void setTextViews() {
TextView Title = findViewById(R.id.term_details_name_value);
TextView Start = findViewById(R.id.term_start_date_value);
TextView End = findViewById(R.id.term_end_date_value);
Title.setText(mTerm.getTermName());
Start.setText(mTerm.getTermStart());
End.setText(mTerm.getTermEnd());
}

}

我的DBHelper扩展了SQLiteOpenHelper,表创建得很好。我能够使用以下代码在另一个活动上拉取数据。

DBHelper

public Term getTerm(int termId) {
Term term;
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(
"SELECT * FROM " + TABLE_TERMS + " WHERE " + TERM_ID + " = " + 
termId, null);
res.moveToFirst();
term = new Term(
res.getInt(0),
res.getString(1),
res.getString(2),
res.getString(3));
res.close();
return term;
}

学期类

public class Term implements Serializable {
private int termId;
private String termName;
private String termStart;
private String termEnd;
public Term(int termId, String termName, String termStart, String termEnd){
this.termId = termId;
this.termName = termName;
this.termStart = termStart;
this.termEnd = termEnd;
}
public int getTermId(){
return termId;
}
public void setTermId(int termId){
this.termId = termId;
}

嗨,在 DBHelper 中使用它之前,请尝试将术语提取到变量中。我怀疑缺少额外的内容,当对getSerializableExtra的调用返回时,getTermId在null上调用,从而导致异常。

编辑:

这就是我提取到变量的意思:

Intent i = getIntent();
Term term = i.getSerializableExtra("term"); // <- this might be null
// Place a breakpoint on the next line to verify
mTerm = mDBHelper.getTerm(term.getTermId());

相关内容

  • 没有找到相关文章

最新更新