Skip to content

Instantly share code, notes, and snippets.

@xxhdpi
Last active March 26, 2017 01:47
Show Gist options
  • Select an option

  • Save xxhdpi/7648a7a2e6773439bf1f2b362c700aee to your computer and use it in GitHub Desktop.

Select an option

Save xxhdpi/7648a7a2e6773439bf1f2b362c700aee to your computer and use it in GitHub Desktop.
public class MainActivity extends AppCompatActivity {
private static final String DATA_FROM_NET = "https://httpbin.org/get";
private static final String TAG = "MainActivity";
private Button btnGetData;
private TextView tvHasil;
private RequestQueue requestQueue;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGetData = (Button) findViewById(R.id.btnGetData);
tvHasil = (TextView) findViewById(R.id.tvHasil);
// initiate requestQueue volley
requestQueue = Volley.newRequestQueue(this);
btnGetData.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
getDataFromURL(DATA_FROM_NET);
}
});
}
/**
* ambil data dari internet menggunakan StringRequest dari volley
*/
private void getDataFromURL(String url) {
StringRequest stringRequest =
new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override public void onResponse(String response) {
// logging
Log.d(TAG, "onResponse: " + response);
tvHasil.setText(response);
}
}, new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) {
// jika proses http rquest gagal
tvHasil.setText(error.getLocalizedMessage());
}
});
// menambahkan request ke queue
requestQueue.add(stringRequest);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment