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

Posted

技术标签:

【中文标题】使用自定义 CursorAdapter 时 ListView 未显示在活动中【英文标题】:ListView not showing up in activity when using custom CursorAdapter 【发布时间】:2017-05-13 19:20:24 【问题描述】:

我正在练习 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_
android:layout_
tools:context=".MainActivity">

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

    <ListView
        android:id="@+id/list_view"
        android:layout_
        android:layout_
        android:layout_below="@+id/toolbar"
        ></ListView>
        <ImageButton
        android:layout_margin="15dp"
        android:layout_
        android:layout_
        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】:

如果你看到你的代码,你正在创建一个游标,将它分配给一个适配器和列表视图,然后关闭游标。如果关闭 cursor,就会释放 cursor 中的所有资源和信息:

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

您必须使用光标信息创建一个列表/数组,使用此信息设置适配器,并且每次您来自 EditorActivity(Main Activity 的 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 类以适应此代码。如果需要帮助,请告诉我们。

【讨论】:

非常感谢。我明白了。我会尝试一下,如果有任何问题,我会回来的

以上是关于使用自定义 CursorAdapter 时 ListView 未显示在活动中的主要内容,如果未能解决你的问题,请参考以下文章

带有自定义 CursorAdapter 的 Android ListFragment 不显示数据

如何使用 CursorAdapter 将 Filter 设置为 ListView?

如何使用CursorAdapter将Filter设置为ListView?

在 cursoradapter 中从 ListView 中删除项目

Web 服务同步后 ListView 未更新

用于图像获取的AsyncTask不断被调用