0

Ich bin mit Facebook GraphAPI und ich versuche Ergebnisse nächste Seite zu laden mit GraphRequest.executeAndWait() wie demonstriert here, aber die App Erste stürzt ab und gibt android.os.NetworkOnMainThreadException.‚android.os.NetworkOnMainThreadException‘ während der Durchführung GraphRequest.executeAndWait() in doInBackground() von AsyncTask

Hier ist mein Code:

class RetrieveF extends AsyncTask<Void, Integer, String> { 

      GraphRequest request; 

      protected String doInBackground(Void...args0) { 
       new GraphRequest(
         AccessToken.getCurrentAccessToken(), "/me/friends", null, HttpMethod.GET, 
         new GraphRequest.Callback() { 
          public void onCompleted(GraphResponse response) { 
           JSONObject innerJson = response.getJSONObject(); 
           try { 
            JSONArray data = innerJson.getJSONArray("data"); 
            for (int i = 0; i<data.length(); i++){ 

             String id = data.getJSONObject(i).getString("id"); 

             request = new GraphRequest(AccessToken.getCurrentAccessToken(), id+"/feed", null, HttpMethod.GET, 
               new GraphRequest.Callback() { 
                @Override 
                public void onCompleted(GraphResponse response) { 

                 JSONObject innerJson = response.getJSONObject(); 
                 try { 
                  JSONArray data = innerJson.getJSONArray("data"); 
                  for (int i = 0; i<data.length(); i++) { 
                   JSONObject obj = data.getJSONObject(i);} 
                 } catch (JSONException e) { 
                  Log.d("innerFacebookException", e.getMessage()); 
                 } 

                 GraphRequest nextResultsRequests = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT); 
                 if (nextResultsRequests != null) { 
                  nextResultsRequests.setCallback(request.getCallback()); 
                  // error on this line 
                  response = nextResultsRequests.executeAndWait(); 
                  // 
                 } 
                } 
               } 
             ); 
             request.executeAsync(); 
            } 
           } catch (JSONException e) { 
            Log.d("facebookException", e.getMessage()); 
           } 
          } 
         } 
       ).executeAsync(); 
       return "success"; 
      } 

      @Override 
      protected void onPostExecute(String s) { 
       super.onPostExecute(s); 
      } 
     } 

Hier ist der Stacktrace:

android.os.NetworkOnMainThreadException 
                     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273) 
                     at com.android.org.conscrypt.OpenSSLSocketImpl.shutdownAndFreeSslNative(OpenSSLSocketImpl.java:1131) 
                     at com.android.org.conscrypt.OpenSSLSocketImpl.close(OpenSSLSocketImpl.java:1126) 
                     at com.android.okhttp.Connection.closeIfOwnedBy(Connection.java:132) 
                     at com.android.okhttp.OkHttpClient$1.closeIfOwnedBy(OkHttpClient.java:75) 
                     at com.android.okhttp.internal.http.HttpConnection.closeIfOwnedBy(HttpConnection.java:137) 
                     at com.android.okhttp.internal.http.HttpTransport.disconnect(HttpTransport.java:135) 
                     at com.android.okhttp.internal.http.HttpEngine.disconnect(HttpEngine.java:578) 
                     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.disconnect(HttpURLConnectionImpl.java:122) 
                     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.disconnect(DelegatingHttpsURLConnection.java:93) 
                     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.disconnect(HttpsURLConnectionImpl.java) 
                     at com.facebook.internal.Utility.disconnectQuietly(Utility.java:416) 
                     at com.facebook.GraphRequest.executeConnectionAndWait(GraphRequest.java:1272) 
                     at com.facebook.GraphRequest.executeBatchAndWait(GraphRequest.java:1168) 
                     at com.facebook.GraphRequest.executeBatchAndWait(GraphRequest.java:1134) 
                     at com.facebook.GraphRequest.executeBatchAndWait(GraphRequest.java:1118) 
                     at com.facebook.GraphRequest.executeAndWait(GraphRequest.java:1093) 
                     at com.facebook.GraphRequest.executeAndWait(GraphRequest.java:987) 
                     at com.qbc.xxx.MainActivity$RetrieveFacebookPosts$1$1.onCompleted(MainActivity.java:398) 
                     at com.facebook.GraphRequest$5.run(GraphRequest.java:1383) 
                     at android.os.Handler.handleCallback(Handler.java:739) 
                     at android.os.Handler.dispatchMessage(Handler.java:95) 
                     at android.os.Looper.loop(Looper.java:148) 
                     at android.app.ActivityThread.main(ActivityThread.java:5417) 
                     at java.lang.reflect.Method.invoke(Native Method) 
                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)    

ich nicht in der Lage bin, um herauszufinden, was diesen Fehler verursacht als solche Fehler in der Regel verursacht werden, wenn diese Art von Code nicht ist in AsyncTask behandelt, aber das ist hier nicht der Fall.

Bitte lassen Sie mich wissen, was diesen Fehler verursacht und wie man ihn los wird.

+0

Bitte die Ausnahme Stacktrace Post auch. – laalto

+0

@laalto Bitte beachten Sie die aktualisierte Frage –

+0

Der innerste 'onCompleted()' Callback läuft auf dem Hauptthread, und Sie führen dort ein 'executeAndWait()' aus. –

Antwort

0

Nach ein paar Google-Suchen bekam ich die Lösung.

Ich wickelte gerade die GraphRequest.executeAndWait() Code in einem Thread wie folgt aus:

Thread t = new Thread() { 
    @Override 
    public void run() { 
     GraphRequest nextResultsRequests = lastGraphResponse.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT); 
     if (nextResultsRequests != null) { 
      nextResultsRequests.setCallback(request.getCallback()); 
      lastGraphResponse = nextResultsRequests.executeAndWait(); 
     } 
    } 
}; 
t.start(); 
1

public void onCompleted() wird auf dem UI-Thread ausgeführt, unabhängig davon, welcher Thread diese Anforderung aufgerufen hat. Wenn Sie also eine weitere Anfrage innerhalb von public void onCompleted() ausführen möchten, müssen Sie sie in einen anderen AsyncTask oder einen anderen asynchronen Mechanismus einbinden.

+0

Ok! Also, wenn ich noch eine 'AsyncTask' schreiben würde. Ich müsste "Anfrage" als Parameter übergeben. Wie kann ich das mit AsyncTask machen? –

1

Dies ist nicht der richtige Ansatz

Thread t = new Thread() { 
@Override 
public void run() { 
    GraphRequest nextResultsRequests = lastGraphResponse.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT); 
    if (nextResultsRequests != null) { 
     nextResultsRequests.setCallback(request.getCallback()); 
     lastGraphResponse = nextResultsRequests.executeAndWait(); 
    } 
} 

} .start();

Sie tun das, indem Sie einen neuen Thread erstellen. Alle Netzwerkoperationen sollten im Hintergrund Thread durchgeführt werden, der bereits existiert, nicht durch Erstellen eines neuen Threads.

Die Möglichkeit, dies zu tun, wird unter Verwendung eines Handlers Objekt den Code auf Hauptthread auszuführen.

Handler handler = new Handler(); 
    handler.post(new Runnable() { 
     @Override 
     public void run() { 
      GraphRequest nextResultsRequests = lastGraphResponse.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT); 
      if (nextResultsRequests != null) { 
       nextResultsRequests.setCallback(request.getCallback()); 
       lastGraphResponse = nextResultsRequests.executeAndWait(); 
      } 
     } 
    }); 

Oder Sie können nach einer gewissen Verzögerung die Operation tun, durch die Verwendung postDelayed

handler.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      GraphRequest nextResultsRequests = lastGraphResponse.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT); 
      if (nextResultsRequests != null) { 
       nextResultsRequests.setCallback(request.getCallback()); 
       lastGraphResponse = nextResultsRequests.executeAndWait(); 
      } 
     } 
    }, DELAY_IN MILLISECONDS); 
Verwandte Themen