Fetching data from database into LisFragment. I need to use this ListFragment file content into MainActivity.java.
SecondActivity which extends ListFragment:
String DB = "TestDB";
String TABLE_NAME = "addcamera";
SQLiteDatabase sampleDB = null;
ArrayList<String> results = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sampleDB = SQLiteDatabase.openOrCreateDatabase(DB, null);
Cursor c = sampleDB.rawQuery("SELECT CameraName FROM " + TABLE_NAME , null);
if (c != null) {
if (c.moveToFirst()) {
do {
String CameraName = c.getString(c.getColumnIndex("CameraName"));
results.add(CameraName);
}while (c.moveToNext());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, results);
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.exercise.FragmentTest.SecondActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/image_list_fragment">
</fragment>
</LinearLayout>
Can anyone helpme?
Well, first thing’s first – your
Activityshould not be extendingListFragment, your ownFragmentclass should be doing so. Hopefully I haven’t misunderstood anything. 🙂However, you could easily see your
ListFragmentderivative as aListActivity, ie you can use thegetListView()method to get theListViewcorresponding element (@android:id/list) from your XML.Seeing that you already have a
Cursorready, you should consider using aSimpleCursorAdapterand let it manage the cursor for you and *all* you need to do is to specify what fields to populate elements with.Example:
Update:
Here’s what your custom ListFragment could look like: