Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {
- "employee_id": 1001,
- "name": "Abhishek",
- }
- build.gradle
- compile 'com.android.volley:volley:1.0.0'
- MySingleton.class
- import android.content.Context;
- import com.android.volley.Request;
- import com.android.volley.RequestQueue;
- import com.android.volley.toolbox.Volley;
- public class MySingleton {
- private static MySingleton mInstance;
- private RequestQueue mRequestQueue;
- private static Context mCtx;
- private MySingleton(Context context) {
- mCtx = context;
- mRequestQueue = getRequestQueue();
- }
- public static synchronized MySingleton getInstance(Context context) {
- if (mInstance == null) {
- mInstance = new MySingleton(context);
- }
- return mInstance;
- }
- public RequestQueue getRequestQueue() {
- if (mRequestQueue == null) {
- // getApplicationContext() is key, it keeps you from leaking the
- // Activity or BroadcastReceiver if someone passes one in.
- mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
- }
- return mRequestQueue;
- }
- public <T> void addToRequestQueue(Request<T> req) {
- getRequestQueue().add(req);
- }
- }
- MainActivity.class
- private void loadJsonObj() {
- JsonObjectRequest jsObjRequest = new JsonObjectRequest
- (Request.Method.GET, obj_url, null, new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- pDialog.dismiss();
- try {
- //Parse the JSON response
- Integer employeeId = response.getInt(KEY_EMPLOYEE_ID);
- String name = response.getString(KEY_NAME);
- //Create String out of the Parsed JSON
- StringBuilder textViewData = new StringBuilder().append("Employee Id: ")
- .append(employeeId.toString()).append(NEW_LINE);
- textViewData.append("Name: ").append(name).append(NEW_LINE);
- //Populate textView with the response
- mTxtDisplay.setText(textViewData.toString());
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- pDialog.dismiss();
- //Display error message whenever an error occurs
- Toast.makeText(getApplicationContext(),
- error.getMessage(), Toast.LENGTH_SHORT).show();
- }
- });
- // Access the RequestQueue through your singleton class.
- MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement