Nitin
Nitin

Reputation: 27

How to get response from json using volley in android

I am post Json object data using volley libraries in my app but I want to get response from that request and update UI according to response and also show progressdialog while doing background process.how can I do that please tell me.

here is my code:-

public void postData() {
    try {
        getText();// get Input Text by the user
        String json;// storing json object

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("agentCode", s_szMobileNumber);
        jsonObject.put("pin", s_szOldPassword);
        jsonObject.put("newpin", s_szNewPassword);
        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();
        System.out.println("Server Request:-" + json);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, CServerAPI.s_szChangePassUrl, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void getText() {// getting text from editText.....
    s_szMobileNumber = m_MobileEditText.getText().toString().trim();// get mobile number from edit text
    s_szNewPassword = m_NewPassEditText.getText().toString().trim();// get  new pasword from edit Text
}

public void getResponse() throws JSONException {// method regarding condition.................
    if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
        s_szResponseNewPassword = m_oResponseobject.getString("newpin");// getting  new password response from server....
        CSnackBar.getInstance().showSnackBarSuccess(findViewById(R.id.mainLayout), "Password Changed Successfully", getApplicationContext());
        upDatePassword();// updating password in shared preference.......

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent login = new Intent(getApplicationContext(), CLoginScreen.class);
                startActivity(login);

            }
        }, 3500);


    } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
        CSnackBar.getInstance().showSnackBarError(findViewById(R.id.mainLayout), "User not found", getApplicationContext());
    } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("New Pin Can Not Be Empty")) {
        CSnackBar.getInstance().showSnackBarError(findViewById(R.id.mainLayout), "Enter valid password", getApplicationContext());
    } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
        CSnackBar.getInstance().showSnackBarError(findViewById(R.id.mainLayout), "Old pin not found", getApplicationContext());
    } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
        CSnackBar.getInstance().showSnackBarError(findViewById(R.id.mainLayout), "Enter valid mobile number", getApplicationContext());
    }
}

public void upDatePassword() {// Update old password from new password in shared preference ......
    m_Preferences = getApplicationContext().getSharedPreferences("LoginData", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = m_Preferences.edit();
    editor.putString("pin", s_szResponseNewPassword);
    editor.apply();
}

Upvotes: 0

Views: 2169

Answers (1)

Sathish Kumar J
Sathish Kumar J

Reputation: 4345

Try this on your onResponse

@Override
public void onResponse(JSONObject response) {
   Log.d("Response", response.toString());
   }

This may helps you.

EDIT 1 :

try following code,

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

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

import org.json.JSONException;
import org.json.JSONObject;

public class Login extends AppCompatActivity{

public static final String LOGIN_URL = "YOUR_URL";

ProgressDialog pDialog;

public static final String KEY_USERNAME="username";
public static final String KEY_PASSWORD="password";

private EditText editTextUsername;
private EditText editTextPassword; 
private Button buttonLogin;

private String username;
private String password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

        editTextUsername = (EditText) findViewById(R.id.editTextUsername);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);

        buttonLogin = (Button) findViewById(R.id.buttonLogin);

        buttonLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if(isNetworkAvailable()){
                userLogin();
                }
                else
                {
                    showMessageDialog("Error", "Check your Internet Connection..!");
                }
            }
        });
}

private void userLogin() {
    username = editTextUsername.getText().toString().trim();
    password = editTextPassword.getText().toString().trim();

    pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show(); 

    StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        //JSONArray myJSON= new JSONArray(response);

                            JSONObject parentObject = new JSONObject(response);
                            JSONObject childObject = parentObject.getJSONObject("Tracking"); 

                              String status = childObject.optString("status");
                              String type = childObject.optString("type");

                              //System.out.println("status : " + status);
                              //System.out.println("Type : " + type);

                                if(status.trim().equals("success"))
                                {
                                    pDialog.hide();
                                    showMessageDialog("Login", type + " Login Successfully..!");
                                }
                                else
                                {
                                    pDialog.hide();
                                    showMessageDialog("Login", "No Users/Admin were Found..! ");
                                }


                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                        pDialog.hide();
                        showMessageDialog("JSON Error", "Server Error..! Try after Some Time..!");//e.getMessage());
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) 
                {
                    pDialog.hide();
                    showMessageDialog("Login", "Reponse => " + error.toString());

                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> map = new HashMap<String,String>();
            map.put(KEY_USERNAME,username);
            map.put(KEY_PASSWORD,password);
            return map;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

public void showMessageDialog(String title , String Message)
{
    AlertDialog dialog = new AlertDialog.Builder(Login.this)
    .setTitle(title)
    .setMessage(Message)
    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            dialog.dismiss();

        }
    })

    .show();


}

  private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

}

Upvotes: 1

Related Questions