-2

so I am new to SQLite and the programming world. I want my app to find the username from DB, if it is found, then show a it's name, else show not found. but somehow my searchUname method is force-closing my app.

Here's where the method is called from

 else if (v.getId() == R.id.bsubmit){
        EditText xa = (EditText)findViewById(R.id.et1);
        String stru = xa.getText().toString();

        String user = helper.searchUname(stru);

        if (user.equals(stru)){
            TextView tv = (TextView)findViewById(R.id.tv4);
            tv.setText(user);
        }
        else{
            TextView tv = (TextView)findViewById(R.id.tv4);
            tv.setText("not found");
        }
        }

Here's my Database

public class DatabaseHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_UNAME = "uname";
private static final String COLUMN_PASS = "pass";
private static final String COLUMN_POINT = "pnt";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts (id integer primary key not null , " +
        "uname text not null , pass text not null ,  pnt integer not null );";

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

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(TABLE_CREATE);
    this.db = db;
}

and Here's my searchUname method.

    public String searchUname (String stru){

    db = this.getReadableDatabase();
    String query = "select uname from "+TABLE_NAME;
    Cursor c = db.rawQuery(query , null);
    String a = "not found";
    String b;

    c.moveToFirst();

        do{
            b = c.getString(1);
            if (b.equals(stru)){
                a = b;

                break;
            }

        }
    while (c.moveToNext());

    return a;
}

1 Answers1

0

You're trying to get a non returned column (1)

b = c.getString(1);

You only return 1 column, so you can retrieve it like this:

b = c.getString(0);

Since columns indexes are 0 based
Even better, retrieve your columns by name rather than by index:

b = c.getString(c.getColumnIndex("uName"));

[EDIT]

You can improve the method logic like this:

public String searchUname (String stru)
{
    db = this.getReadableDatabase();
    String query = "select uname from " + TABLE_NAME + " WHERE uname = '" + stru + "'";
    Cursor c = db.rawQuery(query , null);

    String a = "not found";
    if c.moveToFirst();
    {
        a = c.getString(c.getColumnIndex("uName"));
    }

    return a;
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115