Obtain remote data using Loopj

1

I am using loopj to log in and register using a remote WebService that uses MySQL to store data. I have the WebService configured so that when a user logs me, I get a response in the "Json" type object format:

{
"estado": 1
"ususrio": {
  "user_name": "antonio"
  "user_email": "[email protected]"
  "claveApi": "1b0f21451af767eba3cee46b18caaa74"
  }
}

If the answer is 200 ok then the login is correct. It works well for me, but now I would like to use one of the parameters returned by the server, specifically I would like to use the "Api key " to store it in a constant and treat it in another class within the same app. I would appreciate if someone could give me an example of how to do it.

Code of my login: (Ps the login is framed within a drawer design)

public class Login extends AppCompatActivity implements View.OnClickListener {

//Defining views
private EditText editTextEmail;
private EditText textUser_pass;
private AppCompatButton btnLogin;
private AppCompatButton btnLinkToRegisterScreen;
private AppCompatButton Returning;
private CookieStore cookieStore;
private DrawerLayout drawerLayout;

// Progress Dialog Object
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object

private static final String LOGIN_URL = "http://wi-sen.esy.es/wisen/Sensores/v1/usuarios/login";

//boolean variable to check user is logged in or not
//initially it is false
private boolean loggedIn = false;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    agregarToolbar();

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

    if (navigationView != null) {
        prepararDrawer(navigationView);
        // Seleccionar item por defecto
        seleccionarItem(navigationView.getMenu().getItem(0));
    }

    // Find Error Msg Text View control by ID
    errorMsg = (TextView) findViewById(R.id.login_error);
    // Instantiate Progress Dialog object
    prgDialog = new ProgressDialog(this);
    // Set Progress Dialog Text
    prgDialog.setMessage("Please wait...");
    // Set Cancelable as False
    prgDialog.setCancelable(false);



    //Initializing views
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    textUser_pass = (EditText) findViewById(R.id.textUser_pass);


    btnLogin = (AppCompatButton) findViewById(R.id.btnLogin);
    btnLinkToRegisterScreen = (AppCompatButton) findViewById(R.id.btnLinkToRegisterScreen);
    Returning = (AppCompatButton) findViewById(R.id.Returning);

    //Adding click listener
    btnLogin.setOnClickListener(this);
    btnLinkToRegisterScreen.setOnClickListener(this);
    Returning.setOnClickListener(this);
}

private void agregarToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final ActionBar ab = getSupportActionBar();
    if (ab != null) {
        // Poner ícono del drawer toggle
        ab.setHomeAsUpIndicator(R.drawable.drawer_toggle);
        ab.setDisplayHomeAsUpEnabled(true);
    }

}
private void prepararDrawer(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    menuItem.setChecked(true);
                    seleccionarItem(menuItem);
                    drawerLayout.closeDrawers();
                    return true;
                }
            });

}
private void seleccionarItem(MenuItem itemDrawer) {
    Fragment fragmentoGenerico = null;

    FragmentManager fragmentManager = getSupportFragmentManager();




    switch (itemDrawer.getItemId()) {

        case R.id.item_web:

            startActivity(new Intent(this, com.amg_eservices.appiot.SaltoWeb.WebOficial.class));
            break;


        case R.id.item_categorias:
            startActivity(new Intent(this, com.amg_eservices.appiot.MisSensores.ui.ActividadListaObjeto.class));
            break;

        case R.id.item_acceso:
            startActivity(new Intent(this, com.amg_eservices.appiot.RegistroyAcceso.MainActivity.class));
            break;
    }
    if (fragmentoGenerico != null) {
        fragmentManager
                .beginTransaction()
                .replace(R.id.contenido_principal, fragmentoGenerico)
                .commit();


    }

    // Setear titulo actual
    setTitle(itemDrawer.getTitle());
}

@Override
protected void onResume() {
    super.onResume();
    //In onresume fetching value from sharedpreference
    SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

    //Fetching the boolean value form sharedpreferences
    loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);

}


@Override
public void onClick(View v) {
    //Calling the login function
    if (v == btnLogin) {
        login(v);
    }
    if (v == btnLinkToRegisterScreen) {
        startActivity(new Intent(this, MainActivity.class));
    }
    if (v == Returning) {
        startActivity(new Intent(this, com.amg_eservices.appiot.MainActivity.class));
    }


}


private void login(View v) {
    //Getting values from edit texts
    //final String txt_umail = editTextEmail.getText().toString().trim();
    //final String txt_upass = textUser_pass.getText().toString().trim();

    final String user_email = editTextEmail.getText().toString().trim();
    final String contrasena = textUser_pass.getText().toString().trim();

    // Instantiate Progress Dialog object
    prgDialog = new ProgressDialog(this);
    // Set Progress Dialog Text
    prgDialog.setMessage("Please wait...");
    // Set Cancelable as False
    prgDialog.setCancelable(false);

    //Creating a shared preference
    SharedPreferences sharedPreferences = Login.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

    //Creating editor to store values to shared preferences
    SharedPreferences.Editor editor = sharedPreferences.edit();

    //Adding values to editor
    editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
    //editor.putString(Config.EMAIL_SHARED_PREF, user_mail);
    editor.putString(Config.EMAIL_SHARED_PREF, user_email);

    //Saving values to editor
    editor.commit();

    LoginLoopj(user_email, contrasena);

}

//LoginLoopj(user_email, contrasena);
// TODO: 09/05/16 make the http call loopj here

private void LoginLoopj(String user_email, String contrasena) {

    AsyncHttpClient client = new AsyncHttpClient();

    JSONObject jsonParams = new JSONObject();
    StringEntity entity = null;
    try {
        jsonParams.put(UtilitiesGlobal.USER_EMAIL, user_email);
        // Put Http parameter password with value of Password Edit View control
        jsonParams.put(UtilitiesGlobal.USER_PASSWORD, contrasena);

        entity = new StringEntity(jsonParams.toString());
        entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));



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

    // When Name Edit View, Email Edit View and Password Edit View have values other than Null

    if (Utility.isNotNull(user_email) && Utility.isNotNull(contrasena)) {
        if (Utility.validate(user_email)) {
            // Put Http parameter name with value of Name Edit View control

            LoginLoopj(user_email, contrasena);
        }

    } else {
        Toast.makeText(getApplicationContext(), "Please enter valid email or blank spaces", Toast.LENGTH_LONG).show();
    }

    // client.post(REGISTER_URL, params, new AsyncHttpResponseHandler() {
    // Invoke RESTful Web Service with Http parameters
    RequestHandle post = client.post(this, LOGIN_URL, entity, "application/json", new AsyncHttpResponseHandler() {
        @Override
        public void onStart() {
            // called before request is started
        }

        @Override

        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            // called when response HTTP status is "200 OK"
            String responseStr = null;
            try {



                responseStr = new String(response, "UTF-8");


            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + responseStr);

            Toast toast1 =
                    Toast.makeText(getApplicationContext(),
                            R.string.Logeo_exitoso, Toast.LENGTH_LONG);

            toast1.show();



            Intent intent = new Intent(Login.this, ProfileActivity.class);
            startActivity(intent);
        }

        @Override

        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)
            // Hide Progress Dialog
            prgDialog.hide();
            // When Http response code is '404'
            if (statusCode == 404) {
                Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
            }
            // When Http response code is '500'
            else if (statusCode == 500) {
                Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
            }
            // When Http response code other than 404, 500
            else {
                Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
            }
        }

    });


}
public void navigatetoLoginActivity(View view) {
    Intent loginIntent = new Intent(getApplicationContext(), Login.class);
    // Clears History of Activity
    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(loginIntent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_actividad_principal, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            drawerLayout.openDrawer(GravityCompat.START);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

}

So far the file was unmodified. Now I have changed the onSuccess part as follows:

 public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            // called when response HTTP status is "200 OK"
            String responseStr = null;
            JSONObject jsonobject = null;

            try {


                responseStr = new String(response, "UTF-8");


                jsonobject = new JSONObject(responseStr);
                String claveApi = jsonobject.getString("claveApi");
                Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + jsonobject + claveApi);

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


            Toast toast1 =
                    Toast.makeText(getApplicationContext(),
                            R.string.Logeo_exitoso, Toast.LENGTH_LONG);

            toast1.show();


            Intent intent = new Intent(Login.this, ProfileActivity.class);
            startActivity(intent);
        }

And the error that appears in the log is that the Api key does not have values, it is as if it did not recognize the server's response, before in the log if it told me that it had the data of "state, user_name, user_email and Api key. ": Log

An Object within another object

This modification gives the following error.

Code:

  public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            // called when response HTTP status is "200 OK"
            JSONObject jsonobject = null;
            String claveApi = "";


            try {
                jsonobject = new JSONObject(String.valueOf(response));
                JSONObject usuarioiJSONbject = jsonobject.getJSONObject("usuario");
                claveApi = usuarioiJSONbject.getString("claveApi");

                Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + jsonobject + claveApi);

            }
            catch (JSONException e) {
                e.printStackTrace();
            }
            Intent intent = new Intent(Login.this, ProfileActivity.class);
            startActivity(intent);
        }

LOG

06-06 22:30:09.973 4709-4709/? W/System.err: org.json.JSONException: Unterminated array at character 11 of [B@3dc20986
06-06 22:30:09.977 4709-4709/? W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
06-06 22:30:09.977 4709-4709/? W/System.err:     at org.json.JSONTokener.readArray(JSONTokener.java:440)
06-06 22:30:09.978 4709-4709/? W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:103)
06-06 22:30:09.978 4709-4709/? W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:156)
06-06 22:30:09.978 4709-4709/? W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
06-06 22:30:09.990 4709-4709/? W/System.err:     at com.amg_eservices.appiot.RegistroyAcceso.Login$2.onSuccess(Login.java:308)
    
asked by Oscar C. 05.06.2016 в 23:32
source

2 answers

-1

I think your question goes from parsing the data, saving it and reusing it in a class:

Ok, the answer .Json can be of two types:

  • If the .json starts with {it is considered as Json object.
  • If the .json starts with [it is considered as Json Arrangement.

In your case it seems to be an object, then to get the Key API value:

        JSONObject jsonobject = null;
        try {
            jsonobject = new JSONObject(jsonString);
            String claveApi = jsonobject.getString("claveApi");
        }
        catch (JSONException e) {
            e.printStackTrace();
        }

Now you can save the value in preferences, I recommend this link where there are methods to add and obtain the values of a preference, to obtain the values of the API Key simply use the getValuePreference() method.

Update:

Get the value within an object that in turn is inside another:

If we review the object carefully we can realize that claveApi is actually inside another object usuario

{
"estado": 1
"usuario": {
            "user_name": "antonio"
            "user_email": "[email protected]"
            "claveApi": "1b0f21451af767eba3cee46b18caaa74"
          }
}

In this case we first obtain the main object, then we obtain the object usuario and at the end we obtain the value of claveApi :

    JSONObject jsonobject = null;
    String claveApi = "";
    try {
        jsonobject = new JSONObject(jsonString);            
        JSONObject usuarioiJSONbject = jsonobject.getJSONObject("usuario");
        claveApi = usuarioiJSONbject.getString("claveApi");
    }
    catch (JSONException e) {
        e.printStackTrace();
    }

With this you can easily obtain the value of claveApi : 1b0f21451af767eba3cee46b18caaa74

    
answered by 05.06.2016 / 23:41
source
0

According to Elenasys' response. I have tried your answer and it has worked correctly. Upon receiving a Json Object from the server, the code would look like this:

    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                // called when response HTTP status is "200 OK"
                String responseStr = null;
                try {
                    JSONObject jornada;
                    jornada = new JSONObject(String.valueOf(response));
                    String claveApi = jornada.getString("claveApi");

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

Now I'm going to work on sharepreferences to manipulate the data in question.

    
answered by 06.06.2016 в 01:54