在doInBackground()中调用位置坐标时出错

时间:2017-10-24 09:51:14

标签: android android-asynctask gps

我正在尝试使用AsyncTask方法将数据发送到服务器。

我正在获取所有其他设备信息和用户详细信息。

但是,当我尝试在location coordinates的{​​{1}}内获取try catch时, 我收到以下错误:

  

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

非常感谢任何帮助。

代码如下:

这是我的课程,其中应用了 doInBackground ..

AsyncTask

这是我的位置等级..

 @Override
    public void onClick(View view) {
       if (fieldsValidation().equals("ok")) {
                    if (Check_Internet_Con.isConnectingToInternet(getActivity())) { 
                        new PostSignOnDuty().execute(); 
                    } else {
                        Toast.makeText(getActivity(), "Please check your Internet Connection", Toast.LENGTH_LONG).show();
                    }
                } else {
                    errorMsg.showErrorMsg(getActivity(), view, fieldsValidation());
                }
    }

    private class PostSignOnDuty extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Submitting Details..");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... arg0) {
            dutyId = sharedPreference.getDutyTypeId();
            userId = sharedPreference.getUserId();
            deviceId = simAndDeviceId.getDeviceId();
            stnCode = selectStn.getText().toString();
            signOnComments = edtPurpose.getText().toString();
            btnSignOn.setClickable(false);
            btnSignOn.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark));
            try {
                if (coordinates.getLocation() != null) {
                    latitute = coordinates.getLocation().getLatitude();
                    longitute = coordinates.getLocation().getLongitude();
                    Get_Address get_address = new Get_Address(getActivity(), latitute, longitute);
                    city = get_address.getCity();
                    state = get_address.getState();
                    area = get_address.getArea();
                    completeAddress = get_address.getCompleteAddress();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            String Url_Sign_On_Duty = getResources().getString(R.string.Url_Sign_On_Duty);

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("userid", String.valueOf(userId)));
            params.add(new BasicNameValuePair("longitude", String.valueOf(longitude)));
            params.add(new BasicNameValuePair("latitude", String.valueOf(latitude)));
            params.add(new BasicNameValuePair("deviceid", deviceId));
            params.add(new BasicNameValuePair("stationcode", stnCode));
            params.add(new BasicNameValuePair("DutyId", String.valueOf(dutyId)));
            params.add(new BasicNameValuePair("RouteTypeId", "0"));
            params.add(new BasicNameValuePair("Area", area));
            params.add(new BasicNameValuePair("City", city));
            params.add(new BasicNameValuePair("State", state));
            params.add(new BasicNameValuePair("Address", completeAddress));
            params.add(new BasicNameValuePair("Comment", signOnComments));
            ServiceHandler jsonParser = new ServiceHandler();
            String json = jsonParser.makeGetServiceCall(Url_Sign_On_Duty, ServiceHandler.POST, params);
            return json;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (pDialog.isShowing())
                pDialog.dismiss();

            loginStatusTime = Integer.parseInt(result);
            sharedPreference.setLoginstatusid(loginStatusTime);
            sharedPreference.setActiveUserId(1);
            if (loginStatusTime > 0) {
                try {
                    if (coordinates.getLocation() != null) {
                        coordinates.getLocation();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
                /*getActivity().startService(new Intent(getActivity(), GPS_Service.class));
                getActivity().startService(new Intent(getActivity(), Send_Records_Service.class));*/
                Toast.makeText(getActivity(), "You have Signed on at " + stnCode + " at " + getSignOnTime() + " hours", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(getActivity(), SignOfDuty.class);
                startActivity(intent);
            } else {
                Log.e("JSON Data", "Didn't receive any data from server!");
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

您无法通过 UI Thread 方法对 doInBackground() 执行操作。因为 Android UI工具包不是 thread-safe 。因此,您不应该从工作线程

操纵 UI

<强> From Documentation

使用

runOnUiThread(new Runnable() {
     public void run() {
        // some code #3 (Write your code here to run in UI thread)

       }
});

doInBackground 应为 - :,

@Override
        protected String doInBackground(String... arg0) {

            runOnUiThread(new Runnable() {
                public void run() {                        
                dutyId = sharedPreference.getDutyTypeId();
                userId = sharedPreference.getUserId();
                deviceId = simAndDeviceId.getDeviceId();
                stnCode = selectStn.getText().toString();
                signOnComments = edtPurpose.getText().toString();
                btnSignOn.setClickable(false);


        btnSignOn.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark));
        try {
            if (coordinates.getLocation() != null) {
                latitute = coordinates.getLocation().getLatitude();
                longitute = coordinates.getLocation().getLongitude();
                Get_Address get_address = new Get_Address(getActivity(), latitute, longitute);
                city = get_address.getCity();
                state = get_address.getState();
                area = get_address.getArea();
                completeAddress = get_address.getCompleteAddress();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
 }
            });
        String Url_Sign_On_Duty = getResources().getString(R.string.Url_Sign_On_Duty);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("userid", String.valueOf(userId)));
        params.add(new BasicNameValuePair("longitude", String.valueOf(longitude)));
        params.add(new BasicNameValuePair("latitude", String.valueOf(latitude)));
        params.add(new BasicNameValuePair("deviceid", deviceId));
        params.add(new BasicNameValuePair("stationcode", stnCode));
        params.add(new BasicNameValuePair("DutyId", String.valueOf(dutyId)));
        params.add(new BasicNameValuePair("RouteTypeId", "0"));
        params.add(new BasicNameValuePair("Area", area));
        params.add(new BasicNameValuePair("City", city));
        params.add(new BasicNameValuePair("State", state));
        params.add(new BasicNameValuePair("Address", completeAddress));
        params.add(new BasicNameValuePair("Comment", signOnComments));
        ServiceHandler jsonParser = new ServiceHandler();
        String json = jsonParser.makeGetServiceCall(Url_Sign_On_Duty, ServiceHandler.POST, params);
        return json;
    }

修改

我不确定,但这可能会对你有所帮助

 if (isGPSEnabled) {
                mLocationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, SIXTY_SECONDS,
                        0, this,Looper.getMainLooper());

答案 1 :(得分:0)

您不得禁用button doInBackground()方法。 onPreExecute()就是为了它。停用button onPreExecute()并再次启用onPostExecute(),网络上的所有教程都建议您这样做,同时您也会在这些方法中设置progressBar以其他方式设置按钮时doInBackground()

你的问题与此无关。这是关于Thread没有Looper并尝试发送消息或postRunnable没有Looper。您正在请求Thread of AsyncTask中的更新。相反,您应该在UI线程上请求它,但不是每次请求位置更新时都不在方法内。听众或回调必须注册onResume()和未注册的onPause()方法。