Simple Listview in fragment using SimpleAdapter

蓝咒 提交于 2019-12-20 02:46:21

问题


Here is my code for fragment extending ListFragment and below are the errors it is showing.Almost Same code is working fine for activity except that in activity i am getting listview through

ListView lv = getListView();

and in fragment through

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

It shows nullpointer exception on line java:109 lv.setOnItemClickListener(new AdapterView.OnItemClickListener() If i remove setOnItemClickListener it shows null pointer exception on lv.setAdapter(adapter); SoundCloudFragment.java

 public class SoundCloudFragment extends ListFragment {
        private ProgressDialog pDialog;
        private FragmentActivity myContext;
        ListView lv;
        @Override
        public void onAttach(Activity activity) {

            if (activity instanceof FragmentActivity) {
                myContext = (FragmentActivity) activity;


            }

            super.onAttach(activity);
        }





        // contacts JSONArray
        JSONArray contacts = null;

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList;


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // mVisulizerView = (VisualizerView)findViewById(R.id.visualizerView);

            View rootView = inflater.inflate(R.layout.soundcloud, container, false);
            lv= (ListView)rootView.findViewById(R.id.list);
            // Get ListView object from xml


     //   lv = getListView();

          lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id)
                {
                    // getting values from selected ListItem
                    String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                    String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
                    String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

                    // Starting single contact activity
                    Intent in = new Intent(myContext,
                            SingleContactActivity.class);
                    in.putExtra("name", TAG_TITLE);
                    in.putExtra("id", cost);

                    startActivity(in);

                }
            });

            // Calling async task to get json
            new GetContacts().execute();
            return rootView;
        }
        private class GetContacts extends AsyncTask<Void, Void, Void>  {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Showing progress dialog
                pDialog = new ProgressDialog(myContext);
                pDialog.setMessage("Please wait...");
                pDialog.setCancelable(false);
                pDialog.show();

            }

            @Override
            protected Void doInBackground(Void... arg0) {
                // Creating service handler class instance
                ServiceHandler sh = new ServiceHandler();

                // Making a request to url and getting response
                String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

                Log.d("Response: ", "> " + jsonStr);

                if (jsonStr != null) {
                    try {
                        JSONArray json = new JSONArray(jsonStr);

                        // looping through All Contacts
                        for (int i = 0; i < json.length(); i++) {
                            JSONObject jsonObj = json.getJSONObject(i);
                            //JSONObject c = contacts.getJSONObject(i);

                            String title = jsonObj.getString(TAG_TITLE);
                            String id = jsonObj.getString(TAG_ID);
                            String kind = jsonObj.getString(TAG_KIND);
                            String duration =jsonObj.getString(TAG_DURATION);
                        /*  String gender = c.getString(TAG_GENDER);

                            // Phone node is JSON Object
                            JSONObject phone = c.getJSONObject(TAG_PHONE);
                            String mobile = phone.getString(TAG_PHONE_MOBILE);
                            String home = phone.getString(TAG_PHONE_HOME);
                            String office = phone.getString(TAG_PHONE_OFFICE);*/

                            // tmp hashmap for single contact
                            HashMap<String, String> contact = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            contact.put(TAG_TITLE, title);
                            contact.put(TAG_ID, id);
                            contact.put(TAG_KIND, kind);
                            contact.put(TAG_DURATION, duration);


                            // adding contact to contact list
                            contactList.add(contact);
                        }
                    } catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }

                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                // Dismiss the progress dialog
                if (pDialog.isShowing())
                    pDialog.dismiss();
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        myContext, contactList,
                        R.layout.soundcloud_item, new String[] { TAG_TITLE, TAG_ID,
                        TAG_KIND }, new int[] { R.id.name,
                        R.id.email, R.id.mobile });

              lv.setAdapter(adapter);

            }

        }


    }

Errors-

 FATAL EXCEPTION: main
        java.lang.NullPointerException
                at com.peoplecloud.guggu.ui.fragment.SoundCloudFragment.onCreateView(SoundCloudFragment.java:109)
                at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:829)
                at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
                at android.app.BackStackRecord.run(BackStackRecord.java:635)
                at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
                at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
                at android.os.Handler.handleCallback(Handler.java:615)
                at android.os.Handler.dispatchMessage(Handler.java:92)
                at android.os.Looper.loop(Looper.java:153)
                at android.app.ActivityThread.main(ActivityThread.java:5086)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:511)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
                at dalvik.system.NativeStart.main(Native Method)

回答1:


Try this way,hope this will help you to solve your problem.

There is two way to given ListView id.

1.android predefined id like :

XML

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

Activty

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

Fragment

lv= (ListView)rootView.findViewById(android.R.id.list); 

2.Custom id like :

XML

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

Activty

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

Fragment

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



回答2:


Try using this code to get your ListView:

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

As you are using a ListFragment as the base class. Also you probably would need to use android.R.id.list to get your list if you put it correctly in your xml file.




回答3:


try this.

ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.soundcloud, container, false);

and also in your onItemClick

// Starting single contact activity

Intent in = new Intent(getActivity().getApplicationContext(),
                   SingleContactActivity.class);
          in.putExtra("name", TAG_TITLE);
          in.putExtra("id", cost);
          startActivity(in);


来源:https://stackoverflow.com/questions/26668368/simple-listview-in-fragment-using-simpleadapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!