Pregunta

I'm trying to take the first image of a google search programmatically, to put it into my android application. i've found an example that was made for me(here: https://developers.google.com/image-search/v1/jsondevguide?hl=it#using_json) but i have problems before the unusual part(the part using json)... this is my code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WebView webview = new WebView(this);
    setContentView(webview);
    String s = "ciao";

try {
        URL strana = new URL("https://ajax.googleapis.com/ajax/services/search/images?"
        + "v=1.0&q=barack%20obama&userip=INSERT-USER-IP");
        HttpURLConnection urlConnection = (HttpURLConnection) strana
                .openConnection();
        urlConnection.setDoOutput(true);
        String line;
        StringBuilder builder = new StringBuilder();
        InputStreamReader isr = new InputStreamReader(
                urlConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        JSONObject json = new JSONObject(builder.toString());
        s = json.getJSONObject("responseData").getJSONArray("results")
                .getJSONObject(0).getString("url");
    } catch (Exception ex) {
        ex.printStackTrace();
    }


    webview.getSettings().setJavaScriptEnabled(true);
    String summary = "<html><body>You scored <b>192</b> points." + s
            + "<div></div></body></html>";
    webview.loadData(summary, "text/html", null);

}

I have a problem with the line "urlConnection.getInputStream()" that is the last line processed by the application before catching the exception, but i can't understand why. I tried using URLConnection instead HttpURLConnection (as it was done in the references i linked before), but nothing changed. I also add the line "urlConnection.setDoOutput(true);" hoping in some changes, but nothing. I have add to the manifest the line

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

so that's not the problem.Here is the logcat:

06-25 09:31:05.840: W/IInputConnectionWrapper(850): showStatusIcon on inactive InputConnection
06-25 09:31:13.975: I/webclipboard(1340): clipservice: android.sec.clipboard.ClipboardExManager@41f2e1c8
06-25 09:31:14.030: D/ApplicationPackageManager(1340): Inside getCSCPackageItemIcon
06-25 09:31:14.040: V/webkit(1340): BrowserFrame constructor: this=Handler (android.webkit.BrowserFrame) {41f288a8}
06-25 09:31:14.080: W/System.err(1340): android.os.NetworkOnMainThreadException
06-25 09:31:14.080: W/System.err(1340):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
06-25 09:31:14.080: W/System.err(1340):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
06-25 09:31:14.080: W/System.err(1340):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
06-25 09:31:14.080: W/System.err(1340):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
06-25 09:31:14.080: W/System.err(1340):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
06-25 09:31:14.080: W/System.err(1340):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
06-25 09:31:14.080: W/System.err(1340):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
06-25 09:31:14.080: W/System.err(1340):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
06-25 09:31:14.080: W/System.err(1340):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
06-25 09:31:14.080: W/System.err(1340):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
06-25 09:31:14.080: W/System.err(1340):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
06-25 09:31:14.080: W/System.err(1340):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
06-25 09:31:14.080: W/System.err(1340):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
06-25 09:31:14.080: W/System.err(1340):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
06-25 09:31:14.085: W/System.err(1340):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
06-25 09:31:14.085: W/System.err(1340):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
06-25 09:31:14.085: W/System.err(1340):     at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
06-25 09:31:14.085: W/System.err(1340):     at myapp.test.imgseeker.MainActivity.onCreate(MainActivity.java:45)
06-25 09:31:14.085: W/System.err(1340):     at android.app.Activity.performCreate(Activity.java:5206)
06-25 09:31:14.085: W/System.err(1340):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
06-25 09:31:14.085: W/System.err(1340):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
06-25 09:31:14.085: W/System.err(1340):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
06-25 09:31:14.085: W/System.err(1340):     at android.app.ActivityThread.access$700(ActivityThread.java:140)
06-25 09:31:14.085: W/System.err(1340):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
06-25 09:31:14.085: W/System.err(1340):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-25 09:31:14.085: W/System.err(1340):     at android.os.Looper.loop(Looper.java:137)
06-25 09:31:14.085: W/System.err(1340):     at android.app.ActivityThread.main(ActivityThread.java:4921)
06-25 09:31:14.085: W/System.err(1340):     at java.lang.reflect.Method.invokeNative(Native Method)
06-25 09:31:14.085: W/System.err(1340):     at java.lang.reflect.Method.invoke(Method.java:511)
06-25 09:31:14.085: W/System.err(1340):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
06-25 09:31:14.085: W/System.err(1340):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
06-25 09:31:14.085: W/System.err(1340):     at dalvik.system.NativeStart.main(Native Method)
06-25 09:31:14.105: D/WebView(1340): loadUrlImpl: called
06-25 09:31:14.110: D/webcore(1340):  CORE loadUrl: called
06-25 09:31:14.110: D/webkit(1340): Firewall not null
06-25 09:31:14.110: D/webkit(1340): euler: isUrlBlocked = false
06-25 09:31:14.160: I/GATE(1340): <GATE-M>DEV_ACTION_COMPLETED</GATE-M>
06-25 09:31:14.190: D/libEGL(1340): loaded /system/lib/egl/libEGL_mali.so
06-25 09:31:14.195: D/libEGL(1340): loaded /system/lib/egl/libGLESv1_CM_mali.so
06-25 09:31:14.205: D/libEGL(1340): loaded /system/lib/egl/libGLESv2_mali.so
06-25 09:31:14.210: D/(1340): Device driver API match
06-25 09:31:14.210: D/(1340): Device driver API version: 10
06-25 09:31:14.210: D/(1340): User space API version: 10 
06-25 09:31:14.210: D/(1340): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Thu Oct 25 08:43:05 KST 2012 
06-25 09:31:14.250: D/dalvikvm(1340): GC_CONCURRENT freed 250K, 14% free 9538K/11015K, paused 16ms+2ms, total 38ms
06-25 09:31:14.260: D/OpenGLRenderer(1340): Enabling debug mode 0
06-25 09:31:14.265: D/WebView(1340): onSizeChanged - w:480 h:690
06-25 09:31:14.390: D/TilesManager(1340): new EGLContext from framework: 514be150 
06-25 09:31:14.390: D/GLWebViewState(1340): Reinit shader
06-25 09:31:14.430: D/GLWebViewState(1340): Reinit transferQueue
¿Fue útil?

Solución

The exception thrown is NetworkOnMainThreadException. This is to prevent developers to put their network code in the UI thread, which can freeze the UI as it will block until the request is completed.

If you want to do a network request, you should use an AsyncTask so your UI thread can continue to run. Here is an example : Download a file with Android, and showing the progress in a ProgressDialog

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top