2

I would like to just read on an android device some date i have loaded on a mysql database on a physical server. The database and the php script to extract the data are ok. The problem is the android coding side.

public class MainActivity extends Activity {
    public HttpResponse response;
    public String str;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("/*phpAddressIsCorrect*/");

        try {
            response = httpclient.execute(httppost);
        }
        catch(IOException e) {
            e.printStackTrace();
        }

        try {
            str = EntityUtils.toString(response.getEntity());
        } catch(IOException e){
            e.printStackTrace();
        }

        Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
    }
}

The main.xml is just a RelativeLayout.

With android permission of internet, the apps crashes on loading. I suppose that's because of IOException, isn't it?

jww
  • 97,681
  • 90
  • 411
  • 885

1 Answers1

1

Networking always needs to be done in another Thread (not the UiThread).

new Thread() {
    public void run() {
        HttpURLConnection con = (HttpURLConnection) new URL("http://xyz").openConnection();
        String response = StreamToString(con.getInputStream());
        // ...
    }
}.start();

 

public static String StreamToString(java.io.InputStream is) {
    java.util.Scanner scanner = new java.util.Scanner(is);
    scanner.useDelimiter("\\A");
    String ret = scanner.hasNext() ? scanner.next() : "";
    scanner.close();
    return ret;
}
ByteHamster
  • 4,884
  • 9
  • 38
  • 53
  • Thanks a lot, so i have to create a startIntentService in the main o is it a backgroundThread? – Julius Beta Feb 01 '15 at 13:05
  • The Thread I posted is executed in background. So just copy my answer and do your parsing stuff etc. where I wrote the three dots. Keep in mind that you can not change the UI in another Thread (create a [runOnUiThread](http://stackoverflow.com/a/27992603/4193263) inside this background Thread). Also keep in mind that the networking takes some time, your variables might be uninitialized if you read them for example from an onClickListener. – ByteHamster Feb 01 '15 at 13:26