我正在尝试访问存储在sqlite数据库中的数据。我正在尝试使用Cursor访问数据。我已经编写了函数getInformation()来访问数据。我的问题是当我试图调用此函数时它会抛出java.lang .NullPointerException错误。我不知道为什么会这样做。有人可以帮我解决这个错误。
E / AndroidRuntime:FATAL EXCEPTION:main进程:com.edkul.vimal.edkul,PID:2006 java.lang.NullPointerException:尝试调用虚方法' android.database.Cursor com.edkul.vimal。 edkul.DatabaseHandler.getInformation(com.edkul.vimal.edkul.DatabaseHandler)'在空对象引用上
这是我从Db获取数据的功能:
<pre><code>
public Cursor getInformation(DatabaseHandler db){
SQLiteDatabase sq = db.getWritableDatabase();
String[] columnNames ={"StudentName","StudentEmail","StudentPassword",
"StudentConfirmPassword","InstituteName","ContactInfo"};
String tableName = "StudentRecords";
Cursor cr = sq.query(tableName,columnNames,null,null,null,null,null);
return cr;
}
</code></pre>
我试图调用此函数的部分代码:
<pre><code>
btn = (Button) findViewById(R.id.loginButton);
userName = (EditText) findViewById(R.id.userName);
passWord = (EditText) findViewById(R.id.passWord);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String username = userName.getText().toString();
String userpass = passWord.getText().toString();
boolean login_status = false;
Cursor cr1 = dbHandler.getInformation(dbHandler);
String name = "";
cr1.moveToFirst();
do {
if(username.equals(cr1.getString(0))
&&userpass.equals(cr1.getString(2))){
login_status = true;
name = cr1.getString(0);
}
}while(cr1.moveToNext());
if (login_status){
Intent intentMain = new Intent(welcomepage.this,
UserProfile.class);
startActivity(intentMain);
finish();
}
}while(cr1.moveToNext());
if (login_status){
Intent intentMain = new Intent(welcomepage.this,
UserProfile.class);
startActivity(intentMain);
finish();
}
</code></pre>
答案 0 :(得分:0)
您可以通过这种方式从SQLite数据库访问数据 -
try
{
AndroidOpenDbHelper queryDbHelperObj = new AndroidOpenDbHelper(this);
SQLiteDatabase sqLiteDatabase = queryDbHelperObj.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(SQL_SELECT_QUERY,null);
if(cursor != null)
{
if(cursor.moveToFirst())
{
do
{
String OriginDB = cursor.getString(cursor.getColumnIndex("Origin"));
String DestinationDB = cursor.getString(cursor.getColumnIndex("Destination"));
}while(cursor.moveToNext());
}
}
}
catch(Exception err)
{
err.printStackTrace();
}
希望这有帮助!