Francis Francis - 1 month ago 6
Android Question

Trying to launch a url using asynctask - android

I am trying to launch a url in android using asynctask, the code shows no error but when I launch the application instead of the url displaying, it displays "hello world" to the screen. Below is my attempt:

//Starting the task. Pass an url as the parameter.
new PostTask().execute("http://www.google.com");

setContentView(R.layout.activity_main);
}
// The definition of our task class
private class PostTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();

}

@Override
protected String doInBackground(String... params) {
String url=params[0];
for (int i = 0; i <= 100; i += 5) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
return "All Done!";
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);

}

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

}
}


EDITTED:
This is my activity_main.xml code

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.project.unityapp.MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

</RelativeLayout>


my application is not opening the url on launch. Kindly assist.

Answer

If you want to display the webpage of that url use webview

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.project.unityapp.MainActivity" >


<WebView  
    android:id="@+id/webView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

</RelativeLayout>

Activity

public class WebViewActivity extends Activity {

    private WebView webView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://www.google.com");

    }

}