簡體   English   中英

如何在不將 AppCompatActivity 擴展到類的情況下使用共享首選項?

[英]How to use Shared Preferences without extending AppCompatActivity to the class?

我需要在我的班級中使用共享首選項,但是當我使用 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";
//
//            }

你應該這樣做,

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

您可以使用 GitHub 庫進行 sharePrefence,這里是鏈接 - EasyPrefs 庫

該庫為您提供 SharedPreference 的功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM