How do I retrieve data from the database table by user name?

advertisements

I'm not too sure whether it's appropriate that using 'username' as my selection to retrieve other data instead of using an id. FYI, my username is unique as there will not be any other user having the same username. I'm doing this way because I'm not sure how to use or call the id from the table. I'm getting this error:

    CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

I have a DatabaseAdapter.java with this code:

   public Cursor getData(String username){
      SQLiteDatabase db = dbHelper.getReadableDatabase();
      Cursor cur =  db.query(TABLE_PROFILE, COLUMNS_PROFILE, " username=?", new String[]{username}, null, null, null, null );
      if (cur != null){
          cur.moveToFirst();
      }
      return cur;
   }

With a EditProfileFragment.java:

    dbAdapter = new DatabaseAdapter(getActivity());
    dbAdapter = dbAdapter.open();

    un = getArguments().getString("username");  

    Cursor cur = dbAdapter.getData(un);
    String password = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_PASSWORD));
    String age = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_AGE));
    String weight = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_WEIGHT));
    String height = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_HEIGHT));
    String gender= cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_GENDER));

I'm getting the String un in my log, means my username is successfully passed. I'm blur with the data retrieving data from the cursor, please help and thank you in advance for the help.


Try this Answer

public Cursor getData(String username){
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    String sql="select * from " + tableName + " where username =?";
    Cursor cursor=database.rawQuery(sql,new String{username});
    if (cursor != null)
{   cursor.moveToFirst();}
    return cursor;
}

Hope this will help you