使用Fragment创建ListVew



我正在尝试使用fragment填充列表>列表视图。但是当我运行它时,应用程序会崩溃。我从另一个发送的 json 数据中获取数据。我疲倦地将接收到的数据添加到列表中,然后对其进行更新。有帮助吗?这是我的代码。

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
public class OneFragment extends Fragment {
    public OneFragment() {
        // Required empty public constructor
    }
    private ProgressDialog pDialog;
    // JSON Node names
    private static final String TAG_CONTACTS = "us";
    private static final String TAG_NAME = "un";
    private static final String TAG_EMAIL = "ui";
    private static final String TAG = "JSON";
    int portnumber = 3245;
    // contacts JSONArray
    JSONArray contacts = null;
    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.fragment_one);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootview = inflater.inflate(R.layout.fragment_one, container, false);
        //View vew = inflater.inflate(R.layout.fragment_one, container, false);
        new mparse().execute();
        return rootview;
    }
   /* @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        new mparse().execute();
    }
*/
    private class mparse extends AsyncTask<Void,Void,Void> {
        private ProgressDialog pDialog = new ProgressDialog(getActivity());
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            DatagramSocket socket = null;
            DatagramPacket p;
            byte message[] = new byte[1000];
            String jsonStr = "";
            p = new DatagramPacket(message, message.length);
            JSONObject jsonObj = null;
            try {
                Log.d(TAG, "about to create the socket");
                socket = new DatagramSocket(portnumber);
                if (socket == null)
                    Log.d("JSON", "Could not create socket");
                socket.receive(p);
                jsonStr = new String(p.getData());
                Log.d(TAG, "the received string is" + jsonStr);
                if (jsonStr != null) {
                    try {
                        jsonObj = new JSONObject(jsonStr);
                        Log.d(TAG, "inside the json");
                        // Getting JSON Array node
                        contacts = jsonObj.getJSONArray(TAG_CONTACTS);
                        // looping through All Contacts
                        for (int i = 0; i < contacts.length(); i++) {
                            JSONObject c = contacts.getJSONObject(i);
                            //  String id = c.getString(TAG_ID)
                            String name = c.getString(TAG_NAME);
                            Log.d(TAG, "value of user name is" + name);
                            String email = c.getString(TAG_EMAIL);
                            Log.d(TAG, "value of user id is " + email);
                            // tmp hashmap for single contact
                            HashMap<String, String> contact = new HashMap<String, String>();
                            // adding each child node to HashMap key => value
                            contact.put(TAG_NAME, name);
                            contact.put(TAG_EMAIL, email);
                            //adding contact to contact list
                            Log.d(TAG, "the value of TAG_NAME " + TAG_NAME);
                            Log.d(TAG, "the value of TAG_EMAIL " + TAG_EMAIL);
                            contactList.add(contact);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.d(TAG, "inside JSON  eception");
                    }
                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }
            } catch (SocketException e) {
                e.printStackTrace();
                Log.d(TAG, "INside socketexception");
            } catch (IOException e) {
                e.printStackTrace();
                Log.d(TAG, "Inside the IOException");
            }
            return null;
        }
            @Override
            protected void onPostExecute (Void arg) {
                //super.onPostExecute(result);
                // Dismiss the progress dialog
                if (pDialog.isShowing())
                    pDialog.dismiss();
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListView mylistView = (ListView) getView().findViewById(R.id.list);
                ListAdapter adapter = new SimpleAdapter(
                        getActivity(), contactList,
                        R.layout.list_xml, new String[]{TAG_NAME, TAG_EMAIL,
                }, new int[]{R.id.name,
                        R.id.email, R.id.mobile});
                ;
                mylistView.setAdapter(adapter);
            }
        }
}

这是日志:

 Process: com.example.kgj5kor.material, PID: 18196
    java.lang.NullPointerException
            at com.example.kgj5kor.material.OneFragment$mparse.onPostExecute(OneFragment.java:174)
            at com.example.kgj5kor.material.OneFragment$mparse.onPostExecute(OneFragment.java:77)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5335)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)

,而不是在onPostExecute()中创建ListView对象,而是在onCreateView()中创建它并将其公开。用getView().findViewById替换CC_4。

ListView mylistView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootview = inflater.inflate(R.layout.fragment_one, container, false);
    mylistView = (ListView) rootview.findViewById(R.id.list);
    new mparse().execute();
    return rootview;
}

Renan Bandeira建议的也要在onCreateView()中初始化您的contactList

contactList永远不会初始化。在onCreateView()方法中初始化它,然后重试。

编辑

我重写了课程,以避免可能的问题。您的属性不明,pDialog在两个类中。另外,我将mparse类的名称更改为 Mparse,使其正如公约所说的:

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
public class OneFragment extends Fragment {
    public OneFragment() {
        // Required empty public constructor
    }
    private ProgressDialog pDialog;
    // JSON Node names
    private static final String TAG_CONTACTS = "us";
    private static final String TAG_NAME = "un";
    private static final String TAG_EMAIL = "ui";
    private static final String TAG = "JSON";
    int portnumber = 3245;
    // contacts JSONArray
    JSONArray contacts = null;
    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_one, container, false);
    }

    @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        contactList = new ArrayList<>();
        new Mparse().execute();
    }
    private class Mparse extends AsyncTask<Void,Void,Void> {
        public Mparse() {
            pDialog = new ProgressDialog(getActivity());
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            DatagramSocket socket = null;
            DatagramPacket p;
            byte message[] = new byte[1000];
            String jsonStr = "";
            p = new DatagramPacket(message, message.length);
            JSONObject jsonObj = null;
            try {
                Log.d(TAG, "about to create the socket");
                socket = new DatagramSocket(portnumber);
                if (socket == null)
                    Log.d("JSON", "Could not create socket");
                socket.receive(p);
                jsonStr = new String(p.getData());
                Log.d(TAG, "the received string is" + jsonStr);
                if (jsonStr != null) {
                    try {
                        jsonObj = new JSONObject(jsonStr);
                        Log.d(TAG, "inside the json");
                        // Getting JSON Array node
                        contacts = jsonObj.getJSONArray(TAG_CONTACTS);
                        // looping through All Contacts
                        for (int i = 0; i < contacts.length(); i++) {
                            JSONObject c = contacts.getJSONObject(i);
                            //  String id = c.getString(TAG_ID)
                            String name = c.getString(TAG_NAME);
                            Log.d(TAG, "value of user name is" + name);
                            String email = c.getString(TAG_EMAIL);
                            Log.d(TAG, "value of user id is " + email);
                            // tmp hashmap for single contact
                            HashMap<String, String> contact = new HashMap<String, String>();
                            // adding each child node to HashMap key => value
                            contact.put(TAG_NAME, name);
                            contact.put(TAG_EMAIL, email);
                            //adding contact to contact list
                            Log.d(TAG, "the value of TAG_NAME " + TAG_NAME);
                            Log.d(TAG, "the value of TAG_EMAIL " + TAG_EMAIL);
                            contactList.add(contact);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.d(TAG, "inside JSON  eception");
                    }
                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }
            } catch (SocketException e) {
                e.printStackTrace();
                Log.d(TAG, "INside socketexception");
            } catch (IOException e) {
                e.printStackTrace();
                Log.d(TAG, "Inside the IOException");
            }
            return null;
        }
            @Override
            protected void onPostExecute (Void arg) {
                super.onPostExecute(result);
                //In case the Fragment isn't shown anymore.
                if (!isAdded() || getView() == null) {
                    return;
                }
                // Dismiss the progress dialog
                if (pDialog != null && pDialog.isShowing())
                    pDialog.dismiss();
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListView mylistView = (ListView) getView().findViewById(R.id.list);
                ListAdapter adapter = new SimpleAdapter(
                        getActivity(), contactList,
                        R.layout.list_xml, new String[]{TAG_NAME, TAG_EMAIL,
                }, new int[]{R.id.name,
                        R.id.email, R.id.mobile});
                ;
                mylistView.setAdapter(adapter);
            }
        }
}

最新更新