Skip to content

Instantly share code, notes, and snippets.

@Fbalashov
Created November 7, 2015 18:16
Show Gist options
  • Save Fbalashov/704a797f71dc4da7f36f to your computer and use it in GitHub Desktop.
Save Fbalashov/704a797f71dc4da7f36f to your computer and use it in GitHub Desktop.
Intro App: Async Task
<!-- This stuff goes inside of your manifest tags -->
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".ViewPostActivity"
android:label="@string/app_name" >
</activity>
<activity
android:name=".PickPostActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
public class LoadPostTask extends AsyncTask<Integer, Void, JSONObject> {
private static final String LOG_TAG = LoadPostTask.class.getSimpleName();
private TextView titleView;
private TextView bodyView;
public LoadPostTask(TextView titleView, TextView bodyView) {
this.titleView = titleView;
this.bodyView = bodyView;
}
@Override
protected JSONObject doInBackground(Integer... postId) {
JSONObject jsonObject = null;
try {
URL url = new URL("http://jsonplaceholder.typicode.com/posts/" + postId[0].toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
jsonObject = readStream(in);
} catch (Exception e) {
Log.e(LOG_TAG, "Exception when connecting: "+e.getMessage());
} finally{
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Exception when parsing: "+e.getMessage());
}
return jsonObject;
}
public JSONObject readStream(InputStream inputStream) throws Exception {
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
return new JSONObject(responseStrBuilder.toString());
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
if (jsonObject == null) {
return;
}
try {
String titleString = jsonObject.getString("title");
String bodyString = jsonObject.getString("body");
titleView.setText(titleString);
bodyView.setText(bodyString);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment