Reputation: 417
I've tried to make a HashMap
method to get SQLite database data, but when I call the method it returns null
reference that made my Android app stop working.
This my code:
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;
}
and this how I call the method in other class
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> userDetail= db.getUserDetails();
int userLevel = Integer.parseInt(userDetail.get("level").toString());
anyway I use a tutorial reference to make this and merge with my own needs.
Upvotes: 1
Views: 1731
Reputation: 1
You should return user
object if the user exists in the database, otherwise return null
and check if the user
is 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;
}
Then
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();
}
}
}
Upvotes: 1