-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathASyncTaskExample.java
More file actions
62 lines (52 loc) · 2.11 KB
/
ASyncTaskExample.java
File metadata and controls
62 lines (52 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
private class ThreadGetMessages extends AsyncTask<Integer, Integer, String> {
@Override
protected String doInBackground(Integer... integers) {
Log.i("ASyncTask", "requesting...");
String resourceURI = "https://jsonplaceholder.typicode.com/posts";
String httpParameters = "";
String formatedURL = resourceURI + httpParameters;
URL url = null;
try {
url = new URL(formatedURL);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection con = null;
try {
con = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
con.setRequestMethod("GET");
} catch (ProtocolException e) {
e.printStackTrace();
}
InputStream is = null;
try {
is = con.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
String response = s.hasNext() ? s.next() : "";
Log.i("ASyncTask", "requesting concluded." + response);
JsonParser parser = new JsonParser();
//JsonObject obj = parser.parse(response).getAsJsonObject();
JsonArray array = parser.parse(response).getAsJsonArray();
JsonObject obj = (JsonObject) array.get(0);
String title = obj.get("title").getAsString();
Log.i("ASyncTask", "title>>" + title);
return title;
}
@Override
protected void onPostExecute (String result) {
View v=findViewById(R.id.exportIcon);
// Log.i("ASyncTask",result);
LinearLayout ll=(LinearLayout)findViewById(R.id.LLItems);
TextView tv=new TextView(getBaseContext());
tv.setText(result);
tv.setTextColor(Color.WHITE);
ll.addView(tv);
}
}