Skip to content

Instantly share code, notes, and snippets.

@yudanta
Created June 8, 2015 11:16
Show Gist options
  • Save yudanta/631a7a9f99332d2b1061 to your computer and use it in GitHub Desktop.
Save yudanta/631a7a9f99332d2b1061 to your computer and use it in GitHub Desktop.
GetDataFromServer
package co.nuwira.nwrandroiddev;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by Amanda on 6/8/15.
*/
public class GetDataFromServer extends ActionBarActivity{
String response = "";
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
new DataTask().execute();
}
private class DataTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... arg0) {
InputStream inputStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(new HttpGet("http://yudanta.web.id/trans_jogja.json"));
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null){
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
while((line = bufferedReader.readLine()) != null)
response += line;
inputStream.close();
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
try {
JSONObject jsonData = new JSONObject(response);
if (jsonData != null){
if (jsonData.getInt("status") == 200){
JSONArray arrayData = jsonData.getJSONArray("items");
for (int i = 0; i < arrayData.length(); i++) {
Log.d("Val", arrayData.getJSONObject(i).getString("name"));
}
}
}
}catch (JSONException e){
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment