0

I am trying to build an app, which takes the patient id as a shared preference and uses that id in another activity for getting the records of that id. In Main Activity I set the Shared Preferences, and it sets the value correctly. However, in FetchSinglePatientData, I am not able to get the same Shared Preference Value.

P.S : Before to that error, I was getting nothing at all. My codes at below:

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 activity, this activity uses the fetchSinglePatientData in background.fetchSinglePatientData is like below:

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

And the logs are like below with two different input, 1) jajaja and 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

Thank you very much!

obayral
  • 141
  • 3
  • 15

3 Answers3

0

You're using two different ways to obtain a SharedPreferences object. First you use the Context.getSharedPreferences() method that takes a preference file name. Then you use the static method PreferenceManager.getDefaultSharedPreferences(). This will result in two different SharedPreference files being used. Just pick one way or the other and be consistent and it should work much better.

Greg Moens
  • 1,705
  • 8
  • 15
0

for solving this problem , use a shared preference with define name and mode. for example:

SharedPreferences SharedPreference = context.getSharedPreferences("defined 
name" , Context.MODE_PRIVATE);
  1. for inserting data in shared preference without any delay use commit() instead of apply()
editor.commit();
  1. and send ApplicationContext to your asynctask class
Nima Mohammadi
  • 353
  • 2
  • 9
  • 1
    context can not be resolved in getSinglePatient since it extends the AsyncTask class. We need to create a constructor with Context parameter, then this context can be used in SharedPreferences. Otherwise, context cannot be directly used in AsyncTask extending class. – obayral Dec 02 '18 at 06:26
  • @88yomc yes , I meant that – Nima Mohammadi Dec 02 '18 at 06:33
0

I resolved my problem with changing my code below:

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

with

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

It is true that I used two different SharedPreference method and therefore, I couldn't get the Patient id. However, changing

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);

with

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

does not work since getSharedPreferences() needs a context to be accessed.

In my opinion, this is a little bit tricky with Android. I suggest those posts:

post1 post2

obayral
  • 141
  • 3
  • 15