使用 sqlite db 填充列表视图

Populating listview with sqlite db

我正在尝试使用 sqlite 数据库填充列表视图,到目前为止我认为我已经正确地将 created/added 项添加到数据库中。我不确定如何获取这些项目并将它们放入我的列表视图中。

这是我创建的数据库(RecordsDatabase.java):

public class RecordsDatabase extends SQLiteOpenHelper {

public static final int DATABASE_VERSION = 1;

public RecordsDatabase(Context context) {
    super(context, RecordContract.RecordInfo.DATABASE_NAME, null, DATABASE_VERSION);
    Log.d("Database operations", "Database created");
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + RecordContract.RecordInfo.TABLE_NAME + " ("
                    + RecordContract.RecordInfo.RECORDS_DATE + " TEXT NOT NULL,"
            + RecordContract.RecordInfo.RECORDS_SQUAT + " TEXT NOT NULL,"
            + RecordContract.RecordInfo.RECORDS_BENCH + " TEXT NOT NULL,"
            + RecordContract.RecordInfo.RECORDS_DEAD + " TEXT NOT NULL,"
            + RecordContract.RecordInfo.RECORDS_TOTAL + " TEXT NOT NULL)"

    );
    Log.d("Database operations", "Table created");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public void putInformation(RecordsDatabase rdb, String date, String squat, String bench, String dead, String total) {
    SQLiteDatabase SQ = rdb.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(RecordContract.RecordInfo.RECORDS_DATE, date);
    contentValues.put(RecordContract.RecordInfo.RECORDS_SQUAT, squat);
    contentValues.put(RecordContract.RecordInfo.RECORDS_BENCH, bench);
    contentValues.put(RecordContract.RecordInfo.RECORDS_DEAD, dead);
    contentValues.put(RecordContract.RecordInfo.RECORDS_TOTAL, total);
    long k = SQ.insert(RecordContract.RecordInfo.TABLE_NAME, null, contentValues);
    Log.d("Database operations", "Record added(1 row)");

}

public Cursor getRecords(RecordsDatabase rdb) {
    SQLiteDatabase SQ = rdb.getReadableDatabase();
    String[] columns = {RecordContract.RecordInfo.RECORDS_DATE, RecordContract.RecordInfo.RECORDS_SQUAT, RecordContract.RecordInfo.RECORDS_BENCH
    , RecordContract.RecordInfo.RECORDS_DEAD, RecordContract.RecordInfo.RECORDS_TOTAL};
    Cursor CR = SQ.query(RecordContract.RecordInfo.TABLE_NAME, columns,null, null, null, null, null);
    return CR;

}

这是我在点击按钮时添加按钮的地方(MyMaxes.java):

 mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
            SharedPreferences.Editor editor = pref.edit();
                if (mEditTextBench.getText().length() > 0 && mEditTextDead.getText().length() > 0 && mEditTextSquat.getText().length() > 0) {
                maxBenchDB = mEditTextBench.getText().toString();
                maxSquatDB = mEditTextSquat.getText().toString();
                maxDeadDB = mEditTextDead.getText().toString();
                maxTotalDB = mTxtTotal.getText().toString();

                DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
                Date today = Calendar.getInstance().getTime();
                reportDate = df.format(today);

                RecordsDatabase DB = new RecordsDatabase(mContext);
                DB.putInformation(DB, reportDate, maxSquatDB, maxDeadDB, maxBenchDB, maxTotalDB);
                Toast.makeText(getBaseContext(), "added", Toast.LENGTH_LONG).show();

这里是我的列表视图,我想使用 sqlite 数据库和我的 custom.xml(MyProgress.java):

public class MyProgress extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_progress);
    mToolBar = activateToolbar();
    setUpNavigationDrawer();
    getSupportActionBar().setTitle("My Progress");

    ListView listViewRec = (ListView) findViewById(R.id.listViewRecord);

这是我的 custom_record.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Date"
    android:textSize="18sp"
    android:id="@+id/txtDate"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Bench"
    android:id="@+id/txtBench"
    android:paddingRight="5dp"
    android:textSize="18sp"
    android:layout_gravity="center_horizontal"
    android:layout_alignParentTop="true"
    android:paddingLeft="5dp"
    android:layout_toLeftOf="@+id/txtSquat"
    android:layout_toStartOf="@+id/txtSquat"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Squat"
    android:textSize="18sp"
    android:paddingRight="5dp"
    android:id="@+id/txtSquat"
    android:layout_alignParentTop="true"
    android:paddingLeft="5dp"
    android:layout_toLeftOf="@+id/txtDead"
    android:layout_toStartOf="@+id/txtDead"
    />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Dead"
    android:paddingRight="5dp"
    android:textSize="18sp"
    android:id="@+id/txtDead"
    android:layout_alignParentTop="true"
    android:paddingLeft="5dp"
    android:layout_toLeftOf="@+id/txtTotal"
    android:layout_toStartOf="@+id/txtTotal"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Total"
    android:textSize="18sp"
    android:paddingRight="5dp"
    android:paddingLeft="5dp"
    android:id="@+id/txtTotal"
    android:layout_marginRight="34dp"
    android:layout_marginEnd="34dp"

    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"/>

到目前为止,这是我的 CursorAdapter:

public class TodoCursorAdapter extends CursorAdapter {

  public TodoCursorAdapter(Context context, Cursor c, int flags) {
          super(context, c, flags);
  }

  @Override
  public View newView(Context context, Cursor cursor, ViewGroup parent) {
          return LayoutInflater.from(context).inflate(R.layout.custom_record, parent, false);
  }

  @Override
  public void bindView(View view, Context context, Cursor cursor) {
          TextView txtDate = (TextView) view.findViewById(R.id.txtDate);
          TextView txtSquat = (TextView) view.findViewById(R.id.txtSquat);
          TextView txtBench = (TextView) view.findViewById(R.id.txtBench);
          TextView txtDead = (TextView) view.findViewById(R.id.txtDead);
          TextView txtTotal = (TextView) view.findViewById(R.id.txtTotal);

          String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
          String squat = cursor.getString(cursor.getColumnIndexOrThrow("squat"));
          String bench = cursor.getString(cursor.getColumnIndexOrThrow("bench"));
          String dead = cursor.getString(cursor.getColumnIndexOrThrow("dead"));
          String total = cursor.getString(cursor.getColumnIndexOrThrow("total"));

          txtBench.setText(bench);
          txtDate.setText(date);
          txtDead.setText(dead);
          txtSquat.setText(squat);
          txtTotal.setText(total);
  }
}

我不确定如何使用 sqlite 数据库来填充列表视图。我认为我正在以正确的方式向数据库中添加项目。感谢您的帮助!

您需要制作一个adapter的对象,并将其设置为ListView的adapter。

在你的activity这一行之后。

ListView listViewRec = (ListView) findViewById(R.id.listViewRecord);

输入这段代码。

首先从RecordsDatabase中获取所有记录class

Cursor recordsCursor = recordsDatabase.getRecords();

然后创建一个TodoCursorAdapter对象。

TodoCursorAdapter adapter = new TodoCursorAdapter(getContext(), recordsCursor, 
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

根据developer.android.com 关于 FLAG_REGISTER_CONTENT_OBSERVER

如果设置,适配器将在游标上注册一个内容观察器,并在收到通知时调用 onContentChanged()。使用此标志时要小心:您需要从适配器中取消设置当前游标以避免泄漏由于其注册观察员。将 CursorAdapter 与 CursorLoader 一起使用时不需要此标志。

然后将此适配器设置为ListView的适配器。

listViewRec.setAdapter(adapter);

首先,我建议更改 TodoCursorAdapter 构造函数:

public TodoCursorAdapter(Context context, Cursor c) {
    super(context, c, 0);
}

我自己对 flags 参数感到困惑。特别是因为不带标志的 Cursor 构造函数已经被弃用了一段时间。据我所知,这里的 0 值可以正常工作。

接下来,您需要从 putInformation()getRecords() 中删除 RecordsDatabase rdb 参数。这个参数是完全不需要的,因为 Java 已经作为关键字 this 自动发送了。但是,您实际上不需要在任何地方使用 this。您只需调用您希望直接使用的任何方法。所以而不是

rdb.getWritableDatabase();

就这样

getWritableDatabase();

或者,您可以这样做

this.getWritableDatabase();

但是如果您不使用它,系统会自动假设为 this

现在您需要 Cursor 才能传递给 TodoCursorAdapter 构造函数。您可以使用 RecordsDatabase 扩展 SQLiteOpenHelper:

public class MyProgress {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        // ...snip
        RecordsDatabase helper = new RecordsDatabase(this);
        Cursor c = db.getRecords();
        ListView listViewRec = (ListView) findViewById(R.id.listViewRecord);
        Adapter adapter = new TodoRecordsAdapter(this, c);
        listViewRec.setAdapter(adapter);
    }
}

此外,您可以考虑从 TodoCursorAdapter 构造函数中删除 Cursor 参数。其他选项是

  1. 直接在TodoCursorAdapter构造函数中创建Cursor
  2. MyProgress 中创建 Cursor 并在适配器上调用 changeCursor()