2016-10-28 3 views
-1

자바 코드는 facebook graph api에서 소스 코드를 다운로드해야하지만 작동하지 않습니다. 코드 출력은 htmlCode = "" 이 자바 코드 :url.openStream() 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); } 로그 캣 출력 :

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

모든 예외를 포착하고 있습니다. 적어도 로깅을 시도하십시오 .. –

답변

0

당신은하지 mainUI 스레드에서이 코드를 사용합니다. 그래서,

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

과 방법 업데이트 내부

모든 UI보기이를 사용하여 :

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

이것이 작동하지 않습니다. –

+0

@LukasPlevacDeveloper가 코드를 업데이트합니다 : catch (예외 e) 내부에 로그를 추가하십시오 { Log.e ("MYAPP", "exception", e); }' – Vyacheslav

+0

'catch (Exception e) {Log.e ("MYAPP", "exception", e);를 추가합니다. }'내 질문에 LogCat 출력. –

0
오류가 당신이하지 않은 응용 프로그램의 주 스레드에서 네트워크 호출을 만들려고 노력하는 것을 말한다

허용. 네트워크 통화를하려면 다른 스레드를 생성해야합니다. 다음과 같이 할 수 있습니다.

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

그러나 해당 스레드의 UI와 관련된 작업은 할 수 없습니다. 내 일처럼, 웹 API에 액세스 할 수

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(); 

당신은 아마 헬퍼 클래스를 사용할 수 있습니다 : : 또한 AsyncTask 같은 클래스를 사용할 수 있습니다

그것은 읽기와 쓰기 스트림의 모든 합병증을 처리합니다

, 바이너리 파일을 원한다면 URL을 호출하고 응답을 문자열 또는 스트림으로 얻을 수 있습니다.

관련 문제