Reputation:
I am trying to to display data from a database table onto a listView by retrieving the data by way of a cursor, passing the cursor to a SimpleCursorAdapter and setting the adapter to a listView, as shown below. The app crashes due to a problem on listAdapter.setAdapter(adapter).
-I confirmed there is data in the chats table im using
-upon catching the exception, ex.getMessage was null but it indicated the line number as the one with listAdapter.setAdapter(adapter) CODE:
ChatsActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Conn connection = new Conn();
SQLiteDatabase db = connection.getDB(this, "chats", 1);
//returns readable database
Cursor result = db.rawQuery("SELECT * FROM chats", null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.other,
result,
new String[]{"_id", "lastContent"},
new int[]{R.id.textView1, R.id.textView2});
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
setContentView(listView);
}
}
2 Other.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Main"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:text="Sub"
android:textAppearance="?android:attr/textAppearanceMedium" /> </RelativeLayout>
Activity_chats.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".ChatsActivity">
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" /> </RelativeLayout>
What could be the problem?
Upvotes: 0
Views: 524
Reputation: 132992
Here:
setContentView(listView);
Instead of passing listView
to setContentView
, pass Activity_chats.xml
layout id as Activity layout before accessing values from layout:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Activity_chats);
....
}
Upvotes: 2