Im having issues populating a listview using fragments, I have a fragment class called PagesFragment that extends Fragment.. I also have a MainActivity that switches between my Fragments using a Menu.
I believe I need to extend ListFragment in order to populate my listview in my Fragment 'PagesFragment' , however when I change all my classes to extend ListFragment, and change my cases to ListFragement in my MainActivity, I get an error when I try to run my code:
Your content must have a ListView whose id attribute is 'android.R.id.list'
Note: Even after changing my id attributes to the correct values I still get the error.
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
ListFragment listfragment = null;
switch (position) {
case 0:
listfragment = new HomeFragment();
break;
case 1:
listfragment = new FindPeopleFragment();
break;
case 2:
listfragment = new PhotosFragment();
break;
case 3:
listfragment = new CommunityFragment();
break;
case 4:
listfragment = new PagesFragment();
break;
case 5:
listfragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else if (listfragment != null) {
// do stuff if its a listfragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, listfragment)
.commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
public class PagesFragment extends ListFragment
{
// Counter for checking if Parsed Values are empty - To tell user event has not started
int counter;
int ButtonCounter = 0;
private String gamename;
private String gamedate;
// Progress Dialog
private ProgressDialog pDialog;
private ProgressDialog pDialog2;
private EditText editText;
private TextView textView;
private ListView list1;
//Main variables
private static String pt;
private static String pd;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> inboxList;
// products JSONArray
JSONArray inbox = null;
JSONArray tour = null;
// Inbox JSON url
private static final String INBOX_URL = "http://www…";
// ALL JSON node namesapi_key=tD3djFMGmyWmDUdcgmBVFCd3
private static final String TAG_MESSAGES = "p";
private static final String TAG_ID = "p";
private static final String TAG_FROM = "g";
private static final String TAG_EMAIL = "t";
private static final String TAG_SUBJECT = "r";
private static final String TAG_DATE = "s";
private static final String TAG_TOUR = "t";
private static final String TAG_TOURDATE = "d";
public PagesFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.women_list, container, false);
list1 = (ListView) rootView.findViewById(android.R.id.list);
new LoadInbox().execute();
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
// Hashmap for
inboxList = new ArrayList<HashMap<String, String>>();
/**
* Background Async Task to Load all INBOX messages by making HTTP Request
* */
Log.d("ITS RUNNING!", "Log Message");
new LoadInbox().execute();
}
private void populateList()
{
}
class LoadInbox extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute ()
{
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
/**
* getting Inbox JSON
* */
}
protected void onPostExecute(String file_url)
{
Log.d("Comments", "DoInBackground");
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(INBOX_URL, "GET",
params);
try {
Log.d("Comments", "Try Try Try Try");
inbox = json.getJSONArray(TAG_MESSAGES);
inbox.toString();
// looping through All messages
for (int i = 0; i < inbox.length(); i++)
{
JSONObject c = inbox.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
//Get TOURNAMENT NAME
pgatour = c.getString(TAG_TOUR);
//Get TOURNAMENT DATE
tourdate = c.getString(TAG_TOURDATE);
//Get GOLFER NAME
String from = c.getString(TAG_FROM);
if(from != null && !from.isEmpty())
{
}
//check if blank
else
{
from = "--";
counter++;
}
//GET THUR
String mailer = c.getString(TAG_EMAIL);
if(mailer != null && !mailer.isEmpty())
{
}
else{ mailer = "--";}
///GET ROUND
String subject = c.getString(TAG_SUBJECT);
if(subject != null && !subject.isEmpty())
{
}
else{ subject = "--";}
///GET SCORE
String date = c.getString(TAG_DATE);
if(date != null && !date.isEmpty())
{
}
else
{ subject = "--";
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FROM, from);
map.put(TAG_EMAIL, mailer);
map.put(TAG_DATE, date);
map.put(TAG_SUBJECT, subject);
// adding HashList to ArrayList
inboxList.add(map);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
if( pgatour != null)
{
}
else
{
}
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
//This is for displaying the TOUR NAME & Data above button
textView = (TextView) getView().findViewById(R.id.textView6);
textView.setText(" "+ pt + " - " + pd);
/**
* Updating parsed JSON data into ListView
* */
Log.d("Comments", "pt" +pd );
ListAdapter adapter = new SimpleAdapter(
getActivity(), inboxList,
R.layout.women_list_item, new String[] { TAG_ID, TAG_FROM,TAG_DATE,TAG_EMAIL,TAG_SUBJECT},
new int[] { R.id.from, R.id.subject, R.id.date,R.id.mail,R.id.roundscore });
// updating listview
list1.setAdapter(adapter);
}
});
//class end
}
}
<?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"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
<TextView
android:id="@+id/textView1"
android:text="POS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:textSize="11dp"
android:gravity="center"
/>
<TextView
android:id="@+id/textView2"
android:text="G"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:textSize="11dp"
android:gravity="center"
/>
<TextView
android:id="@+id/textView3"
android:text="S"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:textSize="11dp"
android:gravity="center"
/>
<TextView
android:id="@+id/textView4"
android:text="T"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:textSize="11dp"
android:gravity="center"
/>
<TextView
android:id="@+id/textView5"
android:text="R"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:textSize="11dp"
android:gravity="center"
/>
</LinearLayout>
<ListView
android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:background="#E5E4E2"
android:divider="#736F6E"
android:dividerHeight="4px"
android:padding="8dp"
android:layout_weight="1.0"/>
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="0"
android:textSize="12dp"
android:textColor="#90d2c6"
android:layout_centerVertical="true"
/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:text="Refresh Scores"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:textSize="11dp"
android:layout_weight="1"
/>
</RelativeLayout>
</LinearLayout>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
09-21 17:18:34.873: E/AndroidRuntime(3814): FATAL EXCEPTION: main 09-21 17:18:34.873: E/AndroidRuntime(3814): Process: info.androidhive.slidingmenu, PID: 3814 09-21 17:18:34.873: E/AndroidRuntime(3814): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.slidingmenu/info.androidhive.slidingmenu.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list' 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.app.ActivityThread.access$800(ActivityThread.java:148) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292) 09-21 17:18:34.873: E/AndroidRuntime(3814): at andr oid.os.Handler.dispatchMessage(H andler.java:102) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.os.Looper.loop(Looper.java:135) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.app.ActivityThread.main(ActivityThread.java:5312) 09-21 17:18:34.873: E/AndroidRuntime(3814): at java.lang.reflect.Method.invoke(Native Method) 09-21 17:18:34.873: E/AndroidRuntime(3814): at java.lang.reflect.Method.invoke(Method.java:372) 09-21 17:18:34.873: E/AndroidRuntime(3814): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) 09-21 17:18:34.873: E/AndroidRuntime(3814): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) 09-21 17:18:34.873: E/AndroidRuntime(3814): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list' 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.support.v4.app.ListFragment.ensureList(ListFragment.java:344) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.support.v4.app.ListFragment.onViewC reated(ListFragment.java:145) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:941) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:556) 09-21 17:18:34.873: E/AndroidRuntime(3814): at and roid.app.Instrumentation.callActivityOnStart(Instrumentation.java:1243) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.app.Activity.performStart(Activity.java:5969) 09-21 17:18:34.873: E/AndroidRuntime(3814): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java :2277) 09-21 17:18:34.873: E/AndroidRuntime(3814): ... 10 more
As per documentation ofandroid:id="@id/android:list" ListFragment here . Small section of it.
ListFragment has a default layout that consists of a single list view. However, if you desire, you can customize the fragment layout by returning your own view hierarchy from onCreateView(LayoutInflater, ViewGroup, Bundle). To do this, your view hierarchy must contain a ListView object with the id "@android:id/list" (or list if it's in code)
SOLUTION 1 So if you are changing your fragment to ListFragment then make sure the id of your listView in the layout file must also change and it should be as follow
<ListView
android:id="@id/android:list"
>
and inside onCreate it should be.
View rootView = inflater.inflate(R.layout.women_list, container, false);
list1 = (ListView) rootView.findViewById(android.R.id.list);
and then set the adapter
OR
Solution 2 inside onCreateView you do not need to find the view and directly set the adapter using following code in the onStart or onResume.
setListAdapter(adapter);
OR
Solution 3
Inside onViewCreated or later callback method you use getListView as below and then set the adapter...note-this if used in onCreateView; it would throw you exception
ListView list1 = getListView()
But make sure you are not using same layout file elsewhere other then ListFragment and ListActivity, bcoz if you do so you will get error.
UPDATE BASED ON DISCUSSION AND TRIAL
Thank you for the simple layout R.layout.Women_list. I created a sample project using it with one main Activity(which extended AppCompatActivity) and one Fragment(which extended ListFragment) within activity. And did again a successful test of the above mentioned solution.
Now coming to your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.