shivani
shivani

Reputation: 756

database query returns null even if there is value in it

In my android app am trying to get values from database by passing one parameter to the where clause but it is always returning null...and theres no error in logcat... i cant seem to figure out what is the issue here??

Please help!

the code where i am callimg the database function:

appmname=mDbHelper.getMname(appName);
             applname=mDbHelper.getLname(appmname);
             customername=appName+appmname+applname;
                // app_formno=mDbHelper.getAppno(settings.getString("ap_First_Name", ""));

             s=mDbHelper.fetchDetails(appName);
            s=mDbHelper.getMainData(customername);

these are the functions returning database values:

public String getMname(String fname)
{
    String mname = null;
    try
    {
        String sql="select app_mname from lnt_data_table where app_fname = '"+fname+"'";
        Cursor c=mDb.rawQuery(sql, null);
        if (c != null) {
            c.moveToFirst();

            while (!c.isAfterLast()) {

                    mname=c.getString(0);
            }
            c.close();
        }

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return mname;
}

public String getLname(String mname)
{
    String lname = null;
    try
    {
        String sql="select app_lname from lnt_data_table where app_mname= '"+mname+"'";
        Cursor c=mDb.rawQuery(sql, null);
        if (c != null) {
            c.moveToLast();

            while (c.isBeforeFirst() != true) {

                    lname=c.getString(0);
            }
            c.close();
        }

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return lname;
}

if i give this toast message

Toast.makeText(ListViewDetails.this,appName+ appmname +applname, Toast.LENGTH_LONG).show();

it returns null when the database has values in it!

Upvotes: 0

Views: 1278

Answers (2)

Benil Mathew
Benil Mathew

Reputation: 1634

Try this format for calling the cursor and closing it

    if (cursor != null) {

      if (cursor.moveToFirst()) {

          do {
                       //your code

              }

           while (cursor.moveToNext());

         }

  cursor.close();

Hope it helps :)

Upvotes: 2

SeanSWatkins
SeanSWatkins

Reputation: 413

I think you are moving to the end of the cursor before actually getting anything from it. Try changing c.moveToLast(); to c.moveToFirst() and then in the while loop just change while (c.isBeforeFirst()) to while(!c.isAfterLast())

You are currently moving to the end of the cursor and then checking if its at a position before the first entry...which is kinda impossible. Probably why you aren't getting anything back

Upvotes: 1

Related Questions