Search code examples
androidsdkintellij-ideaurlconnectionandroid-4.2-jelly-bean

URLConnection Android 4.2 doesn't work


Please help me. There is a simple application that displays by clicking the button in TextView code html page. I try to run on android 2.3 ... works. But on android 4.2 with pressing the error takes off "Unfortunately,name_app has stopped".

MainActivity.java

    public class MainActivity extends Activity {
    TextView txtview;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        txtview = (TextView) findViewById(R.id.txtview);

    }
    public void OnClickBtn (View v) {
        URL url = null;
        try {
            url = new URL("http://ya.ru/");
            URLConnection con1 = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(con1.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null){
                txtview.append(line);
            }
        } catch (Exception e){

        }
    }
}

Manifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.test">
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="17" android:maxSdkVersion="17"/>
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

Maybe it's in the android sdk. I am writing another application where you want to query on the internet. On Android 2.3 running, but does not work on 4.2.


Solution

  • In 3.0+ you can't run HTTP requests on the main thread- you must do it in an AsyncTask or Thread, otherwise it throws an exception.