Save user ID in all the fragments of an app?

1

I have a fragment login, a fragment to register clients and depending on who enters the login we will collect a different ID for each user entered.

In an answer to this question I was recommended to create a class with a couple of get and set methods to make a variable that remains during the whole life cycle of the app, however I miss this error when I try to pass the ID with the method set. I leave the codes here and the error message.

/// ERROR ///

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.usuario.alfapharmashop, PID: 6207
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.usuario.alfapharmashop.Adapters.Constants.setIdUsuario(int)' on a null object reference
    at com.example.usuario.alfapharmashop.Fragments.LoginFragment.onResponse(LoginFragment.java:233)
    at com.example.usuario.alfapharmashop.Fragments.LoginFragment.onResponse(LoginFragment.java:41)
    at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:83)
    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:106)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:171)
    at android.app.ActivityThread.main(ActivityThread.java:6651)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)

/// Constants Class ///

public class Constants {

public static int id_usuario;

public  void setIdUsuario(int id)
{
    this.id_usuario = id;
}

public int getIdUsuario()
{
    return this.id_usuario;
}

}

/// Fragment Login ///

public class LoginFragment extends Fragment implements Response.ErrorListener, Response.Listener<JSONObject> {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private TextView textoInfo;
private TextView textorespuesta;
private TextView resultado;
private EditText editUsuario;
private EditText editContra;
private Button botonEntrar;
private IComunicaFragments logginFragments;
private Constants constants;
private SharedPreferences sharedPref;

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

ProgressDialog dialog;
JsonObjectRequest jsonObjectRequest;
private OnFragmentInteractionListener mListener;

public LoginFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment LoginFragment.
 */
// TODO: Rename and change types and number of parameters
public static LoginFragment newInstance(String param1, String param2) {
    LoginFragment fragment = new LoginFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View vista= inflater.inflate(R.layout.fragment_login, container, false);

    textoInfo = (TextView) vista.findViewById(R.id.txtRespuesta1);
    textorespuesta = (TextView) vista.findViewById(R.id.txtRespuesta2);
    resultado = (TextView) vista.findViewById(R.id.resultado);
    editUsuario = (EditText) vista.findViewById(R.id.username);
    editContra = (EditText) vista.findViewById(R.id.password);
    botonEntrar = (Button) vista.findViewById(R.id.buttonLogin);

    logginFragments.setLogginDrawable(false);

    botonEntrar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String usuario = editUsuario.getText().toString();
            String contra= editContra.getText().toString();
            iniciarSesion(usuario,contra);
        }
    });

   /* String defaultSharedPreferencesName = null;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && false) {
        defaultSharedPreferencesName = PreferenceManager.getDefaultSharedPreferencesName(getContext());
    }else {
        defaultSharedPreferencesName = getActivity().getPackageName() + "_preferences";
    }*/

    sharedPref = getActivity().getSharedPreferences("usuario",Context.MODE_PRIVATE);

    String prefStringUser = sharedPref.getString("user", "");
    String prefStringPass = sharedPref.getString("pass", "");
    if (!prefStringUser.isEmpty() && !prefStringPass.isEmpty()) {
        editUsuario.setText(prefStringUser);
        editContra.setText(prefStringPass);
    }

    return vista;
}


private void iniciarSesion(String user, String pass) {

    dialog=new ProgressDialog(getContext());
    dialog.setMessage("Iniciando sesión...");
    dialog.incrementProgressBy(100);
    dialog.show();

    String url="https://alfapharma.000webhostapp.com/loginUsuarios.php?usuario="+user+"&contrasena="+pass;

    jsonObjectRequest=new JsonObjectRequest(Request.Method.GET,url,null,this,this);
    // request.add(jsonObjectRequest);
    VolleySingleton.getIntanciaVolley(getContext()).addToRequestQueue(jsonObjectRequest);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
        logginFragments = (IComunicaFragments) getActivity();

    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

@Override
public void onErrorResponse(VolleyError error) {
    dialog.hide();
    Toast.makeText(getContext(),"El servidor no está disponible, intentalo de nuevo más tarde."+error.toString(),Toast.LENGTH_LONG).show();
    Log.i("ERROR",error.toString());
}

@Override
public void onResponse(JSONObject response) {
    dialog.hide();

    //    Toast.makeText(getContext(),"Mensaje: "+response,Toast.LENGTH_SHORT).show();

    JSONArray json=response.optJSONArray("agente");
    JSONObject jsonObject=null;

    Agente agente = new Agente();
    try {
        jsonObject=json.getJSONObject(0);

            agente.setId(jsonObject.optInt("id"));
            agente.setUsuario(jsonObject.optString("usuario"));
            agente.setContrasena(jsonObject.optString("contrasena"));
            agente.setTipo(jsonObject.optInt("tipo"));


    } catch (JSONException e) {
        e.printStackTrace();
    }

        //Get Editor object
        sharedPref.edit().putString("user", agente.getUsuario());
        sharedPref.edit().putString("pass", agente.getContrasena());
        //sp.edit().commit(); //Blocking Operation
        sharedPref.edit().apply(); //Asynchronous



        textoInfo.setText("Bienvenido " + agente.getUsuario());

        Log.e("ID AGENTE",agente.getId()+"");
        textorespuesta.setText("Has iniciado sesión correctamente.");
        resultado.setText("Ya puedes acceder al menú.");
        textorespuesta.setTextColor(Color.GREEN);
        editUsuario.setEnabled(false);
        editContra.setEnabled(false);
        botonEntrar.setEnabled(false);

        editUsuario.setVisibility(View.INVISIBLE);
        editContra.setVisibility(View.INVISIBLE);
        botonEntrar.setVisibility(View.INVISIBLE);

        logginFragments.setLogginDrawable(true);
        constants.setIdUsuario(agente.getId());




}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}}

/// Fragment Registrar ///

public class RegistroClienteFragment extends Fragment implements Response.ErrorListener, Response.Listener<JSONObject> {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private TextView razonSocial;
private TextView CIF;
private TextView dirFiscal;
private TextView dirPostal;
private TextView poblacion;
private TextView codigoPostal;
private TextView pais;
private TextView telefono;
private TextView fax;
private TextView mail;
private TextView web;
private Spinner formaPago;
private TextView personaResponsable;
private TextView nombreBanco;
private TextView poblacionBanco;
private TextView IBAN;
private TextView SWIFT;
private Button btnRegistrar;
private Constants constants;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

ProgressDialog dialog;

// RequestQueue request;
JsonObjectRequest jsonObjectRequest;

private OnFragmentInteractionListener mListener;

public RegistroClienteFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment PerfilFragment.
 */
// TODO: Rename and change types and number of parameters
public static RegistroClienteFragment newInstance(String param1, String param2) {
    RegistroClienteFragment fragment = new RegistroClienteFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View vista= inflater.inflate(R.layout.fragment_registro_cliente, container, false);

    razonSocial = (EditText) vista.findViewById(R.id.txtEditRazSoc);
    CIF = (EditText) vista.findViewById(R.id.txtEditCIF);
    dirFiscal= (EditText) vista.findViewById(R.id.txtEditDirFis);
    dirPostal = (EditText) vista.findViewById(R.id.txtEditDirPos);
    poblacion = (EditText) vista.findViewById(R.id.txtEditPob);
    codigoPostal = (EditText) vista.findViewById(R.id.txtEditCP);
    pais = (EditText) vista.findViewById(R.id.txtEditPais);
    telefono = (EditText) vista.findViewById(R.id.txtEditTlf);
    fax = (EditText) vista.findViewById(R.id.txtEditFax);
    mail = (EditText) vista.findViewById(R.id.txtEditMail);
    web = (EditText) vista.findViewById(R.id.txtEditWeb);
    formaPago = (Spinner) vista.findViewById(R.id.spinnerFormaPago);

    personaResponsable = (EditText) vista.findViewById(R.id.txtEditPersResp);
    nombreBanco = (EditText) vista.findViewById(R.id.txtEditNomEnt);
    poblacionBanco = (EditText) vista.findViewById(R.id.txtEditPobBan);
    IBAN = (EditText) vista.findViewById(R.id.txtEditIBAN);
    SWIFT = (EditText) vista.findViewById(R.id.txtEditSWIFT);

    btnRegistrar = (Button) vista.findViewById(R.id.btnRegistrar);

    String[] opciones = {"Pago contado","Giro 15 días","Giro 30 días","Giro 60 días"};
    formaPago.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, opciones));



    btnRegistrar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.e("ID AGENTE", constants.getIdUsuario()+"");

            insertarCliente();
        }
    });
    return vista;
}

public void insertarCliente(){
    dialog=new ProgressDialog(getContext());
    dialog.setMessage("Registrando cliente...");
    dialog.incrementProgressBy(100);
    dialog.show();

    String url="https://alfapharma.000webhostapp.com/registroCliente.php?razonsocial="+razonSocial.getText().toString()
            +"&cif="+CIF.getText().toString()
            +"&dirfiscal="+dirFiscal.getText().toString()
            +"&dirpostal="+dirPostal.getText().toString()
            +"&poblacion="+poblacion.getText().toString()
            +"&codigopostal="+Integer.parseInt(codigoPostal.getText().toString())
            +"&pais="+pais.getText().toString()
            +"&telefono="+Integer.parseInt(telefono.getText().toString())
            +"&fax="+Integer.parseInt(fax.getText().toString())
            +"&mail="+mail.getText().toString()
            +"&web="+web.getText().toString()
            +"&reqfact="+formaPago.getSelectedItem().toString()
            +"&personaresponsable="+personaResponsable.getText().toString()
            +"&nombreentidad="+nombreBanco.getText().toString()
            +"&poblacionbanco="+poblacionBanco.getText().toString()
            +"&iban="+IBAN.getText().toString()
            +"&swift="+SWIFT.getText().toString()
            +"&idagente="+constants.getIdUsuario();

    url = url.replace(" ","%20");

    jsonObjectRequest=new JsonObjectRequest(Request.Method.GET,url,null,this,this);
    // request.add(jsonObjectRequest);
    VolleySingleton.getIntanciaVolley(getContext()).addToRequestQueue(jsonObjectRequest);

}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

@Override
public void onErrorResponse(VolleyError error) {

    dialog.hide();
    Toast.makeText(getContext(),"El servidor no está disponible, intentalo de nuevo más tarde."+error.toString(),Toast.LENGTH_LONG).show();
    Log.i("ERROR",error.toString());
}

@Override
public void onResponse(JSONObject response) {

    dialog.hide();
    Toast.makeText(getContext(),"REGISTRO OKEY."+response.toString(),Toast.LENGTH_LONG).show();
   // Toast.makeText(getContext(),"Cliente registrado", Toast.LENGTH_SHORT);

}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

My question is: Is there any way to pick up that ID and use it in any fragment of the app as if it were a global cariable or something similar? I'm using Volley to collect the data from an external DB and I have no problem getting the ID but when I try to pass the data to another fragment (use bundle) it returns 0 in any case

    
asked by Leagueuftrolls 21.12.2018 в 02:40
source

1 answer

1

If what you need is to save the value of a variable while the application is in use, I recommend that you use a class with which you can save and retrieve that value.

Here's an example:

public class Constants {

    public static String id_usuario= "";

    public static void setIdUsuario(String id)
    {
        this.id_usuario = id;
    }

    public static void getIdUsuario()
    {
        return this.id_usuario;
    }
}

To interact with this variable you just have to make the call:

Constants.setIdUsuario(1);
Constants.getIdUsuario();

In case you need to save the id even if the app is closed, I recommend using the SharedPreferences of Android Studio .

//Para guardar un dato.
SharedPreferences datos_usuario= PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("id_usuario",1);
editor.putString("nombre_usuario","MiNombre");
editor.apply();

//Para obtener los datos
SharedPreferences datos_usuario= PreferenceManager.getDefaultSharedPreferences(this);
Integer id_usuario= datos_usuario.getInt("id_usuario", -1);
String name = datos_usuario.getString("nombre_usuario", "");
    
answered by 21.12.2018 / 10:15
source