简体   繁体   中英

Reading Data from SQLite Database to a new Activity - Android Studio

I am creating an android app that has basically 6 inputs (2 from spinners and the rest textviews) and am using an SQLite Database. I have got as far as when the user clicks on a "start button" the data is saved successfully to the database and also displays on the same activity.

The problem that i am asking help for is.. i want to display the saved data, not on the same activity(screen) in which the data is being saved but on a different activity. So, for instance everything is working in terms of storing and displaying the data on screen 1, but how do i retrieve the data again on screen 2?

Here is the code that i have to save the data (DataBaseHelper):

 @Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME +"  (ID INTEGER PRIMARY KEY AUTOINCREMENT,LINETYPE TEXT,PACKAGETYPE TEXT,QUANTITY TEXT,DURATION TEXT,STARTTIME TEXT,ENDTIME TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

public boolean insertData(String linetype, String packagetype, String quantity, String duration, String starttime, String endtime) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2,linetype);
    contentValues.put(COL_3,packagetype);
    contentValues.put(COL_4,quantity);
    contentValues.put(COL_5,duration);
    contentValues.put(COL_6,starttime);
    contentValues.put(COL_7,endtime);
    long result = db.insert(TABLE_NAME,null,contentValues);
    if(result == -1)
        return false;
    else
        return true;
}

public Cursor getAllData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
    return res;
}

And some code from the activity:

//INSERT DATA TO DATABASE
            boolean isInserted = myDb.insertData(
                    spinnerSelection,
                    spinnerSelection2,
                    q,
                    d,
                    formattedtime,
                    endtimecalc);

            if(isInserted == true)
                Toast.makeText(screen2.this, "Data Inserted Successfully", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(screen2.this, "Data not Inserted", Toast.LENGTH_LONG).show();

        }
    });

    nextButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Cursor res = myDb.getAllData();
            if (res.getCount() == 0) {
                //show messages
                showMessage("Error", "Nothing Found");
                return;
            }

            StringBuffer buffer = new StringBuffer();
            while (res.moveToNext()) {
                buffer.append("ID: " + res.getString(0)+"\n");
                buffer.append("LineType: " + res.getString(1)+"\n");
                buffer.append("PackageType: " + res.getString(2)+"\n");
                buffer.append("Quantity: " + res.getString(3)+"\n");
                buffer.append("Duration: " + res.getString(4)+"\n");
                buffer.append("StartTime: " + res.getString(5)+"\n");
                buffer.append("EndTime: " + res.getString(6)+"\n\n");
            }

            //SHOW ALL DATA
            showMessage("Data", buffer.toString());


        }
    });
}

public void showMessage(String title,String Message){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(Message);
    builder.show();
}

So, i now need to display the same information which is being stored from this activity into a new one.

Anyone any thoughts?

ERROR STACK TRACE:

10-05 15:54:58.072 5958-5958/com.example.t_fdonnelly.pharmatest E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.t_fdonnelly.pharmatest, PID: 5958 android.database.CursorIndexOutOfBoundsException: Index 13 requested, with a size of 13 at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460) at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136) at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50) at com.example.t_fdonnelly.tracker.screen2$4.onClick(screen2.java:196) at android.view.View.performClick(View.java:5653) at android.view.View$PerformClick.run(View.java:22509) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6144) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(Zy goteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

UPDATED CODE:

 Cursor res = myDb.getAllData();
            if (res.getCount() == 0) {
                //show messages
                showMessage("Error", "Nothing Found");
                return;
            }

            StringBuffer buffer = new StringBuffer();

            String getid = res.getString(0);
            String getlt = res.getString(1);
            String getpt = res.getString(2);
            String getqty = res.getString(3);
            String getdur = res.getString(4);
            String getst = res.getString(5);
            String getet = res.getString(6);


            if ( res != null && res.moveToFirst()) {
                do {
                    buffer.append(getid);
                    buffer.append(getlt);
                    buffer.append(getpt);
                    buffer.append(getqty);
                    buffer.append(getdur);
                    buffer.append(getst);
                    buffer.append(getet);
                } while (res.moveToNext());
            }


            Intent TransferData = new Intent(getBaseContext(), screen4.class);
            TransferData.putExtra("ID", getid);
            TransferData.putExtra("LineType", getlt);
            TransferData.putExtra("PackageType", getpt);
            TransferData.putExtra("Quantity", getqty);
            TransferData.putExtra("Duration", getdur);
            TransferData.putExtra("Starttime",getst);
            TransferData.putExtra("endtime", getet);

            startActivity(TransferData);
        }
    });
}

When you starting new activity via Intent you can put your strings as extras

String id = res.getString(0);
String lineType = res.getString(1);
//rest of cursor logic
sb.append("ID: ").append(id).append("\n");
sb.append("LineType: ").append(lineType).append("\n");
//rest of StringBuffer logic
Intent newActivity = new Intent(this, NewActivity.class);
    newActivity.putExtra("ID", id);
    newActivity.putExtra("LineType", lineType);
    startActivity(newActivity);

In new activity call getIntent() method and retrieve them from it

String id = getIntent().getStringExtra("ID");

First of all

get a unique key for your data in database table like...

public long insertData(String linetype, String packagetype, String quantity, String duration, String starttime, String endtime) {
     ......
    long result = db.insert(TABLE_NAME,null,contentValues);
    return result;
}

in calling activity.

long yourUniqueId = myDb.insertData(
                    spinnerSelection,
                    spinnerSelection2,
                    q,
                    d,
                    formattedtime,
                    endtimecalc);

Second

Pass this yourUniqueId with intent as putLong...etc . and get it in Second activity. and fetch the record of corresponding id. and show it.

add new method in database class as. and then call it in second activity with the previous unique_id.

public Cursor getAllData(long uid) {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where ID = "+uid,null);
    return res;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM