ListView.setAdapter "null Object Reference"

1

I'm implementing a ListView loaded with an External database, and I'm getting the data with a JSON

This project had it running smoothly in an Activity, but wanting to implement it in a fragment marks me these errors:

This is the Code that I have in my Fragment

FragmentNuevas.java

public class FragmentNuevas extends Fragment {

private OnFragmentInteractionListener mListener;
ArrayList<Product> arrayList;
ListView lv;
ProgressDialog pdialog = null;
Context context = null;

public FragmentNuevas() {
    // Required empty public constructor
}


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

    lv = (ListView) getActivity().findViewById(R.id.listView);
    arrayList = new ArrayList<>();
    context = getActivity();

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            pdialog = ProgressDialog.show(context, "", "Buscando Noticias...", true);
            new ReadJSON().execute("http://lahuerta.gob.mx/WebService/consulta.php");
        }
    });

    /*lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            Product selectedProduct = arrayList.get(position);

            Intent intent = new Intent(getActivity().getApplicationContext(), Nuevas.class);
            intent.putExtra("nombre", selectedProduct.getName());
            intent.putExtra("fecha", selectedProduct.getFecha());
            intent.putExtra("contenido", selectedProduct.getPrice());
            intent.putExtra("extra1", selectedProduct.getImage());
            startActivity(intent);
        }
    });*/

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_fragment_nuevas, container, false);
}

class ReadJSON extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... params) {
        return readURL(params[0]);
    }
    @Override
    protected void onPostExecute(String content) {

        pdialog.dismiss();
        try {
            JSONArray jsonarray = new JSONArray(content);
            for(int i =0;i<jsonarray.length(); i++){
                JSONObject productObject = jsonarray.getJSONObject(i);
                arrayList.add(new Product(
                        productObject.getString("nombre"),
                        productObject.getString("contenido"),
                        productObject.getString("extra1"),
                        productObject.getString("fecha")

                ));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        CustomListAdapter adapter = new CustomListAdapter(
                getActivity(), R.layout.custom_list_layout, arrayList
        );
        lv.setAdapter(adapter); /*Aqui me da Error*/
    }
}

private static String readURL(String theUrl) {
    StringBuilder content = new StringBuilder();
    try {
        // create a url object
        URL url = new URL(theUrl);
        // create a urlconnection object
        URLConnection urlConnection = url.openConnection();
        // wrap the urlconnection in a bufferedreader
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        // read from the urlconnection via the bufferedreader
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return content.toString();
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

I mark an error in this line:

Line 108 where the error is given is: lv.setAdapter(adapter);

The LogCat is this:

  

E / AndroidRuntime: FATAL EXCEPTION: main                     Process: mx.gob.lahuerta.oficiadepartes, PID: 18201                     java.lang.NullPointerException: Attempt to invoke virtual method 'void   android.widget.ListView.setAdapter (android.widget.ListAdapter) 'on a   null object reference

                  at mx.gob.lahuerta.oficiadepartes.FragmentNuevas$ReadJSON.onPostExecute(FragmentNuevas.java:108)
                  at mx.gob.lahuerta.oficiadepartes.FragmentNuevas$ReadJSON.onPostExecute(FragmentNuevas.java:81)
                  at android.os.AsyncTask.finish(AsyncTask.java:667)
                  at android.os.AsyncTask.-wrap1(AsyncTask.java)
                  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
     

Application terminated.

    
asked by Sharly Infinitywars 14.12.2016 в 03:05
source

2 answers

1

Add the context, in this case that of the Activity so that you can execute the methods, for example to obtain the context:

context = getActivity();   //this;

To run runOnUiThread() :

getActivity().runOnUiThread()....

When converting your Activity to Fragment , the Fragment is related to the Activity that contains it, therefore:

To get the context within Fragment you do it using the getActivity() method.

    
answered by 14.12.2016 / 03:27
source
1

Regarding the error

  

android.widget.ListView.setAdapter (android.widget.ListAdapter) 'on a   null object reference

This is because it does not find the reference of ListView in the container layout, it actually finds inside the layout that the Fragment loads, in this case fragment_fragment_nuevas.xml makes this change:

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

    lv = (ListView)view.findViewById(R.id.listView);
    arrayList = new ArrayList<>();
    context = getActivity();

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            pdialog = ProgressDialog.show(context, "", "Buscando Noticias...", true);
            new ReadJSON().execute("http://lahuerta.gob.mx/WebService/consulta.php");
        }
    });


    // Inflate the layout for this fragment
    return view; 
}
    
answered by 14.12.2016 в 11:24