片段和导致错误ListFragments之间切换 [英] Switching between Fragments and ListFragments causing errors

查看:138
本文介绍了片段和导致错误ListFragments之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

填充有片段使用一个ListView的问题,我已要求我是个片段类的 PagesFragment 扩展片段..我也有使用菜单我的片段之间开关的MainActivity。

我相信我需要为了延长ListFragment来填充我的列表视图在我片段PagesFragment,但是当我改变我所有的类来扩展ListFragment,并改变我的情况下ListFragement在我MainActivity ,我得到一个错误,当我尝试运行我的code:

您的内容必须有一个ListView的id属性是'android.R.id.list

注意:我的ID属性设置为正确的值,即使改变之后,我仍然得到错误。

code为转换片段 - 使用SideMenu

  / **
 所选导航抽屉列表项* Diplaying片段视图
 * * /
私人无效displayView(INT位置){
    //更新替换片段的主要内容
    片段片段= NULL;
    ListFragment listfragment = NULL;
    开关(位置){
    情况下0:
        listfragment =新HomeFragment();
        打破;
    情况1:
        listfragment =新FindPeopleFragment();
        打破;
    案例2:
        listfragment =新PhotosFragment();
        打破;
    案例3:
        listfragment =新CommunityFragment();
        打破;
    情况4:
        listfragment =新PagesFragment();
        打破;
    情况5:
        listfragment =新WhatsHotFragment();
        打破;    默认:
        打破;
    }如果(片段!= NULL){
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container,片段).commit();        //更新所选项目和标题,然后关上抽屉
    mDrawerList.setItemChecked(位置,真正的);
        mDrawerList.setSelection(位置);
    (navMenuTitles [位置])的setTitle;
        mDrawerLayout.closeDrawer(mDrawerList);
    }  否则,如果(listfragment!= NULL){
        //如果一个listfragment做的东西
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
            .replace(R.id.frame_container,listfragment)
            。承诺();
 //更新所选项目和标题,然后关上抽屉
        mDrawerList.setItemChecked(位置,真正的);
            mDrawerList.setSelection(位置);
        (navMenuTitles [位置])的setTitle;
            mDrawerLayout.closeDrawer(mDrawerList);
}

code的片段 - 无法填充的ListView

 公共类PagesFragment扩展ListFragment
{
//柜台,如果解析的值是空的检查 - 告诉用户活动尚未开始
INT计数器;INT ButtonCounter = 0;
私人字符串gamename;
私人字符串gamedate;
//进度对话框
私人ProgressDialog pDialog;
私人ProgressDialog pDialog2;
私人的EditText EDITTEXT;
私人TextView的TextView的;
私人的ListView list1的;
//主要变量
私人静态字符串PT;
私人静态字符串PD;
//创建JSON解析器对象
JSONParser jsonParser =新JSONParser();
ArrayList的<&HashMap的LT;字符串,字符串>> inboxList;
//产品JSONArray
JSONArray收件箱= NULL;
JSONArray旅游= NULL;
//收件箱JSON网址
私有静态最后弦乐INBOX_URL =HTTP:// WWW ......;
//所有JSON节点namesapi_key = tD3djFMGmyWmDUdcgmBVFCd3
私有静态最后弦乐TAG_MESSAGES =P;
私有静态最后弦乐TAG_ID =P;
私有静态最后弦乐TAG_FROM =G;
私有静态最后弦乐TAG_EMAIL =T;
私有静态最后弦乐TAG_SUBJECT =R;
私有静态最后弦乐TAG_DATE =S;
私有静态最后弦乐TAG_TOUR =T;
私有静态最后弦乐TAG_TOURDATE =D;公共PagesFragment(){}   @覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState){
     查看rootView = inflater.inflate(R.layout.women_list,集装箱,FALSE);
     list1的=(ListView控件)rootView.findViewById(android.R.id.list);
      新LoadInbox()执行();
      返回rootView;
}
@覆盖
公共无效onActivityCreated(捆绑savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
     //为哈希映射
     inboxList =新的ArrayList<&HashMap的LT;字符串,字符串>>();
     / **
     *背景异步任务以通过HTTP请求负载所有收件箱的邮件
     * * /
     Log.d(它的运行!,日志消息);    新LoadInbox()执行();} 私人无效populateList()
 {
 }     类LoadInbox扩展的AsyncTask<字符串,字符串,字符串>
    {
        / **
         *启动后台线程显示进度对话框之前
         * * /
        @覆盖
        在preExecute保护无效()
        {
        }        @覆盖
        保护字符串doInBackground(字符串... PARAMS){
            // TODO自动生成方法存根
            返回null;
        }        / **
         *让收件箱JSON
         * * /}    保护无效onPostExecute(字符串FILE_URL)
    {         Log.d(评论,DoInBackground);
        //大厦参数
        清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();        // URL从获取JSON字符串
        JSONObject的JSON = jsonParser.makeHtt prequest(INBOX_URL,GET,
                PARAMS);    尝试{
         Log.d(评论,试试试用试用);
            收件箱= json.getJSONArray(TAG_MESSAGES);            inbox.toString();
            //通过所有消息循环
            的for(int i = 0; I< inbox.length();我++)
            {
                  JSONObject的C = inbox.getJSONObject(I)
                    //存储在变量中的每个JSON项目
                    字符串ID = c.getString(TAG_ID);
                    //获取锦标赛NAME
                    pgatour = c.getString(TAG_TOUR);
                    //获取锦标赛日期
                   tourdate = c.getString(TAG_TOURDATE);
                   //获取GOLFER NAME
                   从字符串= c.getString(TAG_FROM);                    如果(自= NULL&放大器;!&安培;!from.isEmpty())
                    {
                    }                  //检查是否空白
                   其他
                   {                      从= - ;
                      反++;
                   }
                 //获取THUR
                  字符串邮件= c.getString(TAG_EMAIL);                  如果(邮件= NULL&放大器;!&安培;!mailer.isEmpty())
                  {                  }
                  其他{邮件= - ;}
                  ///避开                字符串主题= c.getString(TAG_SUBJECT);                如果(主题= NULL&放大器;!&安培;!subject.isEmpty())
                 {                 }                其他{主题= - ;}                 /// GET SCORE                字符串日期= c.getString(TAG_DATE);                 如果(日期=空&安培;!&安培;!date.isEmpty())
                   {
                   }                  其他
                  {主题= - ;                  }                //创建新的HashMap
                HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();                //将每个子节点的HashMap键=>值
                map.put(TAG_ID,身份证);
                map.put(TAG_FROM,来自);
                map.put(TAG_EMAIL,邮件);
                map.put(TAG_DATE,日期);
                map.put(TAG_SUBJECT,学科);                //添加HashList到ArrayList的
                inboxList.add(地图);
            }        }        赶上(JSONException E)
        {
            e.printStackTrace();
        }        如果(pgatour!= NULL)
         {
         }
         其他
         {         }    getActivity()。runOnUiThread(新的Runnable()
    {
      公共无效的run()
             {         //这是用于显示线路名称和放大器;上面的按键数据
         的TextView =(TextView中)getView()findViewById(R.id.textView6)。
        textView.setText(+ PT + - + PD);                            / **
                             *更新解析JSON数据到ListView控件
                             * * /         Log.d(注释,PT+ PD);                            ListAdapter适配器=新SimpleAdapter(
                                   getActivity(),inboxList,
                                    R.layout.women_list_item,新的String [] {TAG_ID,TAG_FROM,TAG_DATE,TAG_EMAIL,TAG_SUBJECT},
                                    新的INT [] {R.id.from,R.id.subject,R.id.date,R.id.mail,R.id.roundscore});
                            //更新列表视图
                     list1.setAdapter(适配器);
             }
    });    //类结束
    }  }

布局code XML - Women_list.XML:

 <?XML版本=1.0编码=UTF-8&GT?;
   < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android  机器人:layout_width =FILL_PARENT
  机器人:layout_height =FILL_PARENT
  机器人:方向=垂直>   <的LinearLayout
    机器人:ID =@ + ID / linearLayout1
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =WRAP_CONTENT
    机器人:layout_alignParentTop =真
    机器人:layout_centerHorizo​​ntal =真正的>     <的TextView
        机器人:ID =@ + ID / textView1
        机器人:文字=POS
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_gravity =center_vertical
        机器人:layout_weight =1
        机器人:TEXTSIZE =11DP
        机器人:比重=中心
       />      <的TextView
        机器人:ID =@ + ID / textView2
        机器人:文字=G
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_gravity =center_vertical
        机器人:layout_weight =1
        机器人:TEXTSIZE =11DP
        机器人:比重=中心
         />    <的TextView
        机器人:ID =@ + ID / textView3
        机器人:文字=S
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_gravity =center_vertical
        机器人:layout_weight =1
         机器人:TEXTSIZE =11DP
        机器人:比重=中心
         />     <的TextView
        机器人:ID =@ + ID / textView4
        机器人:文字=T
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_gravity =center_vertical
        机器人:layout_weight =1
         机器人:TEXTSIZE =11DP
        机器人:比重=中心
        />     <的TextView
        机器人:ID =@ + ID / textView5
        机器人:文字=R
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_gravity =center_vertical
        机器人:layout_weight =1
         机器人:TEXTSIZE =11DP
        机器人:比重=中心
        />
< / LinearLayout中>
  < ListView控件
    机器人:ID =@ ID /安卓名单
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =0dp
    机器人:背景=#E5E4E2
    机器人:分=#736F6E
    机器人:dividerHeight =递四方
    机器人:填充=8DP
    机器人:layout_weight =1.0/>    <的TextView
        机器人:ID =@ + ID / textView6
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_gravity =center_vertical
        机器人:layout_weight =0
         机器人:TEXTSIZE =12dp
         机器人:文字颜色=#90d2c6
         机器人:layout_centerVertical =真
        />
    < RelativeLayout的
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT
    机器人:方向=横向> <按钮
     机器人:ID =@ + ID /按钮1
    机器人:文字=刷新成绩
     机器人:layout_height =WRAP_CONTENT
     机器人:layout_width =FILL_PARENT
     机器人:TEXTSIZE =11DP
机器人:layout_weight =1
      />  < / RelativeLayout的>< / LinearLayout中>

MainActivity XML布局:

 < android.support.v4.widget.DrawerLayout
  的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
  机器人:ID =@ + ID / drawer_layout
  机器人:layout_width =match_parent
  机器人:layout_height =match_parent><! - 的FrameLayout显示片段 - >
<的FrameLayout
    机器人:ID =@ + ID / frame_container
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent/>< TabWidget
        机器人:ID =@机器人:ID /标签
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        />
<! - 列表视图显示滑块菜单 - >
< ListView控件
    机器人:ID =@ + ID /列表
    机器人:layout_width =240dp
    机器人:layout_height =match_parent
    机器人:layout_gravity =开始
    机器人:choiceMode =singleChoice
    机器人:分=@彩色/ list_divider
    机器人:dividerHeight =1DP
    机器人:listSelector =@绘制/ list_selector
    机器人:背景=@色/ list_background/>

错误信息:#

09-21 17:18:34.873:E / AndroidRuntime(3814):致命异常:主要
09-21 17:18:34.873:E / AndroidRuntime(3814):工艺:info.androidhive.slidingmenu,PID:3814
09-21 17:18:34.873:E / AndroidRuntime(3814):了java.lang.RuntimeException:无法启动活动ComponentInfo {info.androidhive.slidingmenu / info.androidhive.slidingmenu.MainActivity}了java.lang.RuntimeException:您的内容必须有一个ListView的id属性是'android.R.id.list
09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
     09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread.access $ 800(ActivityThread.java:148)
     09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1292)
     09-21 17:18:34.873:E / AndroidRuntime(3814):在安德烈oid.os.Handler.dispatchMessage(Handler.java:102)
    09-21 17:18:34.873:E / AndroidRuntime(3814):在android.os.Looper.loop(Looper.java:135)
    09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread.main(ActivityThread.java:5312)
    09-21 17:18:34.873:E / AndroidRuntime(3814):在java.lang.reflect.Method.invoke(本机方法)
    09-21 17:18:34.873:E / AndroidRuntime(3814):在java.lang.reflect.Method.invoke(Method.java:372)
    09-21 17:18:34.873:E / AndroidRuntime(3814):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:901)
    09-21 17:18:34.873:E / AndroidRuntime(3814):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
    09-21 17:18:34.873:E / AndroidRuntime(3814):了java.lang.RuntimeException::你的内容必须有一个ListView的id属性是'android.R.id.list产生的原因
    09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.ListFragment.ensureList(ListFragment.java:344)
    09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.ListFragment.onViewCreated(ListFragment.java:145)
    09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:941)
    09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
    09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
    09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
     09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:556)
     09-21 17:18:34.873:E / AndroidRuntime(3814):在和roid.app.Instrumentation.callActivityOnStart(Instrumentation.java:1243)
     09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.Activity.performStart(Activity.java:5969)
     09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
     09-21 17:18:34.873:E / AndroidRuntime(3814):10 ...更多


解决方案

根据文档ofandroid:ID =@ ID /安卓名单
ListFragment 这里。小部分吧。


  

ListFragment具有由一个单一的列表视图的默认布局。
  但是,如果你的愿望,你可以自定义片段布局
  从onCreateView(LayoutInflater返​​回自己的视图层次,
  ViewGroup中,包)。要做到这一点,您的视图层次结构必须包含一个
  与ID的ListView对象@android:ID /列表(或列表,如果它在
  code)


解决方案1 ​​
所以,如果你改变你的片段ListFragment然后确保在布局文件你的ListView的ID也必须改变,它应该是如下

 < ListView控件
 机器人:ID =@ ID /安卓名单
>

和里面的onCreate是应该的。

 查看rootView = inflater.inflate(R.layout.women_list,集装箱,FALSE);
list1的=(ListView控件)rootView.findViewById(android.R.id.list);

,然后将适配器结果
结果
解决方案2
里面onCreateView你不需要找视图,并直接使用下面的调用onStart或者onResume code设置适配器。

  setListAdapter(适配器);

结果
解决方案3 结果
内部onViewCreated或更高版本回调方法使用getListView如下
然后设置适配器......注意,这如果onCreateView使用;这会让你异常

 的ListView list1的= getListView()


  

但要确保你没有使用相同的布局文件其他地方的话
  ListFragment和ListActivity,bcoz如果你这样做你会得到错误。


更新基于讨论和试用结果
谢谢你的简单的布局R.layout.Women_list。我用它有一个主要的活动(其中延长AppCompatActivity)和一个片段(其扩展ListFragment)活动中创建一个示例项目。并再次做了上述解决方案的成功试验。搜索结果
现在来到你的问题。


  1. 您可能会在应用程序中多个布局可能包含许多列表视图...所以它不是neccessary所有的列表视图应该有id作为 @ ID /安卓列表 只有那些列表视图必须有一个ID,其布局片段延伸ListFragment或Activiy延伸ListActivity要么使用的另请参阅previous注释。

  2. 我不知道为什么你保持列表视图由于Android的id:在MainActivity布局名单是不是真的需要?

  3. 请再次检查所有的碎片和活动与application.It使用可能会发生你所做更改列表视图的id一个文件夹中,离开等,所以你需要在你的RES /布局中的每一个改变布局沿/和RES /布局-... /为R.layout.Women_list
  4. 目录

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.

Code for Switching Fragments - using a SideMenu

 /**
 * 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);
}

Code for Fragment - Can't populate ListView

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
    }

  }

Layout CODE XML - Women_list.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"
  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>

MainActivity XML Layout:

  <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"/>

Error Message: #

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(Handler.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.onViewCreated(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.

  1. You might have multiple layouts in your application which might contain many listviews...so it not neccessary that all the listview should have id as @id/android:list only those listview must have that id whose layout are either used in Fragment which extends ListFragment or Activiy which extends ListActivity Also refer previous note.
  2. I do not know why you are keeping the id of list view as android:list in the MainActivity layout is it really needed?
  3. Please once again check all the fragments and activity along with layout used in application.It might have happen you did change the id of listview in one folder and left other so you need to change in every one of your res/layout/ and res/layout-.../ directories for that R.layout.Women_list

这篇关于片段和导致错误ListFragments之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆