我面临 Volley 超时错误和 mainThread 错误

我正在尝试使用 Volley 库获取数据以在 Andriod 应用程序中形成服务器。当我请求获取数据时我的数据太大但问题是凌空超时错误我也使用了RetryPolicy但问题是一样的。我该如何解决?


我已经尝试过 RetryPolicy 和 AsynTask,但我的问题无法解决。谁能告诉我如何解决这个问题?//主要功能在这里...


protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_search_member);


        initiateViews();

        searchViewCategory();



    }


//initiateViews function...

    private void initiateViews() {

        recyclerView = findViewById(R.id.search_category_recyle_view);

        mSearchView = findViewById(R.id.searchView);

        addMember = findViewById(R.id.addMember);

        requestQueue = Volley.newRequestQueue(this);

    }


    private void searchViewCategory() {

        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override

            public boolean onQueryTextSubmit(String query) {


                getData();

                return false;

            }


            @Override

            public boolean onQueryTextChange(String newText) {

                return false;

            }

        });

    }

//Get Data from Server function

public void getData()

{

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "http://alfahd.witorbit.net/api.php?search_member=a&array=1", new Response.Listener<JSONObject>() {

        @Override

        public void onResponse(JSONObjectresponse)

        {

            Toast.makeText(SearchMember.this, "" + response, Toast.LENGTH_SHORT).show();

        }

    }, new Response.ErrorListener() {

        @Override

        public void onErrorResponse(VolleyError error)

        {

            error.printStackTrace();

            dialog.dismiss();

            Toast.makeText(SearchMember.this, "Error", Toast.LENGTH_SHORT).show();

        }

    });

    request.setRetryPolicy(new DefaultRetryPolicy(

            MY_SOCKET_TIMEOUT_MS,

            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,

            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    requestQueue.add(request);


}




守候你守候我
浏览 124回答 1
1回答

交互式爱情

因此,首先强烈建议使用 Volley Singleton 模式来充分利用它。我的 volley 单例类是这样的。/**&nbsp;* Created by MuhammadFaisal on 8/10/2017.&nbsp;*/public class VolleySingleton {private static final int MAX = 2 * 1024 * 1024;private static int MAX_SERIAL_THREAD_POOL_SIZE = 10;private static VolleySingleton mSingletonInstance = null;private final int MAX_CACHE_SIZE = 2 * 1024 * 1024; //2 MBContext context = null;private ImageLoader imageLoader;private RequestQueue volleyRequestQueue;private VolleySingleton(Context c){&nbsp; &nbsp; RequestQueue serialRequestQueue = prepareSerialRequestQueue(c);&nbsp; &nbsp; serialRequestQueue.start();&nbsp; &nbsp; context = c;&nbsp; &nbsp; volleyRequestQueue = Volley.newRequestQueue(c);&nbsp; &nbsp; imageLoader = new ImageLoader(volleyRequestQueue, new ImageLoader.ImageCache() {&nbsp; &nbsp; &nbsp; &nbsp; private LruCache<String, Bitmap> mCache = new LruCache<>((int) (Runtime.getRuntime().maxMemory() / 1024 / 8));&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public Bitmap getBitmap(String url)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return mCache.get(url);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void putBitmap(String url, Bitmap bitmap)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mCache.put(url, bitmap);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });}public static VolleySingleton getInstance(Context context){&nbsp; &nbsp; if (mSingletonInstance == null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; mSingletonInstance = new VolleySingleton(context);&nbsp; &nbsp; }&nbsp; &nbsp; return mSingletonInstance;}public static RequestQueue prepareSerialRequestQueue(Context context){&nbsp; &nbsp; Cache cache = new DiskBasedCache(context.getCacheDir(), MAX);&nbsp; &nbsp; Network network = getNetwork();&nbsp; &nbsp; RequestQueue requestQueue;&nbsp; &nbsp; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; && Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (checkGooglePlayServices(context))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ProviderInstaller.installIfNeeded(context);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (GooglePlayServicesRepairableException e)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Indicates that Google Play services is out of date, disabled, etc.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Prompt the user to install/update/enable Google Play services.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; GooglePlayServicesUtil.showErrorNotification(e.getConnectionStatusCode(), context);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Notify the SyncManager that a soft error occurred.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //syncResult.stats.numIOExceptions++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (GooglePlayServicesNotAvailableException e)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Indicates a non-recoverable error; the ProviderInstaller is not able&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // to install an up-to-date Provider.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Notify the SyncManager that a hard error occurred.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //GooglePlayServicesUtil.showErrorNotification(e.getConnectionStatusCode(), context);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //syncResult.stats.numAuthExceptions++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; HttpStack stack = null;&nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stack = new HurlStack(null, new TLSSocketFactory());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (KeyManagementException e)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("Your Wrapper Class", "Could not create new stack for TLS v1.2");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stack = new HurlStack();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (NoSuchAlgorithmException e)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("Your Wrapper Class", "Could not create new stack for TLS v1.2");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stack = new HurlStack();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; requestQueue = Volley.newRequestQueue(context, stack);&nbsp; &nbsp; &nbsp; &nbsp; return requestQueue;&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; return new RequestQueue(cache, network, MAX_SERIAL_THREAD_POOL_SIZE);}private static Network getNetwork(){&nbsp; &nbsp; HttpStack stack;&nbsp; &nbsp; String userAgent = "volley/0";&nbsp; &nbsp; if (Build.VERSION.SDK_INT >= 9)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; stack = new HurlStack();&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; stack = null;&nbsp; &nbsp; &nbsp; &nbsp; //stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));&nbsp; &nbsp; }&nbsp; &nbsp; return new BasicNetwork(stack);}private static boolean checkGooglePlayServices(Context con){&nbsp; &nbsp; switch (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(con))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; case ConnectionResult.SERVICE_MISSING:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("googleError: ", Integer.toString(ConnectionResult.SERVICE_MISSING));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //GoogleApiAvailability.getInstance().getErrorDialog(SplashScreen.this,ConnectionResult.SERVICE_MISSING,0).show();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("googleError: ", Integer.toString(ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //GoogleApiAvailability.getInstance().getErrorDialog(this,ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED,0).show();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case ConnectionResult.SERVICE_DISABLED:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("googleError: ", Integer.toString(ConnectionResult.SERVICE_DISABLED));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //GoogleApiAvailability.getInstance().getErrorDialog(this,ConnectionResult.SERVICE_DISABLED,0).show();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; return true;}public RequestQueue getVolleyRequestQueue(){&nbsp; &nbsp; if (volleyRequestQueue == null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // getApplicationContext() is key, it keeps you from leaking the&nbsp; &nbsp; &nbsp; &nbsp; // Activity or BroadcastReceiver if someone passes one in.&nbsp; &nbsp; &nbsp; &nbsp; volleyRequestQueue = Volley.newRequestQueue(context.getApplicationContext());&nbsp; &nbsp; }&nbsp; &nbsp; return volleyRequestQueue;}public ImageLoader getImageLoader(){&nbsp; &nbsp; return imageLoader;}}使用单例方法有很多好处,其中一个主要好处是它为您提供了一个请求队列来执行所有网络请求。现在,像这样初始化你的 requestQueue:private RequestQueue requestQueue;if (requestQueue == null)&nbsp; &nbsp; &nbsp; &nbsp; requestQueue = VolleySingleton.getInstance(context).getVolleyRequestQueue();您现在可以开始像这样进行网络调用,只是为了让您知道我使用相同的方法调用您的端点并成功获得响应。JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://alfahd.witorbit.net/api.php?search_member=a&array=1", new Response.Listener<JSONObject>() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onResponse(JSONObject response)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; volleyCallBack.onSuccess(response.toString());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }, new Response.ErrorListener() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onErrorResponse(VolleyError error)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JSONObject jsonObject;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NetworkResponse networkResponse = error.networkResponse;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (networkResponse != null && networkResponse.data != null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String jsonError = new String(networkResponse.data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(jsonError.contains("500"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; createErrorDialog("Something went wrong. Try Later!","");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; volleyCallBack.onFailure(error);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp;//&nbsp; &nbsp; &nbsp; &nbsp; {//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public byte[] getBody()//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return jsonObject.toString().getBytes();//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }////&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public Map<String, String> getHeaders()//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Map<String, String> params = new HashMap<String, String>();//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; params.put("Authorization", "Bearer " + jwt);//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; params.put("Content-Type", "application/json");//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return params;//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }//&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 0,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DefaultRetryPolicy.DEFAULT_MAX_RETRIES,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));&nbsp; &nbsp; requestQueue.add(jsonObjectRequest);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java