Programmer Hari
Programmer Hari

Reputation: 179

Data is not displayed in a Listview

i am creating a small crud system. after add the record i have to view the record when i click the view button. i attached image below and codes. got errror on this

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

line is titles.add(c.getString(age));

click button code here

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

        }
    }

Upvotes: 2

Views: 766

Answers (2)

Fely
Fely

Reputation: 38

I think you should use do-while loop:

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

Upvotes: 1

Sahil
Sahil

Reputation: 972

Update loop condition as following :

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

Hope it helps.

Upvotes: 1

Related Questions