1

在我尝试在我的片段中实现 listview 后出现错误。请检查我的代码,除了使用 ListView lv = getListView(); 之外,我还试图为我的列表视图增加​​一个 xml 布局 . 我知道这种方法有效,但我不希望那样。请帮我纠正我的代码。

日志猫:

11-07 10:54:36.828: E/AndroidRuntime(2947): FATAL EXCEPTION: main
11-07 10:54:36.828: E/AndroidRuntime(2947): java.lang.NullPointerException
11-07 10:54:36.828: E/AndroidRuntime(2947):     at testing.app.FreeFragment$loadListView.onPostExecute(FreeFragment.java:132)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at testing.app.FreeFragment$loadListView.onPostExecute(FreeFragment.java:1)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at android.os.AsyncTask.finish(AsyncTask.java:417)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at android.os.Looper.loop(Looper.java:130)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at android.app.ActivityThread.main(ActivityThread.java:3691)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at java.lang.reflect.Method.invokeNative(Native Method)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at java.lang.reflect.Method.invoke(Method.java:507)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
11-07 10:54:36.828: E/AndroidRuntime(2947):     at dalvik.system.NativeStart.main(Native Method)

主要活动.java

public class MainActivity extends SherlockFragmentActivity {
    Tab tab;


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);



        AppRater.app_launched(this);
        if (!isNetworkAvailable()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Internet Connection Required")
                    .setCancelable(false)
                    .setPositiveButton("Exit",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    finish();
                                }

                            });
            AlertDialog alert = builder.create();
            alert.show();

        } else {

            ActionBar actionBar = getSupportActionBar();
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);




            tab = actionBar.newTab().setTabListener(new FreeFragment())
                    .setIcon(R.drawable.free);
            actionBar.addTab(tab);

            tab = actionBar.newTab().setTabListener(new BuyFragment())
                    .setIcon(R.drawable.buy);
            actionBar.addTab(tab);

            tab = actionBar.newTab().setTabListener(new ReaderFragment())
                    .setIcon(R.drawable.reader);
            actionBar.addTab(tab);
        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }



}

自由片段.java

 public class FreeFragment extends Fragment implements
        ActionBar.TabListener {

    static final String URL = "https://myxml.xml";
    static final String KEY_SONG = "song";
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_CAT_ARTIST = "artistcat";
    static final String KEY_DURATION = "duration";
    static final String KEY_THUMB_URL = "thumb_url";
    static final String KEY_BIG_URL = "big_url";
    static final String KEY_CAT_URL = "cat_url";
    static final String KEY_DESC = "cat_desc";
    ArrayList<HashMap<String, String>> menuItems;
    ListAdapter adapter;
    private Fragment mFragment;

    ListView lv;

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

            View v = inflater.inflate(R.id.listview); //<--- what do i inflate here? 
            lv = (ListView) v.findViewById(R.id.list);

            if (!isNetworkAvailable()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage("Internet Connection Required")
                        .setCancelable(false)
                        .setPositiveButton("Exit",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        FileCache loader = new FileCache(null);
                                        loader.clear();  
                                        getActivity().finish();
                                    }

                                });
                AlertDialog alert = builder.create();
                alert.show();

            } else {

                new loadListView().execute();

            }


            return v;
    }



    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

    public class loadListView extends AsyncTask<Integer, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Integer... args) {
            // updating UI from Background Thread
            menuItems = new ArrayList<HashMap<String, String>>();

            XMLParser parser = new XMLParser();
            String xml = parser.getXmlFromUrl(URL); // getting XML
            Document doc = parser.getDomElement(xml); // getting DOM element

            NodeList nl = doc.getElementsByTagName(KEY_SONG);
            // looping through all item nodes <item>
            for (int i = 0; i < nl.getLength(); i++) {
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                // adding each child node to HashMap key => value
                map.put(KEY_ID, parser.getValue(e, KEY_ID));
                map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
                map.put(KEY_CAT_ARTIST, parser.getValue(e, KEY_CAT_ARTIST));
                map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
                map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
                map.put(KEY_BIG_URL, parser.getValue(e, KEY_BIG_URL));
                map.put(KEY_CAT_URL, parser.getValue(e, KEY_CAT_URL));
                map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
                // adding HashList to ArrayList
                menuItems.add(map);
            }
            return null;
        }

        @Override
        protected void onPostExecute(String args) {

            if (getActivity() != null) {
                adapter = new MainPageLazyAdapter(getActivity(), menuItems);
                lv = (ListView)getActivity().findViewById(R.id.list);                                 
                //setListAdapter(adapter);
                lv.setAdapter(adapter);


            }

        }
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        mFragment = new FreeFragment();
        ft.add(android.R.id.content, mFragment);
        ft.attach(mFragment);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(mFragment);
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {

    }
}

列表视图.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

     <com.google.ads.AdView android:id="@+id/adView"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         android:layout_centerHorizontal="true"
                         ads:adUnitId="mycode"
                         ads:adSize="BANNER"
                         ads:loadAdOnCreate="true"
                         />


<ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/adView"
    android:cacheColorHint="#00000000" >

</ListView>
</RelativeLayout>
4

1 回答 1

1

当然 ListView 是空的。

这个:

            @Override
            protected void onPostExecute(String args) {

                if (getActivity() != null) {
                    adapter = new MainPageLazyAdapter(getActivity(), menuItems);
                    lv.setAdapter(adapter);

                    lv = (ListView)getActivity().findViewById(R.id.list);


                }

            }

需要是这样的:

            @Override
            protected void onPostExecute(String args) {

                if (getActivity() != null) {
                    adapter = new MainPageLazyAdapter(getActivity(), menuItems);
                    lv = (ListView)getActivity().findViewById(R.id.list);                                 

                    lv.setAdapter(adapter);


                }

            }

ListView初始化ListView.

更重要的是,你做错了:你使用的 a SherlockListFragmentwhich 本身可以扩展ListFragment,你可以认为它与 a 类似ListActivity——它只是为你提供了一些方便来设置 a listview。您只需调用setListAdapter您的postExecute. 您不需要自己膨胀任何列表视图;这就是 a 的全部意义所在ListFragment

编辑:

因为,正如您所指出的,您希望在 Fragment 中不仅仅是一个 ListView,所以不要使用 SherlockListFragment。相反,扩展一个普通的旧片段。然后在 onCreateView 内部,执行以下操作:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.listview);
        lv = v.findViewById(R.id.list);
        return v;
}

现在,您可以将该 ListView 作为字段引用。现在,在你的 onPostExecute 中,你可以做lv.setAdapter(adapter);

于 2012-11-07T03:13:39.827 回答