Android query - Volley

0

Good I need help with something that I can not do, it turns out that I have a login in my application that calls a class WSUsuarios that basically what it does is connect to a web service and rescue the data from this and save them in my internal db of my application and it turns out that I try to get this class - method to return true or false according to the data that is sent but it always returns "empty" and I do not know why it could be, someone can tell me what my error is or what is what I do not see PS: ALTHOUGH I RETURN THE BOOLEAN EMPTY IF IT RESCTS THE DATA FROM THE WEBSERVICE AND I SAVE THEM IN MY DB, WHAT I WANT IS TO RETURN ME THE TRUE OR FALSE ACCORDING TO THE CASE

since thank you very much

WSUSuarios

public class WSUsuarios {

final String URL = "URL WEB SERVICE";
String  REQUEST_TAG = "cne.desarrollo.facturacion.WebServices";

// VARIABLE QUE VA A RESCATAR LOS DATOS QUE TRAEL EL USUARIO LOGEADO
ArrayList<Usuarios> usuarioLogeadoDatos = new ArrayList<>();

// VARIABLE RUTURN
Boolean respuesta;

public Boolean GetUsuarios(final Context context, String username, String password, String rut)
{
    // REVISAMOS SI LA DB EXISTE EN CASO CONTRARIO LA CREAMOS
    final ConexionSQLiteHelper conn = new ConexionSQLiteHelper(context,"database",null,1);

            String usuarioBD = username;
            final String Userbase64 = Base64.encodeToString(usuarioBD.getBytes(), Base64.DEFAULT);

            String passwordBD = password;
            final String Passwordbase64 = Base64.encodeToString(passwordBD.getBytes(), Base64.DEFAULT);

            String rutEmpresaBD = rut;
            final String rutEmpresabase64 = Base64.encodeToString(rutEmpresaBD.getBytes(), Base64.DEFAULT);

            HashMap<String, String> params = new HashMap<String, String>();
            params.put("usuario", Userbase64);
            params.put("password", Passwordbase64);
            params.put("rut_empresa", rutEmpresabase64);

            JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            //RECIBIENDO LOS DATOS DESDE EL SERVIDOR

                            try{
                                //DECLARAMOS LAS VARIABLES TIPO JSONARRAY
                                JSONArray Registros = null;
                                JSONArray ResgitrosOne[] = null;
                                JSONArray[] usuarios = {null};

                                // SI LOS TADOS ENVIADOS SON INCORRECTOS SE ENVIA UN MENSAJE DE ERROR
                                if (  response.getString("Glosa").equals("Problema con usuario y contrasena")  ){
                                    Toast.makeText(context, "Usuario/Contraseña incorrectos", Toast.LENGTH_LONG).show();
                                    respuesta = false;
                                }
                                // LOS DATOS ENVIADOS COINCIDEN CON EL WEB SERVICE
                                else{
                                    JSONArray jsonArray = response.getJSONArray("USUARIOS");

                                    // RECORRER EL JSONARRAY Y GUARDARLO EN UNA VARIABLE TIPO ARRAYLIST<USUARIOS>
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        usuarioLogeadoDatos.add(new Usuarios(jsonArray.getJSONObject(i)));
                                    }

                                    // AGREGAMOS LOS USUARIOS A LA DATABASE INTERNA
                                    SQLiteDatabase db = conn.getWritableDatabase();
                                    ContentValues values = new ContentValues();

                                    // RECORREMOS LOS DATOS TRAIDOS DESDE EL JSONARRAY Y LOS INSERTAMOS EN LA BD
                                    for (int i = 0; i < jsonArray.length(); i++){
                                        values.put(Utilidades.CAMPO_ID_USUARIOS,usuarioLogeadoDatos.get(i).getId());
                                        values.put(Utilidades.CAMPO_RUT_USUARIOS,usuarioLogeadoDatos.get(i).getRut());
                                        values.put(Utilidades.CAMPO_USERNAME_USUARIOS,usuarioLogeadoDatos.get(i).getUsuario());
                                        values.put(Utilidades.CAMPO_PASSWORD_USUARIOS,usuarioLogeadoDatos.get(i).getPassword());
                                        values.put(Utilidades.CAMPO_ID_EMPRESA_USUARIOS,usuarioLogeadoDatos.get(i).getId_empresa());

                                        // INSERTA LOS DATOS EN LA BASE DE DATOS SQLITE
                                        db.insert(Utilidades.TABLA_USUARIOS,Utilidades.CAMPO_ID_USUARIOS,values);
                                    }

                                    // CERRAMOS LA CONEXION A LA DB
                                    db.close();

                                    respuesta = true;

                                }

                            }catch (JSONException e){
                                e.printStackTrace();
                                respuesta = true;
                            }

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.e("Error: ", error.getMessage());
                    respuesta = true;
                }
            });

            AppSingleton.getInstance(context).addToRequestQueue(req,REQUEST_TAG);

    return respuesta;
}

LoginActivity

public class LoginActivity extends AppCompatActivity {

public Button btnLogin;

public EditText password;
public AutoCompleteTextView username,rut;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    // RECOGER LOS DATOS DEL FORMULARIO
    btnLogin = (Button) findViewById(R.id.btnLogin);
    username = (AutoCompleteTextView)findViewById(R.id.txtUsername);
    rut = (AutoCompleteTextView)findViewById(R.id.txtRutEmpresa);
    password = (EditText)findViewById(R.id.txtPassword);

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

            // PRIMER LOGIN, RESCATAR LOS DATOS DEL WEB SERVICE Y DESCARGARLOS A LA BASE DE DATOS LOCAL
            WSUsuarios objWSUsuarios = new WSUsuarios();
            Boolean rescatarUsurios = objWSUsuarios.GetUsuarios(LoginActivity.this,username.getText().toString(),password.getText().toString(),rut.getText().toString());

        }
    });
}
    
asked by Ignacio Fuentes 08.09.2018 в 22:18
source

1 answer

0

Your error is in the way you return the response value. Initially you declare the variable replaced without any value. Then you call

AppSingleton.getInstance(context).addToRequestQueue(req,REQUEST_TAG);
return respuesta;

But volley is asynchronous and the thread does not stop at the getInstance, so the response still has no value and does not return anything.

To solve this I put a progressbar with the blank screen and when the Volley ends (in the Response or Response Error) I remove the progressbar.

    
answered by 09.09.2018 в 10:47