【问题标题】:Access shared preferences from a helper class从帮助程序类访问共享首选项
【发布时间】:2021-04-04 07:17:03
【问题描述】:

我有一个片段,它调用一个辅助类以便使用 Volley 生成一个 jsonRequest。

根据响应,帮助程序类创建一个自定义对象,但为了设置它,它需要检查存储在 Shared Preferences 中的一些值。

问题是我无法访问辅助类中的 getSharedPreferences。

public class MyDataHandler {
ArrayList<MyItem> itemsArrayList = new ArrayList<>();

public List<MyItem> getAll(Boolean completed, String current, final MyAsyncResponse callBack) {

    String url = "https://my.api/" + current;

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
            Request.Method.GET,
            url,
            null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    for (int i = 0; i < response.length(); i++) {

                        try {
                            JSONObject jsonObject = response.getJSONObject(i);

                            MyItem myItem = new MyItem();

                            if (!completed) {
                                SharedPreferences sharedPreferences = getSharedPreferences("MyApp", MODE_PRIVATE); // this doesn't work
                                if (sharedPreferences.getBoolean("someKey", false)) {
                                     // set properties in MyItem
                                }
                            }

                            itemsArrayList.add(myItem);

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

                    if (null != callBack) callBack.processFinished(itemsArrayList);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }
    );

    AppController.getInstance().addToRequestQueue(jsonArrayRequest);

    return itemsArrayList;
}

如果此类未附加到任何特定活动,我如何访问共享首选项?

【问题讨论】:

  • 您可以让您的 getAll 方法采用额外的最终 Context 参数。然后,在 onResponse 实现中调用 context.getSharedPreferences 而不是 getSharedPreferences。

标签: android sharedpreferences


【解决方案1】:

我假设您正在实例化 MyDataBaseHandler,因为“getAll”是一个非静态函数 像这样创建一个构造函数和一个成员变量:-

 MyDataBaseHandler{
   
 Context context;

public MyDataHandler(Context context){ //pass your activity here
    this.context=context;
 }
// write rest of your code

}

现在您可以使用此上下文成员变量并使用 context.getSharedPreference("MyApp", Context.MODE_PRIVATE) 访问您的共享性能。

【讨论】:

    猜你喜欢
    • 2011-06-16
    • 2017-01-28
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 2016-02-14
    相关资源
    最近更新 更多