Lukas Plevac Developer Lukas Plevac Developer - 1 month ago 26
Java Question

url.openStream() not working on android

Java code should download source code from facebook graph api, but is not working. Code output is

htmlCode = ""

This is java code:

package cz.www3.tech_apps.cinetube.cinetube;

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.www3.tech_apps.cinetube.cinetube" >
<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 output:

E/MYAPP (21057): exception
E/MYAPP (21057): android.os.NetworkOnMainThreadException
E/MYAPP (21057): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
E/MYAPP (21057): at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
E/MYAPP (21057): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
E/MYAPP (21057): at java.net.InetAddress.getAllByName(InetAddress.java:215)
E/MYAPP (21057): at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
E/MYAPP (21057): at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
E/MYAPP (21057): at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
E/MYAPP (21057): at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
E/MYAPP (21057): at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
E/MYAPP (21057): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
E/MYAPP (21057): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
E/MYAPP (21057): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
E/MYAPP (21057): at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
E/MYAPP (21057): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
E/MYAPP (21057): at java.net.URL.openStream(URL.java:470)
E/MYAPP (21057): at cz.www3.tech_apps.cinetube.cinetube.MainActivity.ziskatdata(MainActivity.java:31)
E/MYAPP (21057): at cz.www3.tech_apps.cinetube.cinetube.MainActivity.onCreate(MainActivity.java:25)
E/MYAPP (21057): at android.app.Activity.performCreate(Activity.java:5975)
E/MYAPP (21057): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
E/MYAPP (21057): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
E/MYAPP (21057): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2376)
E/MYAPP (21057): at android.app.ActivityThread.access$800(ActivityThread.java:147)
E/MYAPP (21057): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
E/MYAPP (21057): at android.os.Handler.dispatchMessage(Handler.java:102)
E/MYAPP (21057): at android.os.Looper.loop(Looper.java:135)
E/MYAPP (21057): at android.app.ActivityThread.main(ActivityThread.java:5253)
E/MYAPP (21057): at java.lang.reflect.Method.invoke(Native Method)
E/MYAPP (21057): at java.lang.reflect.Method.invoke(Method.java:372)
E/MYAPP (21057): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
E/MYAPP (21057): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Answer

You have to use this code not in mainUI Thread. So,

new Thread(new Runnable() {
                                        public void run() {
                                            try {
                                            ziskatdata();

                                            } catch (Exception e) {

                                            }
                                        }
                                    }).start();

and inside your method update all UI view using this:

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