Search code examples
androidsqlandroid-studiocursors

"How to retrieve data from multiple tables using cursors in android studio"


I tried retrieving data from two tables using cursors, but I am getting data from only one table. please help.

Here is the complete code.

//Creation of tables

//Table T24

db.execSQL("CREATE TABLE IF NOT EXISTS T24 (ID NUMBER PRIMARY KEY,STARTING VARCHAR,DESTINATION VARCHAR" +
                        ",PLACES VARCHAR,PLACESFARE NUMBER(9,3),HOTELS VARCHAR,HOTELSFARE NUMBER(9,3),TRANSPORT VARCHAR," +
                        "TRANSPORTFARE VARCHAR,DAYS INTEGER,TOTALFARE NUMBER(9,3))");

//Table P21

 db.execSQL("CREATE TABLE IF NOT EXISTS P21"+"(NAME VARCHAR PRIMARY KEY,NO NUMBER," +
                    "ADDRESS VARCHAR,DAYS NUMBER,DATE NUMBER,MONTH NUMBER)");

//Retrieving data from database.

 db = openOrCreateDatabase("tour", Context.MODE_PRIVATE, null);
         String query1 = "select *from T24 where " +
               "STARTING='" + s3 + "' and DESTINATION='" + s4 + "'";
        Cursor c = db.rawQuery(query1, null);
        if (c.moveToFirst() == true) {
            t1 = c.getString(3);
            t2 = c.getString(4);
            t3 = c.getString(5);
            t4 = c.getString(6);
            t5 = c.getString(7);
            t6 = c.getString(8);
            t7 = c.getString(9);
            t8 = c.getString(10);
        }
        c.close();
        db.close();
        ptv.setText(t1);
        pf.setText(t2);
        hotels.setText(t3);
        hf.setText(t4);
        td.setText(t5);
        tf.setText(t6);
        fare.setText(t8);
        try {
            db2 = openOrCreateDatabase("tour", Context.MODE_PRIVATE, null);
            String query2 = "select *from P21 where" +
                    "NAME='" + e1 + "'";
            Cursor c1 = db2.rawQuery(query2, null);
            if (c1.moveToFirst() == true) {
                t9 = c1.getString(0);
                t10 = c1.getString(1);
                t11 = Integer.parseInt(c1.getString(3));
                t12 = Integer.parseInt(c1.getString(4));
                t13 = Integer.parseInt(c1.getString(5));
            }
            c1.close();
            db2.close();
            Toast.makeText(getApplicationContext(), "done3", Toast.LENGTH_LONG).show();
            name.setText(t9);
            no.setText(t10);
            sdate1.setText(t12);
            sdate2.setText(t13);

I am able to retrieve date from table "T24",but unable to retrieve data from table"P21".

Please help.


Solution

  • I think you left space after "where" in the sqlite sentence of P21:

    String query2 = "select *from P21 where" +
                    "NAME='" + e1 + "'";
    

    You need to write like this:

    String query2 = "select * from P21 where " +
                    "NAME='" + e1 + "'";