【问题标题】:Volley Request Queue in Android Fragment (getApplicationContext may produce NullPointerException)Android Fragment 中的 Volley 请求队列(getApplicationContext 可能产生 NullPointerException)
【发布时间】:2019-08-05 03:14:16
【问题描述】:

我只想在片段中使用 recyclerview 从我的本地主机加载数据,但没有任何显示,它说getApplicationContext 可能会产生NullPointerException

错误出现在

Volley.newRequestQueue(getActivity().getApplicationContext()).add(stringRequest);

我尝试了主要活动的代码,它工作正常。

public class UpdateFragment extends Fragment {

private static final String URL = "http://192.168.1.32/CAGELCOII_APP/api.php";

RecyclerView recyclerView;
ItemAdapter adapter;

List<Item> itemList;

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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_update, container, false);

    itemList = new ArrayList<>();
    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    loadItem();

    adapter = new ItemAdapter(getActivity(), itemList);
    recyclerView.setAdapter(adapter);

    return view;
}

private void loadItem(){

    StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONArray products = new JSONArray(response);

                        for(int i =0; i < products.length(); i++){
                            JSONObject productObject = products.getJSONObject(i);

                            int id = productObject.getInt("id");
                            String description = productObject.getString("description");
                            String agency = productObject.getString("agency");
                            String date = productObject.getString("date");
                            String time = productObject.getString("time");
                            String image = productObject.getString("image");

                            Item item = new Item(id, description, agency, date, time, image);
                            itemList.add(item);
                        }

                        adapter = new ItemAdapter(getActivity(), itemList);
                        recyclerView.setAdapter(adapter);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

    Volley.newRequestQueue(getActivity().getApplicationContext()).add(stringRequest);

}

}

【问题讨论】:

  • 非常感谢任何帮助。谢谢
  • 使用这个Volley.newRequestQueue(getActivity()).add(stringRequest);
  • @AndroidGeek 我已经尝试过了,结果是“参数 getActivity 可能为空”。谢谢
  • 好的,请试试 Appcontroller 类

标签: java android android-recyclerview fragment


【解决方案1】:

在调用getActivity() 时,您必须确保您的片段isAdded() 为活动,否则您将获得NullPointerException,因为getActivity() 返回托管该片段的活动。

如果您总是想使用应用程序上下文,由于它的生命周期不会消亡,您可以使用这个静态函数在整个应用程序中检索它:

App.java

public class App extends Application {
    private static Context sAppContext;

    public void onCreate() {
        super.onCreate();
        sAppContext = this;
    }

    public static Context getContext() {
        return sAppContext;
    }
}

AndroidManifest.xml

...
    <application
        android:name=".App"
        ...>
    </application>

你可以在你的代码中使用它:

Volley.newRequestQueue(App.getContext()).add(stringRequest);

【讨论】:

    【解决方案2】:

    请试试这个代码

    RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
           mRequestQueue.add(jsonObjReq);
    

    截击请求有两种方式:

    第一 使用应用控制器类

    AppController

        public class AppController extends Application {
    
     public static final String TAG = AppController.class.getSimpleName();
    
     private RequestQueue mRequestQueue;
     private ImageLoader mImageLoader;
    
     private static AppController mInstance;
    
     @Override
     public void onCreate() {
     super.onCreate();
     mInstance = this;
     }
    
    public static synchronized AppController getInstance() {
     return mInstance;
     }
    
    public RequestQueue getRequestQueue() {
     if (mRequestQueue == null) {
     mRequestQueue = Volley.newRequestQueue(getApplicationContext());
     }
    
    return mRequestQueue;
     }
    
    public ImageLoader getImageLoader() {
     getRequestQueue();
     if (mImageLoader == null) {
     mImageLoader = new ImageLoader(this.mRequestQueue,
     new ImageClass());
     }
     return this.mImageLoader;
     }
    
    public  void addToRequestQueue(Request req, String tag) {
     // set the default tag if tag is empty
     req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
     getRequestQueue().add(req);
     }
    
    public  void addToRequestQueue(Request req) {
     req.setTag(TAG);
     getRequestQueue().add(req);
     }
    
    public void cancelPendingRequests(Object tag) {
     if (mRequestQueue != null) {
     mRequestQueue.cancelAll(tag);
     }
     }
     }
    

    **ImageClass **

        public class ImageClass extends LruCache<String, Bitmap> implements
                ImageCache {
            public static int getDefaultLruCacheSize() {
                final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
                final int cacheSize = maxMemory / 8;
    
                return cacheSize;
            }
    
            public ImageClass() {
                this(getDefaultLruCacheSize());
            }
    
            public ImageClass(int sizeInKiloBytes) {
                super(sizeInKiloBytes);
            }
    
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight() / 1024;
            }
    
            @Override
            public Bitmap getBitmap(String url) {
                return get(url);
            }
    
            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                put(url, bitmap);
            }
        }
    

    清单

        <application
         android:allowBackup="true"
         android:name=".AppController"
         android:icon="@mipmap/ic_launcher"
         android:label="@string/app_name"
         android:roundIcon="@mipmap/ic_launcher_round"
         android:supportsRtl="true"
         android:theme="@style/AppTheme">
    

    android:name=".AppController" 添加清单

    MainActivity

       String url = Global.BASE_URL + "api/";
        StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
    
    
                        Log.e(TAG, response.toString());
                    }
                }, new com.android.volley.Response.ErrorListener() {
    
            @Override
            public void onErrorResponse(VolleyError error) {
                //Error Log
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        }) {
    
            @Override
            protected Map<String, String> getParams() {
                //Pass the parameters to according to the API.
                Map<String, String> params = new HashMap<String, String>();
                params.put("API_HASH", "hasKey");
                Log.e(TAG, "splash paramsTest----" + params);
    
                return params;
            }
        };
      /*  ----Adding request to request queue----*/
        AppController.getInstance().addToRequestQueue(jsonObjReq, 
        GlobalString.cancel_login_api);
    

    第二

    RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
            mRequestQueue.add(jsonObjReq);
    

    【讨论】:

      猜你喜欢
      • 2016-09-19
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      相关资源
      最近更新 更多