Java – How to get information from a web page in Android Java

How to get information from a web page in Android Java… here is a solution to the problem.

How to get information from a web page in Android Java

I’ve been trying to convert information from a web page into a string and send it to my Android app. I’ve been using this method.

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class DownloadPage {

private static int arraySize;

public static int getArraySize() throws IOException {

URL url = new URL("http://woah.x10host.com/randomfact2.php");

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));

String size = br.readLine();

arraySize = Integer.parseInt(size);

return arraySize;
    }

}

I even included permissions in my AndroidManifest.xml file

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

But I keep getting error messages and my app won’t start. It crashes every time I call a method or class.

Solution

You seem to have encountered android.os.NetworkOnMainThreadException.
Try using AsyncTask to get the integer.

public class DownloadPage {

private static int arraySize;

public void getArraySize() throws IOException {

new RetrieveInt().execute();
    }

private class RetrieveInt extends AsyncTask<String, Void, Integer> {

@Override
        protected Integer doInBackground(String ... params) {
            try {
                URL url = new URL("http://woah.x10host.com/randomfact2.php");

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));

String size = br.readLine();

arraySize = Integer.parseInt(size);

} catch (Exception e) {
                do something
            }
            return arraySize;  gets 18
        }

protected void onPostExecute(Integer i) {

 TODO: do something with the number
 You would get value of i == 18 here. This methods gets called after your doInBackground() with output.
            System.out.println(i); 
        }
    }

}

Related Problems and Solutions