从SQLite数据库读取数据到新的Activity - Android Studio

时间:2017-10-05 13:09:22

标签: java android sqlite android-sqlite

我正在创建一个基本上有6个输入的Android应用程序(2个来自微调器和其他文本视图)并且正在使用SQLite数据库。当用户点击“开始按钮”时,我已经成功地将数据保存到数据库,并且还显示在同一活动上。

我要求帮助的问题是..我想显示保存的数据,而不是在保存数据但在不同活动的同一活动(屏幕)上。因此,例如,一切都在屏幕1上存储和显示数据方面有效,但我如何在屏幕2上再次检索数据呢?

以下是我必须保存数据的代码(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;
}

活动中的一些代码:

//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();
}

因此,我现在需要将从此活动存储的相同信息显示为新信息。

有人有什么想法吗?

ERROR STACK TRACE:

  

10-05 15:54:58.072 5958-5958 / com.example.t_fdonnelly.pharmatest E / AndroidRuntime:   致命异议:主要                                                                                     处理:com.example.t_fdonnelly.pharmatest,PID:5958                                                                                     android.database.CursorIndexOutOfBoundsException:请求索引13,大小为13                                                                                         在android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)                                                                                         在android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)                                                                                         在android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)                                                                                         在com.example.t_fdonnelly.tracker.screen2 $ 4.onClick(screen2.java:196)                                                                                         在android.view.View.performClick(View.java:5653)                                                                                         在android.view.View $ PerformClick.run(View.java:22509)                                                                                         在android.os.Handler.handleCallback(Handler.java:751)                                                                                         在android.os.Handler.dispatchMessage(Handler.java:95)                                                                                         在android.os.Looper.loop(Looper.java:154)                                                                                         在android.app.ActivityThread.main(ActivityThread.java:6144)                                                                                         at java.lang.reflect.Method.invoke(Native Method)                                                                                         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886)                                                                                         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

更新代码:

 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);
        }
    });
}

2 个答案:

答案 0 :(得分:1)

当您通过Intent开始新活动时,您可以将字符串作为附加内容

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);

在新活动中调用getIntent()方法并从中检索

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

答案 1 :(得分:0)

首先

获取数据库表中数据的唯一键,如...

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;
}

致电活动。

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

<强>第二

将此yourUniqueId的意图传递给putLong...etc。并在第二个活动中得到它。并获取相应id的记录。并展示它。

在数据库类中添加新方法。然后使用之前的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;
}