How to get id from sqlite Android Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to get id from sqlite Android without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a problems, with get an id of user. I can get name, email, created_at columns, but i cannot get id. Help please.

public SQLiteHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_EMAIL +  " TEXT,"
            + KEY_CREATED_AT + " TEXT" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);

    Log.d(TAG, "Database tables created");
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);

    // Create tables again
    onCreate(db);
}

/**
 * Storing user details in database
 * */
public void addUser(String name, String email,  String created_at) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, name); // Name
    values.put(KEY_EMAIL, email); // Email
    values.put(KEY_CREATED_AT, created_at); // Created At

    // Inserting Row
    long id = db.insert(TABLE_USER, null, values);
    db.close(); // Closing database connection

    Log.d(TAG, "New user inserted into sqlite: " + id);
}

/**
 * Getting user data from database
 * */
public HashMap<String, String> getUserDetails() {
    HashMap<String, String> user = new HashMap<String, String>();
    String selectQuery = "SELECT * FROM " + TABLE_USER;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        user.put("name", cursor.getString(1));
        user.put("email", cursor.getString(2));
        user.put("created_at", cursor.getString(3));
    }
    cursor.close();
    db.close();
    // return user
    Log.d(TAG, "Fetching user from Sqlite: " + user.toString());

    return user;
}

/**
 * Re crate database Delete all tables and create them again
 * */
public void deleteUsers() {
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_USER, null, null);
    db.close();

    Log.d(TAG, "Deleted all user info from sqlite");
}`

Result of fetch:

D/SQLiteHandler: Fetching user from Sqlite: {name=admin, created_at=2020-05-06 22:04:39, email=admin@gmail.com}

Answer

The column indices of the Cursor object are 0 based, so the index of the column KEY_ID is 0 and you do not add it to the HashMap.
Change to this:

if (cursor.getCount() > 0) {
    user.put(KEY_ID, cursor.getString(0));
    user.put(KEY_NAME, cursor.getString(1));
    user.put(KEY_EMAIL, cursor.getString(2));
    user.put(KEY_CREATED_AT, cursor.getString(3));
}

It’s better to use the KEY_??? constants throughout your code.
Also instead of the column indices 0,1,2... use the method getColumnIndex():

if (cursor.getCount() > 0) {
    user.put(KEY_ID, cursor.getString(getColumnIndex(KEY_ID)));
    user.put(KEY_NAME, cursor.getString(getColumnIndex(KEY_NAME)));
    user.put(KEY_EMAIL, cursor.getString(getColumnIndex(KEY_EMAIL)));
    user.put(KEY_CREATED_AT, cursor.getString(getColumnIndex(KEY_CREATED_AT)));
}
We are here to answer your question about How to get id from sqlite Android - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji