Application force close in one cell phone when try

2019-08-28 16:38发布

Im trying to get an adress trough the gps, converting the coordinates to my location. I am using this code:

latitude1 = (location.getLatitude());
        longitude2= (location.getLongitude());

        JSONObject ret = getLocationInfo(); 
        JSONObject location2;
        String location_string;
        try {
            location2 = ret.getJSONArray("results").getJSONObject(0);
            location_string = location2.getString("formatted_address");
            Log.d("test", "formattted address:" + location_string);
            StringRua = (" " + location_string);
        } catch (JSONException e1) {
            e1.printStackTrace();

        }

and

public JSONObject getLocationInfo() 
{
        HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+latitude1+","+longitude2+"&sensor=true");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonObject;
}

It works fine in my celphone. But when my friend tries to use the same app when this part of the code is executed the app just force close.

Keep in mind that i already tried to use:

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude1, longitude2, 1);

But it was just too slow to execute this command and,in fact, it always returned null.

Can anyone help me? Thank You

EDIT: I just changed my code to use asynctask, but now i am not getting the location correctly, it just says null.

Here is what i did:

private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
    ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.show();
    }
    @Override
    protected Void doInBackground(Void... params) {

        //this method will be running on background thread so don't update UI frome here
        //do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here


        JSONObject ret = getLocationInfo(); 
        JSONObject location2;
        String location_string;
        try {
            location2 = ret.getJSONArray("results").getJSONObject(0);
            location_string = location2.getString("formatted_address");
            Log.d("test", "formattted address:" + location_string);
            StringRua = (" " + location_string);
        } catch (JSONException e1) {
            e1.printStackTrace();

        }

        return null;
    }

The async task calls, which is above the AsyncTask:

public JSONObject getLocationInfo() {

    HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+latitude1+","+longitude2+"&sensor=true");
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonObject;
}

And i am using, to call the Async :

  new AsyncCaller().execute();

The " StringRua = (" " + location_string); " is not getting any location

EDIT 2 : I've put the public JSONObject getLocationInfo() inside private class AsyncCaller extends AsyncTask {

I just find out that it doesnt get the location the first time that it calls asynctask, but the second time it works. But i need to make this work the first time it call asynctask. OBS: In my friends phone it doesnt crash anymore but he is always getting Null

1条回答
神经病院院长
2楼-- · 2019-08-28 17:28

The problem is as I guess network I/O on main ui, you need an AsyncTask to perform the network operations in main thread,

For more info about AsyncTasks

http://developer.android.com/reference/android/os/AsyncTask.html

and as of Android Honeycomb and above the application will crash with NetworkOnMainThreadException, but will work on earlier versions.

From the developer reference

This is only thrown for applications targeting the Honeycomb SDK or higher. 
Applications targeting earlier SDK versions are allowed to do networking on 
their main event loop threads, but it's heavily discouraged.

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

查看更多
登录 后发表回答