首页 > 解决方案 > 数据不显示在列表视图中

问题描述

我正在创建一个小的 crud 系统。添加记录后,我必须在单击查看按钮时查看记录。我附上了下面的图片和代码。对此有误

**android.database.CursorIndexOutOfBoundsException: Index 4 requested, with a size of 4**

行是titles.add(c.getString(age));

单击此处的按钮代码

  Intent i = new Intent(this,view.class);
            startActivity(i);

在此处输入图像描述

**Listview xml file**

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".view">

    <ListView
        android:id="@+id/lst1"
        android:layout_width="368dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp" />
</LinearLayout>

视图.java

 public class view extends AppCompatActivity {
        ListView lst1;
        ArrayList<String> titles = new ArrayList<String>();
        ArrayAdapter arrayAdapter;

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

            SQLiteDatabase db = openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
            lst1 = findViewById(R.id.lst1);

            Cursor c = db.rawQuery("select * from record",null);
            int name = c.getColumnIndex("name");
            int age = c.getColumnIndex("age");
            c.moveToFirst();
            titles.clear();
            arrayAdapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,titles);
            lst1.setAdapter(arrayAdapter);
              while (c != null)
              {
                  titles.add(c.getString(name));
                  titles.add(c.getString(age));

                  c.moveToNext();
              }
            arrayAdapter.notifyDataSetChanged();

        }
    }

标签: android

解决方案


我认为你应该使用 do-while 循环:

if(c.moveToFirst()) {
    do {
        titles.add(c.getString(name));
        titles.add(c.getString(age));
     } while (c.moveToNext())
}

推荐阅读