java - 在 fragment 和列表 fragment 之间切换会导致错误

标签 java android json listview android-fragments

我在使用片段填充列表视图时遇到问题,我有一个名为PagesFragment的片段类,该片段类扩展了Fragment.。我还有一个MainActivity,可以使用菜单在我的片段之间切换。

我相信我需要扩展ListFragment以便在Fragment'PagesFragment'中填充列表视图,但是当我更改所有类以扩展ListFragment,并在MainActivity中将案例更改为ListFragement时,尝试运行时出现错误我的代码:

您的内容必须具有一个ID属性为“ android.R.id.list”的ListView

注意:即使将我的id属性更改为正确的值,我仍然会收到错误消息。

切换片段的代码-使用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);
}


片段代码-无法填充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
    }

  }


布局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布局:

  <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):致命异常:主要
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:您内容必须具有ID属性为“ android.R.id.list”的ListView
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):at 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):at and 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):at java.lang.reflect.Method.invoke(本机方法)
    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):在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:您的内容必须具有ID属性为'android.R.id.list'的ListView
    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):at和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个

最佳答案

根据android:id =“ @ id / android:list”的文档
ListFragment here。小部分。


  ListFragment具有由单个列表视图组成的默认布局。
  但是,如果需要,可以通过以下方式自定义片段布局
  从onCreateView(LayoutInflater,
  ViewGroup,捆绑销售)。为此,您的视图层次结构必须包含一个
  ID为“ @android:id / list”的ListView对象(如果位于,则为list
  码)


解决方案1
因此,如果要将片段更改为ListFragment,请确保布局文件中的listView的ID也必须更改,并且应如下所示

<ListView
 android:id="@id/android:list"
>


并应该在onCreate中。

View rootView = inflater.inflate(R.layout.women_list, container, false);
list1 = (ListView) rootView.findViewById(android.R.id.list);


然后设置适配器
要么
解决方案2
在onCreateView内,您无需查找视图并使用onStart或onResume中的以下代码直接设置适配器。

setListAdapter(adapter); 


要么
解决方案3
在onViewCreated或更高版本的回调方法中,您可以使用getListView,如下所示
然后设置适配器...如果在onCreateView中使用,请注意此;会抛出异常

ListView list1  = getListView()



  但是请确保您不在其他地方使用相同的布局文件
  ListFragment和ListActivity,如果这样做,则会出现错误。


基于讨论和试用的更新
感谢您的简单布局R.layout.Women_list。我使用它创建了一个示例项目,其中有一个主Activity(扩展了AppCompatActivity)和一个Fragment(扩展了ListFragment)。并再次成功测试了上述解决方案。
现在来解决您的问题。


您的应用程序中可能有多个布局,其中可能包含许多列表视图...因此,所有列表视图的ID都不必为@ id / android:list,而仅那些列表视图必须具有其ID的ID或在扩展的Fragment中使用的布局扩展ListActivity的ListFragment或Activiy也请参考前面的说明。
我不知道为什么您要在MainActivity布局中将列表视图的ID保留为android:list,是否真的需要它?
请再次检查所有片段和活动以及应用程序中使用的布局。可能是您确实在一个文件夹中更改了listview的ID,然后又更改了另一个,因此您需要更改res / layout /和res /该R.layout.Women_list的layout -... /目录

关于java - 在 fragment 和列表 fragment 之间切换会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32697511/

相关文章:

android - OutOfMemoryError 如果我使用 ViewPager 重新启动完成的 Activity

javascript - 如何将此输出发布到 API

javascript - JSON 和 jQuery

ios - 葫芦-ios : Run test physical device installed ipa without xcodeproj

java - 如何编译多个相互依赖的java文件?

java - 我如何知道 eclipse 已经构建完成了我的项目(禁用自动构建)?

android - 使用注释的改造拦截器的 OkHttp 调用超时未应用

android - ionic 构建android后http请求失败

java - LambdaJ 类属性匹配器

java - 指定类文件目标 eclipse ide