android url always return empty string

so here is my code, and i’ve tried the getContent on the basic java and it works fine. but here it doesn’t at all. the content of the url i load is always empty. i’ve also added the permission.INTERNET to the manifest. i’m new to android

@Override
protected void onCreate(Bundle savedInstanceState) {
    String lines="";
    try {
        lines=getContent("http://detik.com");
    }catch (Exception e) {e.printStackTrace();}
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage(lines);

    alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(MainActivity.this, "You clicked yes button", Toast.LENGTH_LONG).show();
        }
    });

    alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }
    });

    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public static String getContent(String url) {
    String pageContent="";
    try
    {
        URL pageLink=new URL(url);
        BufferedReader in=new BufferedReader(new InputStreamReader(pageLink.openStream()));

        String line=in.readLine();
        while (line!=null)
        {
            pageContent=pageContent+line;
            line=in.readLine();
        }
        in.close();
    } catch (Exception e) {e.printStackTrace();}
    return "content of "+url+" : "+pageContent;
}

and this is my manifest

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

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</manifest>


Source: android

Leave a Reply