I’m trying to collect some json data, put those in a string and show them in my app through a toast as for test. I’m pretty sure that the server allows me and responds to my request because previously testing the GET method on Fiddler with the same URL(URI).
Here’s the activity/class code:
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
try {
request.setURI(new URI("http://scards.cloudapp.net/api/AddressBooks/3"));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
try {
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String page = sb.toString();
Toast.makeText(this, page, Toast.LENGTH_LONG).show();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And in LogCat it shows me that I have android.os.NetworkOnMainThreadException.
Open to suggestions and corrections.
Project properties : SDK: API16 – Android 4.1.2, minBuilSDK : API:7 Android 2.1(Eclair) – Eclipse SDK 4.2
Here is an example of
AsyncTaskbelow. Also here is a great tutorialI call my
AsyncTaskwith this line:Here is a Youtube tutorial (from the New Boston) for
AsyncTaskthat I found helpful.Android Application Development Tutorial – 101 – Async Task class to load stuff
Android Application Development Tutorial – 102 – The 4 AsyncTask Methods
Android Application Development Tutorial – 103 – ProgressDialog and Correction