jeudi 8 octobre 2015

ListView not working with SimpleCursorAdapter and ListAdapter

I know there are many questions similar to this and swear I have tried them all. I am storing a string and database and want to retrieve it as list. This has been accomplished using ListAdapter (I followed a ToDo List Tutorial).

The issue is, I want to implement OnItemClickListener for this list that has been retrieved from DB. But the moment I replace ListAdapter with ListView, the app starts crashing with NullPointException.

Here is the code:

public class OfflineActivity extends ListActivity {
private ListAdapter listAdapter;
private TaskDBHelper helper;
ListView listView;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.offline_list);
    updateUI();

}

private void updateUI() {
    helper = new TaskDBHelper(OfflineActivity.this);
    SQLiteDatabase sqlDB = helper.getReadableDatabase();
    Cursor cursor = sqlDB.query(TaskContract.TABLE,
            new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK},
            null, null, null, null, null);

    listAdapter = new SimpleCursorAdapter(
            this,
            R.layout.offline_item,
            cursor,
            new String[]{TaskContract.Columns.TASK},
            new int[]{R.id.taskTextView},
            0
    );


this.setListAdapter(listAdapter);
listView.setAdapter(listAdapter);
}
}

The app works fine until I put listView.setAdapter(listAdapter); . Is there some way I can implement OnItemClickListenerwithout making much changes in my code.?

Here are the XML files:

offline_list.xml

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@android:id/list"
    android:layout_weight="1" />

offline_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://ift.tt/nIICcg">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/taskTextView" />

PS. I am sure that listAdapter is not empty.. coz the list does get populated if I dont add the last line. stuck on it since 2 days. plssss help

Aucun commentaire:

Enregistrer un commentaire