Fragment' OnCreateView()中的NullPointerException

时间:2015-03-24 11:28:25

标签: android json listview fragment

我在Fragement的OnCreateView()方法中得到一个NullPointerException。我尝试了几件事,但错误不断出现。我认为错误来自listview。

这是我的代码:

  package com.imptmd.charliemacdonald.desleutelaar;

 import android.app.ProgressDialog;
 import android.content.Intent;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.support.v4.app.ListFragment;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.AdapterView;
 import android.widget.ListAdapter;
 import android.widget.ListView;
 import android.widget.SimpleAdapter;
 import android.widget.TextView;

 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;

 import java.util.ArrayList;
 import java.util.HashMap;


 public class SlotenFragment extends ListFragment {

private ProgressDialog nDialog;

// URL to get contacts JSON
private static String url = "http://charlenemacdonald.com/sloten.json";

// JSON Node names
private static final String TAG_SLOTEN = "slotenlijst";
private static final String TAG_SLOT = "Slot";


// contacts JSONArray
JSONArray sloten= null;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.fragment_sloten, container, false);

    slotenLijst = new ArrayList<HashMap<String, String>>();

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


    // Listview on item click listener
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

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


            // Starting single contact activity
            Intent in = new Intent(getActivity().getApplicationContext(),
                    SlotInfoScherm1.class);
            in.putExtra(TAG_SLOT, Slot);

            startActivity(in);

        }
    });

    return rootView;


    // Calling async task to get json


}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetSloten extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        nDialog = new ProgressDialog(getActivity());
        nDialog.setMessage("Even geduld a.u.b., studenten worden geladen...");
        nDialog.setCancelable(false);
        nDialog.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 {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                sloten = jsonObj.getJSONArray(TAG_SLOTEN);

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

                    String Slot = c.getString(TAG_SLOT);


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

                    // adding each child node to HashMap key => value
                    sloten.put(TAG_SLOT, Slot);


                    // adding contact to contact list
                    slotenLijst.add(sloten);
                }
            } 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 (nDialog.isShowing())
            nDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(getActivity(), slotenLijst,
                R.layout.sloten_info, new String[] { TAG_SLOT}, new int[] { R.id.textviewslotnaam});

        setListAdapter(adapter);


    }



}






    }

提前致谢!

2 个答案:

答案 0 :(得分:1)

onCreateView()方法中,替换

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

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

getView()返回之前无法调用onCreateView()方法,因为getView()实际上会返回View创建的onCreateView()

答案 1 :(得分:1)

在您刚刚充气的findViewById()上致电rootView,而不是活动。

您刚刚虚增的视图层次结构还不是活动视图层次结构的一部分。