簡體   English   中英

在異步任務類中獲取共享首選項

[英]Getting Shared Preferences in Async Task Class

我正在嘗試構建一個應用,該應用將患者ID作為共享首選項,並在另一個活動中使用該ID來獲取該ID的記錄。 在主要活動中,我設置了“共享首選項”,並且它正確設置了該值。 但是,在FetchSinglePatientData中,我無法獲得相同的共享首選項值。

PS:在出現該錯誤之前,我什么都沒得到。 我的代碼如下:

public void getSinglePatient(View v)
    {
        etID = findViewById(R.id.editTextID);
        SharedPreferences sharedPref = getSharedPreferences("patientId", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("patientId",etID.getText().toString());
        editor.apply();

        String xx = sharedPref.getString("patientId","hayamk");
        Log.d("XX","DEGER" + xx);

        //instantiate intent class
        Intent intent=new Intent(MainActivity.this, GetSinglePatient.class);

        //start the activity
        startActivity(intent);
    }

GetSinglePatient活動,此活動使用background.fetchSinglePatientData中的fetchSinglePatientData如下所示:

package project.android.mapd713.college.centennial.com.mapd713application;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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

    String data = "";
    String dataParsed = "";
    String singleParsed = "";
    JSONObject myObject;
    private Context ctx;

    public fetchSinglePatientData(Context ctx) {
        this.ctx = ctx;
    }


    @Override
    protected Void doInBackground(Void... voids) {


        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
        //String patientId = prefs.getString("patientId", "");
        String xx = sharedPref.getString("patientId","fafafa");
        Log.d("XX2","DEGE2R" + xx);





        Log.i("fonksiyon","ICINE GIRDI");

        try {
            URL url = new URL("https://mapd713prjct.herokuapp.com/patients/5bf63c770fc33ea59c9c3a97");
            Log.i("URL","URL ICINE GIRDI");
            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;

            }

            myObject = new JSONObject(data);
            myObject.getString("doctor");
            Log.d("DOKTOR BU NE","hmm" + myObject.getString("doctor"));



        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.out.print("HATA 1: " + e);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.print("HATA 2: " + e);
        } catch (JSONException e) {
            e.printStackTrace();
            System.out.print("HATA 3: " + e);
        }


        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        System.out.println("girdi");
        Log.i("onPostExecute","GIRDI");
        GetSinglePatient.mTextViewResult.setText(myObject.toString());
    }
}

日志如下所示,有兩個不同的輸入,1)jajaja和2)hehehe

2018-12-01 22:38:12.360 7470-7470/project.android.mapd713.college.centennial.com.mapd713application D/XX: DEGERjajaja
2018-12-01 22:38:12.816 7470-

7497/project.android.mapd713.college.centennial.com.mapd713application D/XX2: DEGE2Rfafafa
2018-12-01 22:43:05.644 7470-7470/project.android.mapd713.college.centennial.com.mapd713application D/XX: DEGERhehehe
2018-12-01 22:43:05.815 7470-7547/project.android.mapd713.college.centennial.com.mapd713application D/XX2: DEGE2Rfafafa

非常感謝你!

您正在使用兩種不同的方法來獲取SharedPreferences對象。 首先,您使用帶有首選項文件名的Context.getSharedPreferences()方法。 然后,您使用靜態方法PreferenceManager.getDefaultSharedPreferences()。 這將導致使用兩個不同的SharedPreference文件。 只需選擇一種方式並保持一致,它應該會更好。

要解決此問題,請使用具有定義名稱和模式的共享首選項。 例如:

SharedPreferences SharedPreference = context.getSharedPreferences("defined 
name" , Context.MODE_PRIVATE);
  1. 為了在共享首選項中插入數據而沒有任何延遲,請使用commit()而不是apply()
editor.commit();
  1. 並將ApplicationContext發送到您的asynctask類

我通過更改下面的代碼解決了我的問題:

SharedPreferences sharedPref = getSharedPreferences("patientId", Context.MODE_PRIVATE);

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

的確,我使用了兩種不同的SharedPreference方法,因此無法獲得患者ID。 但是,改變

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);

SharedPreferences sharedPref = getSharedPreferences("patientId", Context.MODE_PRIVATE);

不起作用,因為getSharedPreferences()需要訪問上下文。

我認為,使用Android有點棘手。 我建議那些職位:

post1 post2

暫無
暫無

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

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