使用自定义CursorAdapter时,ListView未显示在活动中

时间:2016-12-29 12:53:23

标签: android listview sqlite cursor android-cursoradapter

我在练习SQLiteDatabases。我做了两项活动MainActivityEditorActivity。我使用列表视图和自定义适配器扩展游标适配器来显示MainActivity中的数据。插入数据库成功,但列表视图未显示在MainActivity中。请帮我解决一下这个。 代码

MainActivity类

public class MainActivity extends AppCompatActivity {

Toolbar toolbar;
ImageButton FAB;
ListView listView;
CustomAdapter adapter;

DatabaseHelper mDbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    listView = (ListView) findViewById(R.id.list_view);

    FAB = (ImageButton) findViewById(R.id.imageButton);
    FAB.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this , EditorActivity.class));
        }
    });
}

@Override
protected void onStart() {
    super.onStart();
    mDbHelper = new DatabaseHelper(getBaseContext());
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor c;

    c = db.query(
            DatabaseContract.TABLE_NAME,
            null,
            null,
            null,
            null,
            null,
            null
    );

    adapter = new CustomAdapter(MainActivity.this , c , false);

    listView.setAdapter(adapter);

    c.close();


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}}

编辑器活动类

    public class EditorActivity extends AppCompatActivity {

Toolbar toolbar;
EditText edtName, edtAge , edtMarks;
Button submit;
DatabaseHelper dbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_editor);

    toolbar = (Toolbar) findViewById(R.id.toolbar_editor);
    setSupportActionBar(toolbar);
    toolbar.setTitle("Editor");

    edtName = (EditText) findViewById(R.id.edt_name);
    edtAge = (EditText) findViewById(R.id.edt_age);
    edtMarks = (EditText) findViewById(R.id.edt_marks);

    submit = (Button) findViewById(R.id.btn_submit);

    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String name = edtName.getText().toString();
            int age = Integer.parseInt(edtAge.getText().toString());
            int marks = Integer.parseInt(edtMarks.getText().toString());

            dbHelper = new DatabaseHelper(getBaseContext());
            SQLiteDatabase db = dbHelper.getWritableDatabase();

            ContentValues values = new ContentValues();
            values.put(DatabaseContract.COLUMN_NAME , name);
            values.put(DatabaseContract.COLUMN_AGE , age);
            values.put(DatabaseContract.COLUMN_MARKS , marks);

            long rowId = db.insert(
                    DatabaseContract.TABLE_NAME,
                    null,
                    values
            );

            if (rowId == -1) {
                Toast.makeText(EditorActivity.this ,"Error inserting row"+rowId , Toast.LENGTH_SHORT).show();
            }else
            {
                Toast.makeText(EditorActivity.this ,"Succesfully inserted students data", Toast.LENGTH_SHORT).show();
                finish();

            }


        }
    });


}}

自定义适配器

public class CustomAdapter extends CursorAdapter {

public CustomAdapter(Context context, Cursor c, boolean autoRequery) {
    super(context, c, autoRequery);
}

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

@Override
public void bindView(View view, Context context, Cursor c) {

    TextView nameTv = (TextView) view.findViewById(R.id.list_name);
    TextView marksTv = (TextView) view.findViewById(R.id.list_marks);

    String nameString = c.getString(c.getColumnIndex(DatabaseContract.COLUMN_NAME));
    int marks = c.getInt(c.getColumnIndex(DatabaseContract.COLUMN_MARKS));

    nameTv.setText(nameString);
    marksTv.setText(String.valueOf(marks));

}}

activity_main xml代码

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<include
    android:id="@+id/toolbar"
    layout="@layout/tool_bar" />

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar"
        ></ListView>
        <ImageButton
        android:layout_margin="15dp"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:src="@drawable/ic_add_black_36dp"
        android:background="@drawable/circle"
        android:id="@+id/imageButton"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        />
        </RelativeLayout>

列表视图未显示。活动正在启动,但即使值正在更新到sqlite数据库,它看起来好像没有列表视图。 请帮我 谢谢。

1 个答案:

答案 0 :(得分:0)

如果看到代码,则表示正在创建Cursor,将其分配给适配器和列表视图,然后关闭光标。如果关闭光标,则将释放光标中的所有资源和信息:

https://developer.android.com/reference/android/database/Cursor.html#close()

您必须创建一个包含游标信息的列表/数组,使用此信息设置适配器,并且每次来自此活动的EditorActivity(主活动的onResume方法)更新信息,并通知适配器有关更改:

@Override
protected void onResume() {
    super.onResume();
    mDbHelper = new DatabaseHelper(getBaseContext());
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor c;

    c = db.query(
            DatabaseContract.TABLE_NAME,
            null,
            null,
            null,
            null,
            null,
            null
    );
    // This is pseudo-code, maybe methods are not correct.
    List<DataFromDB> list = new ArrayList<DataFromDB>();
    while(cursor.hasNext()){
      DataFromDB obj ;
      // create your obj with data from cursor
      list.add(obj);
    }
    // end pseudo-code
    c.close();

    adapter = new CustomAdapter(MainActivity.this , list , false);

    listView.setAdapter(adapter);

}

您必须更改Adapter类以适应此代码。如果需要帮助,请告诉我们。