Search code examples
androidjsoncompiler-errorsandroid-volleyresponse

Android Volley Response


I am trying to create a simple login and if it is successful, I am trying to save the response userid (uid) into the shared preferences. Below is the part of my loginActivity.java and the error messages are:

Error 1

error: incompatible types: int cannot be converted to String
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, Config.LOGIN_URL, null, new Response.Listener<JSONObject>() {

Error 2

error: cannot find symbol
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,Config.LOGIN_URL, null, new Response.Listener<JSONObject>() {
                                   ^

symbol: constructor (int,String,,>)

LoginActivity.java

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONObject;

import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    //Defining views
    private EditText editTextTCNO;
    private EditText editTextMobile;
    private AppCompatButton buttonLogin;

    //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);

        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();

        //Initializing views
        editTextTCNO = (EditText) findViewById(R.id.editTextTCNO);
        editTextMobile = (EditText) findViewById(R.id.editTextMobile);

        buttonLogin = (AppCompatButton) findViewById(R.id.loginButton);

        //Adding click listener
        buttonLogin.setOnClickListener(this);
    }

    @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);

        //If we will get true
        if(loggedIn){
            //We will start the Profile Activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
        }
    }

    private void login() {
        //Getting values from edit texts
        final String tcno = editTextTCNO.getText().toString().trim();
        final String mobile = editTextMobile.getText().toString().trim();
        final String operation = "login";

        //Creating a string request
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, Config.LOGIN_URL, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                String smsg = response.getString("msg");
                String pid = response.getString("uid");

                //If we are getting success from server
                if(smsg == Config.LOGIN_SUCCESS){
                    //Creating a shared preference
                    SharedPreferences sharedPreferences = LoginActivity.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.UID_SHARED_PREF, pid);

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

                    //Starting profile activity
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                }else{
                    //If the server response is not success
                    //Displaying an error message on toast
                    Toast.makeText(LoginActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
                }
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                //Adding parameters to request
                params.put(Config.KEY_TCNO, tcno);
                params.put(Config.KEY_MOBILE, mobile);
                params.put(Config.KEY_OPERATION, operation);

                //returning parameter
                return params;
            }
        };

        //Adding the string request to the queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(jsonObjReq);

    }

    @Override
    public void onClick(View v) {
        //Calling the login function
        login();
    }
}

Solution

  • this is my fully functional way to make a volley request, hope it helps

    private JSONObject LoginJson()
    {
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("Username", "testUser");
            jsonBody.put("Password", "123456");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonBody;
    }
    public boolean identificarce ()
    {
        RequestFuture<JSONObject> future = RequestFuture.newFuture();
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL.ServicioLogging, this.LoginJson(), future, future);
    
        QueuHolder.getInstance(Login.contexto).getRequestQueue().add(request);
        try {
            JSONObject response = future.get();
            try
            {
                String NombreCompleto = response.getString("NombreCompleto");
                int id = response.getInt("id");
                //save results in shared preferences
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
        return true;
    }