【问题标题】:Getting Shared Preferences in Async Task Class在异步任务类中获取共享首选项
【发布时间】:2018-12-02 03:48:15
【问题描述】:

我正在尝试构建一个应用程序,它将患者 ID 作为共享偏好,并在另一个活动中使用该 ID 来获取该 ID 的记录。在主活动中,我设置了共享首选项,它正确设置了值。但是,在 FetchSinglePatientData 中,我无法获得相同的共享偏好值。

P.S:在那个错误发生之前,我什么也没得到。我的代码如下:

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 活动,该活动使用后台的 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

非常感谢!

【问题讨论】:

    标签: java android android-studio android-asynctask sharedpreferences


    【解决方案1】:

    您正在使用两种不同的方式来获取 SharedPreferences 对象。首先,您使用带有首选项文件名的 Context.getSharedPreferences() 方法。然后使用静态方法 PreferenceManager.getDefaultSharedPreferences()。这将导致使用两个不同的 SharedPreference 文件。只需选择一种或另一种方式并保持一致,它应该会更好地工作。

    【讨论】:

    • 老兄,你在我脑海中弹出了灯泡。我找到了解决方案并发布了它。谢谢!
    【解决方案2】:

    为解决此问题,请使用具有定义名称和模式的共享首选项。为了 示例:

    SharedPreferences SharedPreference = context.getSharedPreferences("defined 
    name" , Context.MODE_PRIVATE);
    
    1. 为了在共享首选项中插入数据,使用 commit() 代替 apply()
    editor.commit();
    
    1. 并将 ApplicationContext 发送到您的 asynctask 类

    【讨论】:

    • 上下文无法在 getSinglePatient 中解析,因为它扩展了 AsyncTask 类。我们需要创建一个带有 Context 参数的构造函数,然后这个上下文可以在 SharedPreferences 中使用。否则,在 AsyncTask 扩展类中不能直接使用 context。
    • @88yomc 是的,我是这个意思
    【解决方案3】:

    我通过更改以下代码解决了我的问题:

    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 来说有点棘手。我建议这些帖子:

    post1post2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多