为什么HashMap方法返回null对象引用?

时间:2015-02-28 10:43:42

标签: java android sqlite hashmap

我尝试使用HashMap方法获取SQLite数据库数据,但是当我调用该方法时,它返回null引用,这使我的Android应用程序停止工作。

这是我的代码:

HashMap方法:

public HashMap<String, String> getUserDetails(){
    HashMap<String,String> user = new HashMap<String,String>();
    String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    cursor.moveToFirst();
    if(cursor.getCount() > 0){
        user.put("name", cursor.getString(1));
        user.put("position", cursor.getString(2));
        user.put("level", cursor.getString(3));
        user.put("email", cursor.getString(4));
        user.put("uid", cursor.getString(5));
        user.put("created_at", cursor.getString(6));
    }
    cursor.close();
    db.close();

    return user;
}

这就是我如何在其他类中调用该方法

DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> userDetail= db.getUserDetails();
int userLevel = Integer.parseInt(userDetail.get("level").toString());

无论如何我使用教程参考来制作它并合并我自己的需要。

1 个答案:

答案 0 :(得分:1)

如果用户存在于数据库中,则应返回user对象,否则返回null并检查user是否为null

public HashMap<String, String> getUserDetails(){
    HashMap<String,String> user = null;
    String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;

    try {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor != null){
    cursor.moveToFirst();
    if(cursor.getCount() > 0){
        user = new HashMap<String,String>();
        user.put("name", cursor.getString(1));
        user.put("position", cursor.getString(2));
        user.put("level", cursor.getString(3));
        user.put("email", cursor.getString(4));
        user.put("uid", cursor.getString(5));
        user.put("created_at", cursor.getString(6));
    }
}
} finally {
    cursor.close();
    db.close();
}

    return user;
}

然后

DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> userDetail= db.getUserDetails();
if (userDetail != null) {
  String level = userDetail.get("level");
  if (level != null){
    try {
      int userLevel = Integer.parseInt(level);
    } catch (Exception e){
     e.printStackTrace();
    }
  }
}