【问题标题】:How to use Shared Preferences without extending AppCompatActivity to the class?如何在不将 AppCompatActivity 扩展到类的情况下使用共享首选项?
【发布时间】:2020-02-13 11:14:44
【问题描述】:

我需要在我的班级中使用共享首选项,但是当我使用 getSharedPreferences 方法时,它会说 “无法解析方法'getSharedPreferences(java.lang.String, int)'。代码如下:


public class FetchData extends AsyncTask<Void, Void, Void> {

    String data = "";



    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL("https://api.jsonbin.io/b/5e42776dd18e4016617690ce/3");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while (line != null) {
                line = bufferedReader.readLine();
                data = data + line;
            }



            JSONArray JA = new JSONArray(data);

SharedPreferences sharedPreferences = getSharedPreferences("SHARED_PREFS", Context.MODE_PRIVATE); // THE ERROR
            SharedPreferences.Editor editor = sharedPreferences.edit();

//            for(int i =0 ;i < JA.length(); i++) {
//                JSONObject JO = (JSONObject) JA.get(i);
//                singleParsed =
//                        "id: " + JO.get("id") + "\n" +
//                      "img: " + JO.get("img") + "\n" +
//                        "w1: " + JO.get("w1") + "\n" +
//                        "w2: " + JO.get("w2") + "\n" +
//                        "w3: " + JO.get("w3") + "\n" +
//                        "w4: " + JO.get("w4") + "\n";
//
//                dataParsed = dataParsed + singleParsed + "\n";
//
//            }

【问题讨论】:

    标签: java android json sharedpreferences


    【解决方案1】:

    你应该这样做,

     public class FetchData extends AsyncTask<Void, Void, Void> {
    
        String data = "";
        Context context;
    
        FetchData (Context context){
         this.context = context;
        }
    
     }
    

          SharedPreferences sharedPreferences = context.getSharedPreferences("SHARED_PREFS", Context.MODE_PRIVATE);
    

    【讨论】:

      【解决方案2】:

      您可以使用 GitHub 库进行 sharePrefrence 这里是链接 - EasyPrefs Library

      这个库为你提供了 SharedPreference 的功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-11
        • 2014-08-17
        • 2015-09-25
        • 2022-06-10
        • 2015-07-02
        • 1970-01-01
        相关资源
        最近更新 更多