【问题标题】:Creating ListVew using Fragment使用 Fragment 创建 ListView
【发布时间】:2016-06-23 10:46:18
【问题描述】:

我正在尝试使用 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)

【问题讨论】:

    标签: android listview android-asynctask


    【解决方案1】:

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

    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

    【讨论】:

    • 感谢您的回复,我按照您的建议做了仍然无法运行它。
    • 发布您的日志报告
    【解决方案2】:

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

    【讨论】:

    • 感谢 :) 您的回复,但我仍然无法找到解决方案。
    • 取消注释super.onPostExecute() 行。
    • 运气不好 :(
    • 另外,您正在尝试在创建视图之前对其进行更新!请注意,当您在 onCreateView() 中调用 new mparse().execute(); 时,您可能还没有视图,因为 mparse 是在单独的线程中调用的。尝试在onActivityCreated() 方法中调用它。
    • 感谢您一直以来 :) 应用程序崩溃,尚无解决方案 :(
    猜你喜欢
    • 2014-01-07
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多