Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android connecting to json/xml api

I'm trying to communicate with a rest api to retrieve a JSON document, but when I run the application in the Eclipse Android emulator the app closes as soon as it starts ("Unfortunately TestRest has stopped"). It seems to close due to the call to the httpClient.execute method.

The code for the main activity is below:

public class TestRestActivity extends Activity {
    /** Called when the activity is first created. */
    TextView info;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        info = (TextView) findViewById(R.id.debug);

        String testUri = "http://www.entireweb.com/xmlquery?pz=MYAPIKEY&ip=IP&q=pizza&n=50&format=json";
        // print the uri to the screen - (not seen if rest of code runs)
        info.setText(testUri);

        HttpClient httpclient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpget = new HttpGet(testUri);


        HttpResponse response = null;
        try {
            // TODO fails on this line
            response = httpclient.execute(httpget, localContext);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                info.setText("got it");
            }

        } catch (ClientProtocolException e) {
            // Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // Auto-generated catch block
            e.printStackTrace();
        } finally {
        }

    }
}

Also I've included the web permissions in my manifest file as below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.john.testRes"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-permission android:name="android.permission.INTERNET" />

Not too familiar with android development and really clueless as to what's causing the problem. The api I'm using is fine and returns the expected json document from my browser. The AVD I'm using can connect to the internet in its browser and I've tried the app on a few different AVDs.

Any suggestions as to what's causing the problem? Thanks.

Edit: added errors

11-22 18:13:14.221: D/AndroidRuntime(556): Shutting down VM
11-22 18:13:14.221: W/dalvikvm(556): threadid=1: thread exiting with uncaught exception (group=0x409951f8)
11-22 18:13:14.251: E/AndroidRuntime(556): FATAL EXCEPTION: main
11-22 18:13:14.251: E/AndroidRuntime(556): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.john.testRes/org.john.testRes.TestRestActivity}: android.os.NetworkOnMainThreadException
11-22 18:13:14.251: E/AndroidRuntime(556):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
11-22 18:13:14.251: E/AndroidRuntime(556):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
11-22 18:13:14.251: E/AndroidRuntime(556):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
11-22 18:13:14.251: E/AndroidRuntime(556):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
11-22 18:13:14.251: E/AndroidRuntime(556):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-22 18:13:14.251: E/AndroidRuntime(556):  at android.os.Looper.loop(Looper.java:137)
11-22 18:13:14.251: E/AndroidRuntime(556):  at android.app.ActivityThread.main(ActivityThread.java:4340)
11-22 18:13:14.251: E/AndroidRuntime(556):  at java.lang.reflect.Method.invokeNative(Native Method)
11-22 18:13:14.251: E/AndroidRuntime(556):  at java.lang.reflect.Method.invoke(Method.java:511)
11-22 18:13:14.251: E/AndroidRuntime(556):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-22 18:13:14.251: E/AndroidRuntime(556):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-22 18:13:14.251: E/AndroidRuntime(556):  at dalvik.system.NativeStart.main(Native Method)
11-22 18:13:14.251: E/AndroidRuntime(556): Caused by: android.os.NetworkOnMainThreadException
11-22 18:13:14.251: E/AndroidRuntime(556):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
11-22 18:13:14.251: E/AndroidRuntime(556):  at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
11-22 18:13:14.251: E/AndroidRuntime(556):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
11-22 18:13:14.251: E/AndroidRuntime(556):  at java.net.InetAddress.getAllByName(InetAddress.java:220)
11-22 18:13:14.251: E/AndroidRuntime(556):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-22 18:13:14.251: E/AndroidRuntime(556):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-22 18:13:14.251: E/AndroidRuntime(556):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-22 18:13:14.251: E/AndroidRuntime(556):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-22 18:13:14.251: E/AndroidRuntime(556):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-22 18:13:14.251: E/AndroidRuntime(556):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-22 18:13:14.251: E/AndroidRuntime(556):  at org.john.testRes.TestRestActivity.onCreate(TestRestActivity.java:41)
11-22 18:13:14.251: E/AndroidRuntime(556):  at android.app.Activity.performCreate(Activity.java:4465)
11-22 18:13:14.251: E/AndroidRuntime(556):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-22 18:13:14.251: E/AndroidRuntime(556):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
11-22 18:13:14.251: E/AndroidRuntime(556):  ... 11 more
11-22 18:13:48.321: I/Process(556): Sending signal. PID: 556 SIG: 9
11-22 18:14:01.552: D/AndroidRuntime(597): Shutting down VM
like image 531
not_john Avatar asked Nov 22 '11 16:11

not_john


1 Answers

The problem is that you are trying to do network operations on the main UI thread. You need to do these on a separate thread. You can use a AsyncTask or just a standard Thread.

Here is a simple example:

final Handler handler = new Handler();
new Thread(new Runnable() {

     @Override
     public void run() {
          // Do something long running
          handler.post(new Runnable() {

               @Override
               public void run() {
                    // Do something on the UI Thread
               }
          });
     }
}).start();
like image 78
HandlerExploit Avatar answered Oct 26 '22 14:10

HandlerExploit