2016-10-28 5 views
-1

Java-Code sollte Quellcode von Facebook Graph API herunterladen, aber funktioniert nicht. Code-Ausgabe ist htmlCode = "" Dies ist Java-Code:url.openStream() funktioniert nicht auf Android

package cz.apps; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.TextView; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.*; 
import java.net.URL; 

public class MainActivity extends AppCompatActivity { 

    public String htmlCode = ""; 

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

    public void ziskatdata(){ 
     try { 
      URL url = new URL("https://graph.facebook.com/v2.8/****/events?access_token=****"); 
      BufferedInputStream bis = new BufferedInputStream(url.openStream()); 
      byte[] buffer = new byte[1024]; 
      StringBuilder sb = new StringBuilder(); 
      int bytesRead = 0; 
      while((bytesRead = bis.read(buffer)) > 0) { 
       String text = new String(buffer, 0, bytesRead); 
       sb.append(text); 
      } 
      bis.close(); 

     htmlCode = sb.toString(); 
     } catch (Exception e) { 
      //Data se nestáhla 
     } 

     if (htmlCode.equals("")){ 
      //Nezdařilo se vypsat události 
     } else { 
      try { 
       JSONObject json = new JSONObject(htmlCode); 
       JSONArray jarray = json.getJSONArray("data"); 
       for(int i = 0; i < jarray.length(); i++){ 
        JSONObject udalosti = jarray.getJSONObject(i); 
        String popis = udalosti.getString("description"); 
        String konec = udalosti.getString("end_time"); 
        String zacatek = udalosti.getString("start_time"); 
        String jmeno = udalosti.getString("name"); 

        JSONObject lokace = udalosti.getJSONObject("place").getJSONObject("location"); 
        String mesto = lokace.getString("city"); 
        String zeme = lokace.getString("country"); 
        String lat = lokace.getString("latitude"); 
        String lon = lokace.getString("longitude"); 
        final TextView textViewToChange = (TextView) findViewById(R.id.textprovypsani); 
        textViewToChange.setText(mesto); 
       } 
      } catch (JSONException e) { 
       //Něco je špatně 
      } 
     } 
    } 
} 

AndroidManifest:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="cz.app" > 
    <uses-permission android:name="android.permission.INTERNET" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme" > 
     <activity android:name=".MainActivity" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 
</manifest> 

catch (Exception e) { Log.e("MYAPP", "exception", e); } LogCat Ausgang:

E/MYAPP (21057): exception 
E/MYAPP (21057): android.os.NetworkOnMainThreadException 
+1

Sie fangen alle Ausnahmen ab und schalten sie aus. Versuchen Sie mindestens Logging sie .. –

Antwort

0

Sie haben diesen Code zu verwenden, nicht in mainUI Thread. So

new Thread(new Runnable() { 
    public void run() { 
     try { 
      ziskatdata(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
}).start(); 

und innerhalb Ihrer Methode Update alle UI-Ansicht mit diesem:

runOnUiThread(new Runnable() { 
    public void run() { 
     try { 
      textViewToChange.setText(mesto); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
}); 
+0

Dies funktioniert nicht. –

+0

@LukasPlevacDeveloper aktualisieren Sie Ihren Code: fügen Sie das Protokoll in 'catch (Ausnahme e) { Log.e (" MYAPP "," Ausnahme ", e); } ' – Vyacheslav

+0

Ich füge' catch (Ausnahme e) {Log.e ("MYAPP", "Ausnahme", e); } 'LogCat-Ausgabe zu meiner Frage. –

0

Der Fehler sagt, dass Sie versuchen, ein Netzanruf auf dem Hauptthread der Anwendung zu machen, was nicht der Fall ist zulässig. Sie müssen einen anderen Thread erstellen, um einen Netzwerkanruf zu tätigen. Sie können etwas tun wie:

new Thread() { 
    @Override 
    public void run() { 
     // do your work here 
    } 
}.start(); 

Aber Sie können nichts im Zusammenhang mit UI auf diesem Thread tun. Sie können auch eine Klasse wie AsyncTask verwenden:

new AsyncTask<Void, Void, String>() { 
    @Override 
    protected String doInBackground(Void... params) { 
     String response = whatEverMethodGetsMeNetworkCallResponse(); 

     return response; 
    } 

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

     // Do whatever you want to do with the network response 
    } 
}.execute(); 

Sie können sich wahrscheinlich eine Hilfsklasse verwenden Web-APIs zugreifen können, wie eine von mir:

es alle Komplikationen des Lesens und Schreibens Ströme handhaben wird, Sie können eine URL aufrufen und die Antwort als Zeichenfolge oder Stream abrufen, wenn Sie eine Binärdatei erwarten.

Verwandte Themen