Estoy implementando un ListView cargado con una base de Datos Externa, y estoy Obteniendo los datos con un JSON
Este proyecto lo tenia funcionando sin problemas en un Activity, pero al querer implementar el mismo en un fragment me marca estos errores:
Este es el Codigo que tengo en mi 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);
}
}
Me marca un error en esta linea:
la Linea 108 en donde da el error es: lv.setAdapter(adapter);
El LogCat es este:
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.