Variable loss in Android Studio

1

Good, I am trying to use a query to a database, and the truth is that I have several questions, first of all I am very very new to this, so I can understand part of the code, so be patient.

I make a query and recover the data from the server, since everything works well, the problem is that I can not use the variables that I store throughout the activity, I would like to know in what way I can achieve keep the data at least until the user closes the application

The code I have is the following:

LoginRequest loginRequest = new LoginRequest(username, password, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.i("Login Response", response);                                                        
        progressDialog.dismiss();
        // Response from the server is in the form if a JSON, so we need a JSON Object
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getBoolean("success")) {
                Intent loginSuccess = new Intent(LoginActivity.this, MainActivity.class);
                // Passing all received data from server to next activity                                     
                loginSuccess.putExtra("nombre", jsonObject.getString("nombre"));

                //loginSuccess.putExtra("cedula", jsonObject.getString("cedula"));

                loginSuccess.putExtra("correo", jsonObject.getString("correo"));

                //loginSuccess.putExtra("saldoact", jsonObject.getString("saldoact"));

                //loginSuccess.putExtra("url", jsonObject.getString("pic"));
                String correo = getIntent().getStringExtra("correo");
                String nombre = getIntent().getStringExtra("nombre");
                startActivity(loginSuccess);
                finish();
            }
     ...
}

The application works very well indeed, the issue is that when I enter the main activity and move on to another activity, when I return to the activity the data I was using is lost, what I can do to prevent this from happening.

The other doubt is that when I make the query, it makes the query, but when the loop is exited the variable is lost:

RequestSaldo RequestSaldo = new RequestSaldo(username, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.i("Saldo Response", response);
                //progressDialog.dismiss();

                // Response from the server is in the form if a JSON, so we need a JSON Object
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getBoolean("success")) {
                        xcusrsaldo = jsonObject.getString("saldoact");
                        //Toast.makeText(PagoCorreo.this, usrsaldo, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(PagoCorreo.this, "Bad Response From Server", Toast.LENGTH_SHORT).show();
                }

            }



        });requestQueue.add(RequestSaldo);
        Toast.makeText(PagoCorreo.this, xcusrsaldo, Toast.LENGTH_SHORT).show();
        misaldo = (TextView) findViewById(R.id.saldoact);
        misaldo.setText(xcusrsaldo);

In both cases the question is how can I keep the variable that I am consulting in the JSON.

Edit: My main activity is configured to read Login.class, I do not know if that could be an error, When I go to the main activity I can show the data, but when I return, the other thing is that I do not know how to declare a variable global, well I would like and I think that would be a solution to declare a variable globally that can be accessed by all activities, ultimately if I do not succeed I have thought maybe using sqlite database. The problem is that if I use the database I must delete the data once it leaves the system so as not to overload the application with data.

Here is my Login class:

@Override
public class LoginActivity extends AppCompatActivity {
    //conexion a la base de datos
    EditText txtusername, txtpassword;
    Button bt_login;
    TextView tv_register;
    String username, password;
    RequestQueue requestQueue;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setTitle("Bienvenido a E-pay"); //set title of the activity
        txtusername = (EditText) findViewById(R.id.txtusername);
        txtpassword = (EditText) findViewById(R.id.txtpassword);
        bt_login = (Button) findViewById(R.id.bt_login);
        tv_register = (TextView) findViewById(R.id.tv_register);

        requestQueue = Volley.newRequestQueue(LoginActivity.this);//Creating the RequestQueue

        //proceso al hacer click al boton de entrar
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = txtusername.getText().toString();
                password = txtpassword.getText().toString();


                if (validateUsername(username) && validatePassword(password)) { //Username and Password Validation
                    final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);

                    progressDialog.setTitle("Por favor aguarda un momento");
                    progressDialog.setMessage("Ingresando al sistema");
                    progressDialog.setCancelable(false);
                    progressDialog.show();

                    LoginRequest loginRequest = new LoginRequest(username, password, new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            Log.i("Login Response", response);
                            //progressDialog.dismiss();

                            // Response from the server is in the form if a JSON, so we need a JSON Object
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (jsonObject.getBoolean("success")) {
                                    Intent loginSuccess = new Intent(LoginActivity.this, MainActivity.class);
                                    //Passing all received data from server to next activity
                                    loginSuccess.putExtra("nombre", jsonObject.getString("nombre"));
                                    //loginSuccess.putExtra("cedula", jsonObject.getString("cedula"));
                                    loginSuccess.putExtra("correo", jsonObject.getString("correo"));
                                    //loginSuccess.putExtra("saldoact", jsonObject.getString("saldoact"));
                                    //loginSuccess.putExtra("url", jsonObject.getString("pic"));
                                    startActivity(loginSuccess);
                                    finish();
                                } else {

                                    if(jsonObject.getString("status").equals("NOEXISTE")) {
                                        Toast.makeText(LoginActivity.this, "Tu correo no esta registrado, si no tienes cuenta, create una", Toast.LENGTH_LONG).show();
                                    }
                                    if
                                            (jsonObject.getString("status").equals("PASSWORD")){
                                        Toast.makeText(LoginActivity.this, "Hay un error en tu contraseña", Toast.LENGTH_SHORT).show();
                                    }
                                    if(jsonObject.getString("status").equals("NOVERIFICADO")) {
                                        Toast.makeText(LoginActivity.this, "Tu correo no ha sido verificado", Toast.LENGTH_LONG).show();
                                        Intent mostrarmensaje = new Intent(LoginActivity.this, ActivarCorreo.class);
                                        startActivity(mostrarmensaje);

                                    }



                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Toast.makeText(LoginActivity.this, "Bad Response From Server", Toast.LENGTH_SHORT).show();
                            }

                        }



                    });requestQueue.add(loginRequest);



                }
            }
        });





        // enlace si no tienes cuenta
        tv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, SignUp.class);
                startActivity(intent);
            }
        });


    }

    private boolean validateUsername(String string) {
        if (string.equals("")) {
            txtusername.setError("Ingresa tu correo");
            return false;
        } else if (string.length() > 120) {
            txtusername.setError("Máximo 120 Cáracteres");
            return false;
        }
        txtusername.setError(null);
        return true;
    }
    private boolean validatePassword(String string) {
        if (string.equals("")) {
            txtpassword.setError("Ingresa tu clave");
            return false;
        } else if (string.length() > 32) {
            txtpassword.setError("Maximo 32 Cáracteres");
            return false;
        } else if (string.length() < 8) {
            txtpassword.setError("Minimo 8 Cáracteres");
            return false;
        }
        txtpassword.setError(null);
        return true;
    }
}
    
asked by Jesus Moran 07.08.2017 в 20:28
source

2 answers

1

Good, I solved the problem to be able to use the variable temporarily during the execution of my application.

I created a file called Constantes.java

The code is as follows: class Constantes { public static String NOMBRE = ""; public static String CORREO = ""; public static String SALDO = ""; }

After the query json to my database, I store the values in those constants, which are available in any part of my application:

Constantes.NOMBRE=jsonObject.getString("nombre"); Constantes.CORREO=jsonObject.getString("correo"); Constantes.SALDO=jsonObject.getString("saldoact");

and to call them in any activity (used mostly with text boxes, what I do is a settext (constants.CORREO)

    
answered by 09.08.2017 / 18:41
source
0

Regarding your first question this happens because the activity once it is displayed on the screen is destroyed before resuming, so all the data you have on screen is lost. Another case in which the same thing can happen is when you rotate the screen.

For this, what you need is to store all the data before in the onSaveInstanceState () method and then recover them in onRestoreInstanceState () , assigning the values you want to persist in the bundle. These can be Obejetos, String, Integers, etc.

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("obj", myClass);  // Si se trata de un objeto
        outState.putString("llaveString", myString)  // Si es String
        outState.putInt("llaveEntero", myEntero)  // Si es un entero
    }

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    uper.onRestoreInstanceState(savedInstanceState);
    myClass = savedInstanceState.getParcelable("obj"));
    String myString = savedInstanceState.getParcelable("llaveString"));
    Integer myEntero = savedInstanceState.getParcelable("llaveEntero"));
}

In android what you must master is the control of the life cycle of the activities and fragments to avoid problems with this, yet I leave you this link where you'll find out more about how each method works.

I hope my answer has helped you, regards.

    
answered by 07.08.2017 в 22:07