dimanche 13 décembre 2015

Retrieving data from sqlite and display into listview

I have a problem with this code:

SimpleCursorAdapter adapter;
       adapter = new SimpleCursorAdapter(context, R.layout.activity_view_medication, cursor, from, toViewMed)

When I run my project, the logcat error shows this:

java.lang.IllegalArgumentException: column '_id' does not exist

Code:

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

    context=this;

    // Get ListView object from xml
    lv = (ListView)findViewById(R.id.list);

    myDb = new DatabaseHelper(this);

    Create_Alarm();
    populateListView();
}

public void populateListView(){

    myDb.getAllData();
    Cursor cursor = myDb.getAllData();

    String[] from = new String[] {myDb.COL_2, myDb.COL_3 };
    int[] toViewMed = new int[] {R.id.txtName, R.id.txtQuantity};

    SimpleCursorAdapter adapter;
    adapter = new SimpleCursorAdapter(context, R.layout.activity_view_medication, cursor, from, toViewMed) {

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

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

            // Find fields to populate in inflated template
            TextView medicine = (TextView) view.findViewById(R.id.txtName);
            TextView quantity= (TextView) view.findViewById(R.id.txtQuantity);

            // Extract properties from cursor
            String  from = cursor.getString(cursor.getColumnIndexOrThrow("from"));
            int toViewMed = cursor.getInt(cursor.getColumnIndexOrThrow("toViewMed"));

            // Populate fields with extracted properties
            medicine.setText(from);
            quantity.setText(String.valueOf(toViewMed));

        }
    };

    // Assign adapter to ListView
    lv.setAdapter(adapter);
}

Aucun commentaire:

Enregistrer un commentaire