简体   繁体   English

如何将 JSON 响应对象从自定义类发送到另一个活动 android

[英]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).我在自定义类(非活动类)中获取 API 数据。 Now I want to parse my JSON response object to Activity Class, but not able to do the same.现在我想将我的 JSON 响应对象解析为 Activity 类,但不能这样做。 Kindly held how to send response object from non activity class to Activity Class:请教如何将响应对象从非活动类发送到活动类:

Note: I don't want to use Sharedpreference.注意:我不想使用 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);

    }
}

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此代码可能有语法错误,请报告我修复它

It's easier if you use gson.如果您使用 gson 会更容易。 just follow these steps只需按照这些步骤

  1. add gson dependency to your gradle将 gson 依赖项添加到您的 gradle

     implementation 'com.google.code.gson:gson:2.8.7'
  2. Convert your JSON object or JSON arraylist into a String like this.将您的 JSON 对象或 JSON 数组列表转换为这样的字符串。

     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.因此,您可以将其保存在 Utils 类或共享引用中。 To retrieve the JSON back, use this要检索 JSON,请使用此

    // 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从一个活动向另一个活动发送和接收 json 对象? - How to send and receive the json object from one activity to another? 如何将对象从 ViewHolder 类发送到另一个活动 - how to send an object from a ViewHolder class to another Activity 如何将数据从一个非活动类发送到另一个 android - how to send data from one non activity class to another android 如何使用 Intent 将对象从一个 Android Activity 发送到另一个? - How to send an object from one Android Activity to another using Intents? 如何在android中将Calendar对象从一个活动发送到另一个活动? - How to send a Calendar object from one activity to another in android? 如何使用可打包将对象从一个Android活动发送到另一个? - How to send an object from one Android Activity to another using parcelable? 如何将一个活动的类对象类型的ArrayList发送到另一个活动? - How to send ArrayList of class object type from one activity to another activity? 将JSON解析为Parcelable对象,以将Parcelable对象发送到Android中的另一个Activity - Parsing JSON to Parcelable objects to send Parcelable object to another Activity in Android 如何将自定义类的对象从Android发送到Java Server? - How to send an object of custom class from Android to Java Server? 如何将类中的数据发送到Android中的Activity - How to send data from a class to an Activity in Android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM