0

I am trying to run an asynchronous task after getting gps coordinates from my map routine in an Android MainActivity. The asynchronous task is to do an httpurlconnection to get data from my server based on the gps coordinates. However, the asynchronous task GetRestaurant() never gets called while observing in my debug process. I should mention while in debugger the looper routine is called over and over. In debug I noticed that the program executes the GetRestaurant instruction but after that nothing happens. The class is never reached. The map does get displayed and that's about it. Can anyone tell from the code below as to why my asynchronous task class GetRestaurant never gets executed?

locationManager.requestLocationUpdates(provider, 3600, 1000, new LocationListener() {

        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}


        public void onLocationChanged(Location loc) {
            if(loc != null) {
                lat = (float) (loc.getLatitude());
                lng = (float) (loc.getLongitude());

                String latLongString = "Lat:" + lat + "\nLong:" + lng;
                myLocationText.setText("Your current position is:\n" + latLongString);
                int latit = (int) (loc.getLatitude() * 1E6);
                int longit = (int) (loc.getLongitude() * 1E6);
                point = new GeoPoint(latit, longit);
                mapController.animateTo(point);
                mapController.setCenter(point);
                mapController.setZoom(15);
                String addr=getAddress(point);
                TextView addressView = (TextView) findViewById(R.id.address_view);
                addressView.setText(addr);
                MyOverlay mapOverlay = new MyOverlay();
                List<Overlay> overlayList=mapView.getOverlays();
                overlayList.clear();
                overlayList.add(mapOverlay);

                new GetRestaurant().execute();

            }

        }
    });

}

 class GetRestaurant extends AsyncTask<Void, Void, String[]> {
 @Override
    protected String[] doInBackground(Void...parameters ) {
        // TODO Auto-generated method stub

        String thislat = ((String.valueOf(lat)));
        String thislng = ((String.valueOf(lng)));
        String[] result = null;
        URL url;


         try {

            String query = "lat=" + thislat + "&lng=" + thislng + "&uid=&vegkey=1";
            url = new URL("http://10.0.2.2:8000/xxxxxxx/webservice/frontpage1.php?" + query);
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            int responseCode = httpConnection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) {
                InputStream in = httpConnection.getInputStream();
                BufferedReader br = new BufferedReader(
                    new InputStreamReader(in));

                StringBuilder sb = new StringBuilder();

                String line;
                int x=0;
                while ((line = br.readLine()) != null) {
                  //     sb.(line);
                    result[x] = line;
                    x++;
                } 

            }


        }

        catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
            System.out.println(e.toString());
        }


    return result;
    }

    protected void onProgressUpdate(Integer... progress) {

    }
    @Override
    protected void onPostExecute(String[] result) {

        restaurants = result;
        final ArrayAdapter<String> arrayAdpt = new ArrayAdapter<String>(null, android.R.layout.simple_list_item_1, restaurants);
        restaurant_list.setAdapter(arrayAdpt);
        mapView.postInvalidate();

    }



  }

Here is my errorlog: I noticed this error: "Can't create handler inside thread that has not called Looper.prepare()." That sounds suspicious.

 03-08 23:53:27.846: E/AndroidRuntime(570): FATAL EXCEPTION: AsyncTask #1
 03-08 23:53:27.846: E/AndroidRuntime(570): java.lang.RuntimeException: An error occured while executing doInBackground()
 03-08 23:53:27.846: E/AndroidRuntime(570):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
 03-08 23:53:27.846: E/AndroidRuntime(570):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
 03-08 23:53:27.846: E/AndroidRuntime(570):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at java.lang.Thread.run(Thread.java:856)
  03-08 23:53:27.846: E/AndroidRuntime(570): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
  03-08 23:53:27.846: E/AndroidRuntime(570):    at android.os.Handler.<init>(Handler.java:197)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at android.os.Handler.<init>(Handler.java:111)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at android.widget.Toast$TN.<init>(Toast.java:324)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at android.widget.Toast.<init>(Toast.java:91)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at android.widget.Toast.makeText(Toast.java:238)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at com.example.herb4.MainActivity$GetRestaurant.doInBackground(MainActivity.java:159)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at com.example.herb4.MainActivity$GetRestaurant.doInBackground(MainActivity.java:1)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
  03-08 23:53:27.846: E/AndroidRuntime(570):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
  03-08 23:53:27.846: E/AndroidRuntime(570):    ... 4 more

Ok. I changed the code to read 'return (String[]) result.toArray() at the end of doInBackground. Now I get the following error: '03-09 03:24:18.796: E/AndroidRuntime(4726): Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]'. I think the error occurred in onPostExecute which has the following code"

  @Override
    protected void onPostExecute(String[] result) {

    //  restaurants = result;
        final ArrayAdapter<String> arrayAdpt = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, result);
        restaurant_list.setAdapter(arrayAdpt);
        mapView.postInvalidate();

    }

This would be a lot easier if I could follow the program in the debugger but it quits before I get to the problem area.

Dave
  • 873
  • 2
  • 15
  • 27
  • In debugger you have to lookup different threads most likely. Did you setup some logging to check out of the background task is being executed at all? Do you run the location determination task on the UI thread? – Sergey Benner Mar 08 '13 at 23:05
  • What do you mean "the looper routine is called over and over"? My guess would be that your LocationListener isn't instanced properly (and thus not receiving Location Updates) but that part of the question makes me think maybe there's a different issue. – DigCamara Mar 08 '13 at 23:05
  • do try to use `Log.e` in your `doInBackground` to check that the doInBackground is called or not ? – Shoshi Mar 08 '13 at 23:08
  • What is your API version? – Serkan Arıkuşu Mar 08 '13 at 23:15
  • Do you have the permissions in your manifest?( ) Is onLocationChanged ever called? – DigCamara Mar 08 '13 at 23:18
  • 1
    Are you running it in emulator or on a device if on emulator did you enable the GPS support on it? – Sergey Benner Mar 08 '13 at 23:23
  • I put in a log.e and no message came back but I did get a message saying 'Unfortunately, Herb4 has stopped' which I only get when running without debug. When I run in debug mode the map is displayed and then nothing happens. Very confusing. – Dave Mar 08 '13 at 23:26
  • I am running in emulator mode and I do use the Google APIs as the target. I am able to display a map so I would think the I have GPS support. – Dave Mar 08 '13 at 23:28
  • your log should show you why it crashed - the exception should be in your logcat. – Sergey Benner Mar 08 '13 at 23:28
  • I have these permissions LocationChanged is called as I push a gps coordinate using DDMS. It displays a map so LocationChanged is called. I followed the logic in the debugger. It just stops after it executes new GetRestaurant().execute(); – Dave Mar 08 '13 at 23:33
  • AVD manager - > Hardware -> New -> Select GPS or hw.gps=yes did you do that? also http://stackoverflow.com/questions/2279647/how-to-emulate-gps-location-in-the-android-emulator – Sergey Benner Mar 08 '13 at 23:33
  • My error log says 'Couldn't get connection factory client'. Then it says it has an error in doInbackground. Then it says 'Choreographer - Skipped 120 frames! The application may be doing too much work on its main thread.' Then it says 'thread exiting with uncaught exception (group=0x4a71030)'. I guess I don't know what all this means. – Dave Mar 08 '13 at 23:40
  • What is exact error in doInbackground()? – Sergey Benner Mar 08 '13 at 23:54

1 Answers1

0

Look at this answer. It explains the error that is appearing in your logcat. If you want to have a clear vision of your error, get rid of the Toast; your System.out output will show up in the logcat.


PROBLEM: In doInBackground you have

 String[] result = null;

which you're using in your loop, without initialization. I guess your actuall error is a Null Variable Exception on your

result[x]=line;

line.

Expanding the solution. I hope you can spot where you need to change this:

 String line;
 List<String> result = new ArrayList<String>();
 int x=0;
 while ((line = br.readLine()) != null) {
 //     sb.(line);
     result.add(line);

 } 
 return (String[])(result.toArray());
Community
  • 1
  • 1
DigCamara
  • 5,540
  • 4
  • 36
  • 47
  • I tried your suggestion on running it on the UI and I still do not get to the doInBackground method. – Dave Mar 08 '13 at 23:54
  • I am running on this API verison: android:targetSdkVersion="17" /> – Dave Mar 08 '13 at 23:57
  • I can't get rid of the try/catch loop as it gives me all kinds of errors if I do. – Dave Mar 09 '13 at 00:09
  • I will be back in 1 hour and will respond to further comments. – Dave Mar 09 '13 at 00:11
  • I get an error if I used Array result = newArray(); How can I initialize result before I know how big its going to be? – Dave Mar 09 '13 at 02:20
  • I tried your changes but I get an error on return result.toArray(). It says I cannot change from Object[] to String[]. As you can tell I am still struggling to make the conversion from C# to Java. – Dave Mar 09 '13 at 03:20
  • Yeah. You need to add a cast to String[]. I'll change my answer. – DigCamara Mar 09 '13 at 03:21
  • I ran it again and the error is a NullPointerException in onPostExecute which has the following command:final ArrayAdapter arrayAdpt = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, result); The only thing that could be null in the getApplicationContext(). What do I replace that with? – Dave Mar 09 '13 at 04:17
  • I finally figured it out. I left out this line: ListView restaurant_list = (ListView) findViewById(R.id.restaurant_list); before this line. restaurant_list.setAdapter(arrayAdpt); It is very hard to figure out what's going on when you can't run a debugger in an asyntask. Thanks to everyone who helped me through this mess. – Dave Mar 09 '13 at 05:30