Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. {
  2. "employee_id": 1001,
  3. "name": "Abhishek",
  4. }
  5.  
  6. build.gradle
  7. compile 'com.android.volley:volley:1.0.0'
  8.  
  9. MySingleton.class
  10. import android.content.Context;
  11.  
  12. import com.android.volley.Request;
  13. import com.android.volley.RequestQueue;
  14. import com.android.volley.toolbox.Volley;
  15.  
  16. public class MySingleton {
  17.  
  18. private static MySingleton mInstance;
  19. private RequestQueue mRequestQueue;
  20. private static Context mCtx;
  21.  
  22. private MySingleton(Context context) {
  23. mCtx = context;
  24. mRequestQueue = getRequestQueue();
  25. }
  26.  
  27. public static synchronized MySingleton getInstance(Context context) {
  28. if (mInstance == null) {
  29. mInstance = new MySingleton(context);
  30. }
  31. return mInstance;
  32. }
  33.  
  34. public RequestQueue getRequestQueue() {
  35. if (mRequestQueue == null) {
  36. // getApplicationContext() is key, it keeps you from leaking the
  37. // Activity or BroadcastReceiver if someone passes one in.
  38. mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
  39. }
  40. return mRequestQueue;
  41. }
  42.  
  43. public <T> void addToRequestQueue(Request<T> req) {
  44. getRequestQueue().add(req);
  45. }
  46.  
  47. }
  48.  
  49. MainActivity.class
  50. private void loadJsonObj() {
  51. JsonObjectRequest jsObjRequest = new JsonObjectRequest
  52. (Request.Method.GET, obj_url, null, new Response.Listener<JSONObject>() {
  53.  
  54. @Override
  55. public void onResponse(JSONObject response) {
  56. pDialog.dismiss();
  57. try {
  58. //Parse the JSON response
  59. Integer employeeId = response.getInt(KEY_EMPLOYEE_ID);
  60. String name = response.getString(KEY_NAME);
  61.  
  62. //Create String out of the Parsed JSON
  63. StringBuilder textViewData = new StringBuilder().append("Employee Id: ")
  64. .append(employeeId.toString()).append(NEW_LINE);
  65. textViewData.append("Name: ").append(name).append(NEW_LINE);
  66.  
  67. //Populate textView with the response
  68. mTxtDisplay.setText(textViewData.toString());
  69.  
  70. } catch (JSONException e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. }, new Response.ErrorListener() {
  75.  
  76. @Override
  77. public void onErrorResponse(VolleyError error) {
  78. pDialog.dismiss();
  79.  
  80. //Display error message whenever an error occurs
  81. Toast.makeText(getApplicationContext(),
  82. error.getMessage(), Toast.LENGTH_SHORT).show();
  83. }
  84. });
  85.  
  86. // Access the RequestQueue through your singleton class.
  87. MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement