如何在其他活动中访问模型类

时间:2019-02-01 06:39:29

标签: android android-activity

我有一个模型类,该模型类正在Fragment中填充。有没有办法访问modelsecond activity类中存储的列表数据?

这是我的模型课:

public class Idea {
    private String id, name, voted;

    public Idea(String id, String name, String voted) {
        this.id = id;
        this.name = name;
        this.voted = voted;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getVoted() {
        return voted;
    }

    public void setVoted(String voted) {
        this.voted = voted;
    }
}

编辑: 这是我的fragment中的一个代码段,其中正在填充model类:

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray products = new JSONArray(response);
                        for (int i = 0; i<products.length(); i++) {
                            JSONObject productObject = products.getJSONObject(i);

                            String id = productObject.getString("id");
                            String name = productObject.getString("name");
                            String voted = productObject.getString("voted");

                            Idea idea = new Idea(id, name, voted);
                            ideaList.add(idea);
                        }

                        ideaListAdapter = new IdeaListAdapter(getActivity().getApplicationContext(), ideaList);
                        recyclerViewIdeaFragment.setAdapter(ideaListAdapter);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

我猜正确的问题是如何在model类内获取值

1 个答案:

答案 0 :(得分:0)

是的。

您必须将模型类的对象声明为public static,并将其与片段类的对象一起形成所需的位置。