KickAss
KickAss

Reputation: 4280

Android Java reading Google Search JSON

I have found this (http://code.google.com/apis/imagesearch/v1/jsondevguide.html#json_snippets_java), I have included that in a new project like so and want to know how I can get the results from the JSONObject. I tried to do a search but did not find anything that I could use to help me (I am a newbie - self-teaching Java).

package com.googlesearch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

public static String searchstring = "big bang theory";
public static URLConnection connection;
public static URL url;
public static BufferedReader reader;
public static JSONObject json;

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

    try {
        url = new URL("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + searchstring);
    } catch (MalformedURLException e) {
    }

    try {
        connection = url.openConnection();
    } catch (IOException e) {
    }
    connection.addRequestProperty("Referer", "www.google.co.uk");
    String line;
    StringBuilder builder = new StringBuilder();

    try {
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    } catch (IOException e1) {
    }
    try {
        while((line = reader.readLine()) != null) {
            builder.append(line);
        }
    } catch (IOException e) {
    }

    try {
        json = new JSONObject(builder.toString());
    } catch (JSONException e) {
    }
}
}

LogCat:

04-08 19:59:33.019: E/AndroidRuntime(4965): FATAL EXCEPTION: main
04-08 19:59:33.019: E/AndroidRuntime(4965): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bigbangtheorywallpapers/com.bigbangtheorywallpapers.MainActivity}: android.os.NetworkOnMainThreadException
04-08 19:59:33.019: E/AndroidRuntime(4965):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at android.app.ActivityThread.access$600(ActivityThread.java:140)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at android.os.Looper.loop(Looper.java:137)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at android.app.ActivityThread.main(ActivityThread.java:4898)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at java.lang.reflect.Method.invokeNative(Native Method)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at java.lang.reflect.Method.invoke(Method.java:511)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at dalvik.system.NativeStart.main(Native Method)
04-08 19:59:33.019: E/AndroidRuntime(4965): Caused by: android.os.NetworkOnMainThreadException
04-08 19:59:33.019: E/AndroidRuntime(4965):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at com.bigbangtheorywallpapers.MainActivity.onCreate(MainActivity.java:43)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at android.app.Activity.performCreate(Activity.java:5206)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
04-08 19:59:33.019: E/AndroidRuntime(4965):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
04-08 19:59:33.019: E/AndroidRuntime(4965):     ... 11 more

Upvotes: 0

Views: 552

Answers (1)

Paresh Mayani
Paresh Mayani

Reputation: 128428

As per the comment:

I tried to test the code just now as it is above, but the app crashes on start.

=> As you making web API call directly on main UI Thread, it's giving android.os.NetworkOnMainThreadException actually.

To resolve this issues, there are two solutions:

  1. Standard way => Implement AsyncTask
  2. Lazy solution => Include below lines before making a call:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);

And yes, Don't forget to add this to AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>

Upvotes: 1

Related Questions