Gaurav Dureja
Gaurav Dureja

Reputation: 190

How to send JSON response object from custom class to another activity android

I am fetching API data in a custom class (non-activity class). Now I want to parse my JSON response object to Activity Class, but not able to do the same. Kindly held how to send response object from non activity class to Activity Class:

Note: I don't want to use Sharedpreference.

My Custom Class:

public class APIHelper {

    private static final String baseurl = "myUrl";
    private static final String loginAPI = "auth/login";

    public void getAPIResponse(Context context, View view, JSONObject parameters) {

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, baseurl + loginAPI, parameters, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                //I want to send this response to another activity...

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                NetworkResponse response = error.networkResponse;
                if (error instanceof ServerError && response != null) {
                    try {

                        String res = new String(response.data, HttpHeaderParser.parseCharset(response.headers, "utf-8"));
                        JSONObject jsonObject = new JSONObject(res);
                        Utility.showSnackBar(view, jsonObject.getString("message"), "top", "error");

                    } catch (UnsupportedEncodingException | JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        RequestQueue queue = Volley.newRequestQueue(context);
        queue.add(jsonObjectRequest);

    }
}

Upvotes: 0

Views: 385

Answers (2)

aref behboodi
aref behboodi

Reputation: 169

First create this interface :

public interface ApiService {
    onResponse(JSONObject json);
}

then

public class APIHelper {

    private static final String baseurl = "myUrl";
    private static final String loginAPI = "auth/login";
    private ApiService  apiService;

    public void setApiService(ApiService  apiService) {
       this.apiService = apiService;
    }


    public void getAPIResponse(Context context, View view, JSONObject parameters) {

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, baseurl + loginAPI, parameters, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                 apiService.onResponse(response);
                //I want to send this response to another activity...

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                NetworkResponse response = error.networkResponse;
                if (error instanceof ServerError && response != null) {
                    try {

                        String res = new String(response.data, HttpHeaderParser.parseCharset(response.headers, "utf-8"));
                        JSONObject jsonObject = new JSONObject(res);
                        Utility.showSnackBar(view, jsonObject.getString("message"), "top", "error");

                    } catch (UnsupportedEncodingException | JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        RequestQueue queue = Volley.newRequestQueue(context);
        queue.add(jsonObjectRequest);

    }
}

in your activity :

APIHelper api = new APIHelper();
api.setApiService(new ApiService() {
            @Override
            public void onResponse(JSONObject res) {
                //write your code
            }
}
api.getAPIResponse(context, view, params);

this code may haven syntax error, report me to fix it

Upvotes: 2

Dev4Life
Dev4Life

Reputation: 3317

It's easier if you use gson. just follow these steps

  1. add gson dependency to your gradle

    implementation 'com.google.code.gson:gson:2.8.7'
    
  2. Convert your JSON object or JSON arraylist into a String like this.

    Gson gson = new Gson();
    String json = gson.toJson(arrayList);
    

It's converted to string now. So you can save it in your Utils class or in sharedreference. To retrieve the JSON back, use this

    // If you have JSON Object then put your class name which you are using to save data

    String savedJson = Utils.jsonStr;
    Type type = new TypeToken<YourModelClass>() {
    }.getType();
    
    YourModelClass model = gson.fromJson(json, type);

    // If you have JSON arraylist then

    String savedJson = Utils.jsonStr;
    Type type = new TypeToken<ArrayList<YourModelClass>>() {
    }.getType();

    ArrayList<YourModelClass> arrayList = gson.fromJson(json, type);

Upvotes: 0

Related Questions