Android Does Sharedpreferences save null?

1

Good morning everyone! I'm making an app using Android Studio. It is very simple, it has a numeric field to enter a número de cliente and a button of confirmar that based on the number entered brings you the puntos of that client. I am using SharedPreferences to save the client number and every time the app starts it checks if there is a client number saved or not. If there is a number, load the points. The problem is that when you close the app and start it again it is as if the value of SharedPreferences becomes null . I do not know what I'm doing wrong. It's the first time I use SharedPreferences. Thank you very much.

PS: with the client number 47, it returns the value 101. At first it works. But when you close and open the app no longer.

I leave my code:

public class Tab1_MisPuntos extends Fragment {

TextView tv_nroCliente;
EditText txt_IdCliente;
Button bConfirmar;
TextView tv_puntosCliente;

String type = "login";
String PREF_ID_CLIENTE = "";

ImageView img1;
ImageView img2;
ImageView img3;
ImageView img4;
ImageView img5;
ImageView img6;


@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.tab1_mispuntos, container, false);

    tv_nroCliente = (TextView) view.findViewById(R.id.tv_nroCliente);
    txt_IdCliente = (EditText) view.findViewById(R.id.txt_IdCliente);
    bConfirmar = (Button) view.findViewById(R.id.bConfirmar);
    tv_puntosCliente = (TextView) view.findViewById(R.id.tv_puntosCliente);

    img1 = (ImageView) view.findViewById(R.id.img1);
    img2 = (ImageView) view.findViewById(R.id.img2);
    img3 = (ImageView) view.findViewById(R.id.img3);
    img4 = (ImageView) view.findViewById(R.id.img4);
    img5 = (ImageView) view.findViewById(R.id.img5);
    img6 = (ImageView) view.findViewById(R.id.img6);



    if(SaveSharedPreference.getNroCliente(this.getContext()).length() == 0)
    {
        //Seguir normal
    }
    else
    {
        //Obtener puntos
        new BackgroundWorker(getContext(),tv_puntosCliente, txt_IdCliente, bConfirmar).execute(type, PREF_ID_CLIENTE);
    }

    //Boton Confirmar.
    bConfirmar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (txt_IdCliente.getText().toString().equals("")){
                //ALERTDIALOG "Por favor, ingrese un nro de cliente."
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage(R.string.alertDialogMensaje1)
                        .setCancelable(false)
                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                //Aceptar
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();
            }
            else {
                PREF_ID_CLIENTE = txt_IdCliente.getText().toString();
                //Obtener puntos desde urlPuntos + idCliente;
                SaveSharedPreference.setNroCliente(getContext(), PREF_ID_CLIENTE);
                new BackgroundWorker(getContext(),tv_puntosCliente, txt_IdCliente, bConfirmar).execute(type, PREF_ID_CLIENTE);
            }
        }

    });

    return view;
}

SharedPreferences class:

class SaveSharedPreference {

static final String PREF_ID_CLIENTE= "NroCliente";

static SharedPreferences getSharedPreferences(Context ctx) {
    return PreferenceManager.getDefaultSharedPreferences(ctx);
}

public static void setNroCliente(Context ctx, String nroCliente)
{
    SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
    editor.putString(PREF_ID_CLIENTE, nroCliente);
    editor.commit();
}

public static String getNroCliente(Context ctx)
{
    return getSharedPreferences(ctx).getString(PREF_ID_CLIENTE, "");
}

BackgroundWorker Class

class BackgroundWorker extends AsyncTask<String, Void, String> {

private final TextView tv_puntosCliente;
private final Button bConfirmar;
private final EditText txt_IdCliente;


Context context;
BackgroundWorker (Context ctx, TextView tv_puntosCliente, EditText txt_IdCliente, Button bConfirmar) {
    context = ctx;
    this.tv_puntosCliente = tv_puntosCliente;
    this.bConfirmar = bConfirmar;
    this.txt_IdCliente = txt_IdCliente;
}
private ProgressDialog pDialog;

private String PREF_ID_CLIENTE = "";
private String type = "";


@Override
protected String doInBackground(String... params) {

    type = params[0];
    PREF_ID_CLIENTE = params[1];

    String urlPuntos = "http://myweb.com/app/clubapp.php?i=0&c="+PREF_ID_CLIENTE;

    if(type.equals("login")) {

        try {
            URL url = new URL(urlPuntos);

            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode(" ","UTF-8")+"="+ URLEncoder.encode(PREF_ID_CLIENTE,"UTF-8");
            bufferedWriter.write(post_data);

            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result="";
            String line="";

            while((line = bufferedReader.readLine())!= null) {
                result += line;
            }

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();

            return result;


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    pDialog = new ProgressDialog(this.context);
    pDialog.setCancelable(false);
    pDialog.show();
}

@Override
protected void onPostExecute(String result) {
    if (pDialog.isShowing())
        pDialog.dismiss();

    if (result.equals("")){
        //ALERTDIALOG "Por favor, ingrese un nro de cliente."
        AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
        builder.setMessage(R.string.alertDialogMensaje2)
                .setCancelable(true)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //Aceptar
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
    else {
        //Puntos
        tv_puntosCliente.setText(result);
        txt_IdCliente.setText(SaveSharedPreference.getNroCliente(this.context), TextView.BufferType.EDITABLE);
        txt_IdCliente.setEnabled(false);
        bConfirmar.setVisibility(View.GONE);

    }
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

EDIT: I could solve it in the following way: When passing the parameter to the BackgroundWorker, instead of passing PREF_ID_CLIENTE that by default initializes as empty, I passed this to it: SaveSharedPreference.getNroCliente (getContext ());

And it works fine. Thank you all for responding!.

    
asked by L_C 25.01.2018 в 00:45
source

2 answers

1

The code of your class to save and obtain the data is correct.

But in your class Tab1_MisPoints when starting these, defining an empty value of PREF_ID_CLIENTE which overwrites the preference.

public class Tab1_MisPuntos extends Fragment {

...
...
String PREF_ID_CLIENTE = "";
...
...
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.tab1_mispuntos, container, false);   

    if(SaveSharedPreference.getNroCliente(this.getContext()).length() == 0)
    {
        //Seguir normal
    }
    else
    {
        //Obtener puntos
        new BackgroundWorker(getContext(),tv_puntosCliente, txt_IdCliente, bConfirmar).execute(type, PREF_ID_CLIENTE);
    }

....

I notice that you use the variable PREF_ID_CLIENT as a key of the preference in class SaveSharedPreference but also in other parts of your code, I suggest you do not use this same variable so you do not get confused.

    
answered by 25.01.2018 / 17:31
source
0

It is not advisable to use the getDefaultSharedPreferences instead, try the following code:

private final static String preferences_key="MyDB";

getSharedPreferences(preferences_key,Context.MODE_PRIVATE);
    
answered by 26.01.2018 в 00:05