0

I'm trying to get location on android device the code is as follows:

private void openLocation() {
    lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Criteria c = new Criteria();
    pro = lm.getBestProvider(c,false);
    Location l = lm.getLastKnownLocation(pro);

    if (l != null) {
        Toast.makeText(WebActivity.this, "Longitude : "+String.valueOf(l.getLongitude())+", Latitude : "+String.valueOf(l.getLatitude()), Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(WebActivity.this,"loc object is null",Toast.LENGTH_LONG).show();
    }

    mgac = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

but it crashes when executed. What's wrong in the code, or please give me a working code that give me location to string and I want to send the data to another url using get/post request and this request should run in background.

David Passmore
  • 6,089
  • 4
  • 46
  • 70
  • if it crashes first see is it consoling some error/exception in console, if yes what is it? – Akhilesh Kumar May 31 '15 at 18:39
  • Use LogCat to examine the Java stack trace associated with your crash: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – CommonsWare May 31 '15 at 18:39

1 Answers1

0

This might help u,

Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

            try {

                URL url = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                // Starts the query

                conn.connect();
                InputStream stream = conn.getInputStream();

                String data = convertStreamToString(stream);

                // u can read data here
                stream.close();


            } catch (Exception e) {
            }
        }
    });

    thread.start();

& the convertStreamToString is,

static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

this can help you in sending the some request to server in background but for getting location I'm not very sure.

Akhilesh Kumar
  • 9,085
  • 13
  • 57
  • 95