Android Volley Null Pointer Exception

Estoy intentando convertir un tutorial previamente basado en actividad en un fragmento, pero sigo corriendo en el error NullPointerException en mi adaptador.

El tutorial se basa en esto y he adelgazado el constructor para el adaptador porque solía llamar a una actividad.

Hay una solución posible aquí, pero nadie sabe cómo proceder con la misma pregunta posible.

Quiero convertir todo a un Fragmento de trabajo. Por favor, hágamelo saber si necesita más información de mí.

Clase convertida principal:

public class mainViewController2 extends Fragment { private static final String TAG = mainViewController2.class.getSimpleName(); private ListView listView; private FeedListAdapter listAdapter; private List<FeedItem> feedItems; private String URL_FEED = "http://api.androidhive.info/feed/feed.json"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.mainviewcontroller2_fragment, container, false); listView = (ListView) v.findViewById(R.id.list); feedItems = new ArrayList<FeedItem>(); //where the error shows up? listAdapter = new FeedListAdapter(feedItems); listView.setAdapter(listAdapter); // We first check for cached request Cache cache = AppController.getInstance().getRequestQueue().getCache(); Entry entry = cache.get(URL_FEED); if (entry != null) { // fetch the data from cache try { String data = new String(entry.data, "UTF-8"); try { parseJsonFeed(new JSONObject(data)); } catch (JSONException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { // making fresh volley request and getting json JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET, URL_FEED, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { VolleyLog.d(TAG, "Response: " + response.toString()); if (response != null) { parseJsonFeed(response); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); } }); // Adding request to volley request queue AppController.getInstance().addToRequestQueue(jsonReq); } return v; } /** * Parsing json reponse and passing the data to feed view list adapter * */ private void parseJsonFeed(JSONObject response) { try { JSONArray feedArray = response.getJSONArray("feed"); for (int i = 0; i < feedArray.length(); i++) { JSONObject feedObj = (JSONObject) feedArray.get(i); FeedItem item = new FeedItem(); item.setId(feedObj.getInt("id")); item.setName(feedObj.getString("name")); // Image might be null sometimes String image = feedObj.isNull("image") ? null : feedObj .getString("image"); item.setImge(image); item.setStatus(feedObj.getString("status")); item.setProfilePic(feedObj.getString("profilePic")); item.setTimeStamp(feedObj.getString("timeStamp")); // url might be null sometimes String feedUrl = feedObj.isNull("url") ? null : feedObj .getString("url"); item.setUrl(feedUrl); feedItems.add(item); } // notify data changes to list adapater listAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } } 

FeedListAdapter:

  public class FeedListAdapter extends BaseAdapter { private Activity activity; private LayoutInflater inflater; private List<FeedItem> feedItems; Context context; ImageLoader imageLoader; public FeedListAdapter(Context ctx,List<FeedItem> feedItems) { this.context= ctx; this.feedItems = feedItems; imageLoader = AppController.getInstance().getImageLoader(); inflater = LayoutInflater.from(context); } @Override public int getCount() { return feedItems.size(); } @Override public Object getItem(int location) { return feedItems.get(location); } @Override public long getItemId(int position) { return position; } @SuppressLint("InflateParams") @Override public View getView(int position, View convertView, ViewGroup parent) { if (inflater == null) inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (convertView == null) convertView = inflater.inflate(R.layout.feed_item, null); if (imageLoader == null) imageLoader = AppController.getInstance().getImageLoader(); TextView name = (TextView) convertView.findViewById(R.id.name); TextView timestamp = (TextView) convertView .findViewById(R.id.timestamp); TextView statusMsg = (TextView) convertView .findViewById(R.id.txtStatusMsg); TextView url = (TextView) convertView.findViewById(R.id.txtUrl); NetworkImageView profilePic = (NetworkImageView) convertView .findViewById(R.id.profilePic); FeedImageView feedImageView = (FeedImageView) convertView .findViewById(R.id.feedImage1); FeedItem item = feedItems.get(position); name.setText(item.getName()); // Converting timestamp into x ago format CharSequence timeAgo = DateUtils.getRelativeTimeSpanString( Long.parseLong(item.getTimeStamp()), System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS); timestamp.setText(timeAgo); // Chcek for empty status message if (!TextUtils.isEmpty(item.getStatus())) { statusMsg.setText(item.getStatus()); statusMsg.setVisibility(View.VISIBLE); } else { // status is empty, remove from view statusMsg.setVisibility(View.GONE); } // Checking for null feed url if (item.getUrl() != null) { url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">" + item.getUrl() + "</a> ")); // Making url clickable url.setMovementMethod(LinkMovementMethod.getInstance()); url.setVisibility(View.VISIBLE); } else { // url is null, remove from the view url.setVisibility(View.GONE); } // user profile pic profilePic.setImageUrl(item.getProfilePic(), imageLoader); // Feed image if (item.getImge() != null) { feedImageView.setImageUrl(item.getImge(), imageLoader); feedImageView.setVisibility(View.VISIBLE); feedImageView .setResponseObserver(new FeedImageView.ResponseObserver() { @Override public void onError() { } @Override public void onSuccess() { } }); } else { feedImageView.setVisibility(View.GONE); } return convertView; } } 

Errores de LogCat:

 09-06 02:51:55.823: E/AndroidRuntime(8279): FATAL EXCEPTION: main 09-06 02:51:55.823: E/AndroidRuntime(8279): Process: com.rynovation.kline, PID: 8279 09-06 02:51:55.823: E/AndroidRuntime(8279): java.lang.NullPointerException 09-06 02:51:55.823: E/AndroidRuntime(8279): at androidFeedClasses.FeedListAdapter.<init>(FeedListAdapter.java:35) 09-06 02:51:55.823: E/AndroidRuntime(8279): at com.rynovation.kline.mainViewController2.onCreateView(mainViewController2.java:51) 09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.Fragment.performCreateView(Fragment.java:1700) 09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890) 09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062) 09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.BackStackRecord.run(BackStackRecord.java:684) 09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1453) 09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443) 09-06 02:51:55.823: E/AndroidRuntime(8279): at android.os.Handler.handleCallback(Handler.java:733) 09-06 02:51:55.823: E/AndroidRuntime(8279): at android.os.Handler.dispatchMessage(Handler.java:95) 09-06 02:51:55.823: E/AndroidRuntime(8279): at android.os.Looper.loop(Looper.java:146) 09-06 02:51:55.823: E/AndroidRuntime(8279): at android.app.ActivityThread.main(ActivityThread.java:5487) 09-06 02:51:55.823: E/AndroidRuntime(8279): at java.lang.reflect.Method.invokeNative(Native Method) 09-06 02:51:55.823: E/AndroidRuntime(8279): at java.lang.reflect.Method.invoke(Method.java:515) 09-06 02:51:55.823: E/AndroidRuntime(8279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 09-06 02:51:55.823: E/AndroidRuntime(8279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 09-06 02:51:55.823: E/AndroidRuntime(8279): at dalvik.system.NativeStart.main(Native Method) 

Supongo que te perdiste un código simple en tu archivo de manifiesto. Su paquete AppController amplía la Application , por lo que la etiqueta de aplicación en su manifiesto está buscando el AppController pero no puede encontrarlo.

Simplemente escriba este código simple en su AndroidManifest.xml

android:name = your.package.AppController

Un poco tarde quizás, pero una respuesta representativa a la respuesta de user3902144:

Respuesta similar a esta pregunta: Link

Usted puede haber perdido esto desde su manifiesto:

  <application android:name="<package-name>.app.AppController" // <-- this one android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> 

Es por eso que onCreate nunca ha llamado y mInstance es null.

Espero que esto ayude 🙂

Viendo el error, parece que estás llamando a getActivity() dentro de onCreateView() . Debería estar recibiendo la actividad en onActivityCreated en lugar donde no debería ser null.

Cambiar esto de

 listView = (ListView) getActivity().findViewById(R.id.list); 

a

 listView = (ListView)v.findViewById(R.id.list); 

Esto se debe a que getActivity() se utiliza generalmente como un Context en Fragmento. Mientras you'r encontrar id para sus elementos de UI en Fragmento, entonces usted tiene que dar referencia de su objeto View's que se devolverá en el método onCreateView() .

Actualizar:

Cambie su adaptador como,

 listAdapter = new FeedListAdapter(getActivity(),feedItems); 

Ahora en su Constructor

  ImageLoader imageLoader; public FeedListAdapter(Context ctx,List<FeedItem> feedItems) { this.context= ctx; this.feedItems = feedItems; imageLoader = AppController.getInstance().getImageLoader() } 

Ahora en su clase adaptadora use la variable de context como Context .

Por favor, compruebe todos sus parámetros con cuidado, asegúrese de no enviar ningún valor nulo en los parámetros, si se utilizan algunos valores almacenados a continuación, utilice la condición como a continuación:

 @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); if(paramValue!= null) params.put("paramKey", paramValue); else params.put("paramKey", "anyOtherDefaultValue"); return params; } 
  • Android - La llamada requiere el nivel 9 de API (el min actual es 8): android.os.StrictMode # setThreadPolicy
  • Gson - convierta de Json a una clase ArrayList <T>
  • JSON elemento de verificación Java es un JSONArray o JSONObject
  • Enviar solicitud de correo utilizando Volley y recibir en PHP
  • Dibujo de rutas de conducción con waypoints en android (Google Maps, api dirección de Google, json parsing, decodificar google polyline)
  • Org.json.JSONObject no se puede convertir en JSONArray
  • ¿Cómo analizar json array con múltiples objetos por gson?
  • Cómo analizar JSON analizado para uso sin conexión
  • Org.json.JSONArray no se puede convertir en JSONObject (Populating spinner from webservice)
  • No se puede analizar JSonArray en Android
  • ¿Cómo realizar pruebas sin conexión para aplicaciones que dependen de JSON?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.