数据未显示在列表视图中

时间:2019-03-03 15:17:53

标签: android

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

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

enter image description here

**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>

view.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();

        }
    }

2 个答案:

答案 0 :(得分:0)

更新循环条件如下:

for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) 
  {
   // The Cursor is now set to the right position
    titles.add(c.getString(name));
    titles.add(c.getString(age));));
  }

希望有帮助。

答案 1 :(得分:0)

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

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