RuntimeException无法在未调用Looper.prepare()的线程内创建处理程序

时间:2017-03-28 12:02:35

标签: android multithreading android-broadcastreceiver

当我收到LocalBroadcast消息时,我试图发出一个截击请求。但是我得到了这个RuntimeException。我尝试使用线程,但仍然得到相同的错误。我应该用别的吗?我在方法prepareData()中获得了异常,这就是我在其中添加try / catch的原因。在这个try / catch我得到了例外。



public class NewItemsNearUFragment extends Fragment{

    private SharedPref pref;
    private ConnectionDetector cd;
    private ProgressDialog pd;
    private LocalBroadcastManager bManager;
    Activity activity;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        pref = new SharedPref(getActivity());
        cd = new ConnectionDetector(getActivity());
        pd = new ProgressDialog(getActivity());

        bManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("UPDATE_NOTIFY");
        bManager.registerReceiver(bReceiver, intentFilter);

    }


    @Override
    public void onDestroy() {
        LocalBroadcastManager.getInstance(activity).unregisterReceiver(bReceiver);
        super.onDestroy();
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof Activity){
            activity=(Activity) context;
        }

    }

    private BroadcastReceiver bReceiver = new BroadcastReceiver() {
    	@Override
        public void onReceive(Context context, Intent intent) {
            if(intent!=null){
                if(intent.getAction().equals("UPDATE_NOTIFY")) {
                    System.out.println("sammy_received_broadcast");
                    new Thread() {
                        public void run() {

                                try {
                                    activity.runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            

                                            prepareData();
                                        }
                                    });
                                    Thread.sleep(300);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                        }
                    }.start();


                }
            }

        }
    };


    private void prepareData(){

        try{

            pd.setMessage(activity.getString(R.string.plzwait));
            pd.show();

            if(arrayList!=null )arrayList.clear();

            if(TextUtils.isEmpty(pref.getString(Utility.HOME_LAT)))
                pref.setString(Utility.HOME_LAT, String.valueOf(GPSTracker.currLat));

            if(TextUtils.isEmpty(pref.getString(Utility.HOME_LANG)))
                pref.setString(Utility.HOME_LANG, String.valueOf(GPSTracker.currLong));

            if(TextUtils.isEmpty(pref.getString(Utility.HOME_PRICEORDER)))
                pref.setString(Utility.HOME_PRICEORDER, "");

            if(TextUtils.isEmpty(pref.getString(Utility.HOME_DATAORDER)))
                pref.setString(Utility.HOME_DATAORDER, "");

            if(TextUtils.isEmpty(pref.getString(Utility.HOME_PRODNAME)))
                pref.setString(Utility.HOME_PRODNAME, "");

            if(TextUtils.isEmpty(pref.getString(Utility.HOME_CATID)))
                pref.setString(Utility.HOME_CATID, "");

            if(TextUtils.isEmpty(pref.getString(Utility.HOME_STARTPRICE)))
                pref.setString(Utility.HOME_STARTPRICE, "");

            if(TextUtils.isEmpty(pref.getString(Utility.HOME_ENDPRICE)))
                pref.setString(Utility.HOME_ENDPRICE, "");


            StringRequest stringRequest = new StringRequest(Request.Method.POST, Utility.ALLPROD,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            pd.dismiss();
                            System.out.println("sammy_All_Prod_response "+response);

                            try {
                                JSONObject jObj = new JSONObject(response);
                                if(jObj.getInt("ACK")==1){
                                    JSONArray jsonArray = jObj.getJSONArray("all_products");
                                    for(int i=0;i<jsonArray.length();i++){
                                        JSONObject main = jsonArray.getJSONObject(i);

                                        Model home = new Model();
                                        home.setUserid(main.getString("user_id"));
                                        home.setTitle(main.getString("name"));
                                        String price = "$"+main.getString("price");
                                        home.setPrice(price);
                                        home.setImage(main.getString("image"));
                                        home.setPrdid(main.getString("product_id"));

                                        arrayList.add(home);

                                    }
                                }

                                adapter.notifyDataSetChanged();


                            } catch (JSONException e) {
                                // JSON error
                                e.printStackTrace();
                            }

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    pd.dismiss();
                    if (error instanceof TimeoutError) {
                        Toast.makeText(getActivity(),getString(R.string.tooslow),Toast.LENGTH_LONG).show();
                    }else if (error instanceof NoConnectionError){
                        Toast.makeText(getActivity(),getString(R.string.nointernet),Toast.LENGTH_LONG).show();
                    }else if (error instanceof AuthFailureError) {
                        System.out.println("sammy_AuthFailureError "+error);
                    } else if (error instanceof ServerError) {
                        System.out.println("sammy_ServerError "+error);
                    } else if (error instanceof NetworkError) {
                        System.out.println("sammy_NetworkError "+error);
                    } else if (error instanceof ParseError) {
                        System.out.println("sammy_ParseError "+error);
                    }
                }
            }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("user_id", pref.getString(Utility.USERID));
                    params.put("user_lat", pref.getString(Utility.HOME_LAT));
                    params.put("user_lang", pref.getString(Utility.HOME_LANG));
                    params.put("price_order", pref.getString(Utility.HOME_PRICEORDER));
                    params.put("data_order", pref.getString(Utility.HOME_DATAORDER));
                    params.put("product_name", pref.getString(Utility.HOME_PRODNAME));
                    params.put("categoryid", pref.getString(Utility.HOME_CATID));
                    params.put("start_price", pref.getString(Utility.HOME_STARTPRICE));
                    params.put("end_price", pref.getString(Utility.HOME_ENDPRICE));


                    System.out.println("sammy_All_Prod_params "+params);
                    return params;
                }

            };


            RequestQueue requestQueue = Volley.newRequestQueue(activity.getApplicationContext());
            //if(getActivity()!=null)
            requestQueue.add(stringRequest);
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                    10000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


        }catch(Exception e){
            System.out.println("sammy_prepareData_exception "+e);
        }


    }

}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

你的错误是你在线程中调用prepareData();

prepareData()函数中,您正在进行UI操作。显示ToastprogressDialog

Toast需要向用户界面显示活动,而threads则没有。

你应该使用UI线程:

 getActivity().runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(getActivity(), "Message", Toast.LENGTH_LONG).show();
    }
});