How do I return serverAnswer behind onResponse?
Because in onResponse, serverAnswer gets data, but behind onResponse it's an empty variable...
For example, if I try to show a Toast with serverAnswer in onResponse, it's alright, serverAnswer has data from JSON string. But if try to show a Toast with serverAnswer behind onResponse - I get an empty Toast.
And addUser returns an empty String too.
public String addUser(final String username, final String email, final String password, final Context context) {
StringRequest request = new StringRequest(
Request.Method.POST,
REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonObject = new JSONObject(response);
final JSONObject status = jsonObject.getJSONObject("Result");
serverAnswer = status.getString("Server answer");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverAnswer = error.getMessage();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(KEY_USERNAME, username);
params.put(KEY_EMAIL, email);
params.put(KEY_PASSWORD, password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(request);
return serverAnswer;
}
Related
I want to make an activity to change user profil. The received part which is based on JSON, is properly working. I have tested by set variable manually in PHP code. However, when I have posted the variable from android to php, it cannot receive it. Anyone can tell me the problem ?
public class ProfilActivity extends AppCompatActivity {
private EditText editTextNama, editTextEmail, editTextPassword, editTextNohp;
private Button Simpan;
private static final String PROFIL_URL = "http://vrai-dev.000webhostapp.com/koneksi_profil.php";
List<Profil> profilList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
Button back = (Button) findViewById(R.id.profil_back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ProfilActivity.this, MenuActivity.class);
startActivity(i);
}
});
profilList = new ArrayList<>();
getEmail();
editTextNama = (EditText) findViewById(R.id.profil_username);
editTextEmail = (EditText) findViewById(R.id.profil_email);
editTextPassword = (EditText) findViewById(R.id.profil_password);
editTextNohp = (EditText) findViewById(R.id.profil_nohp);
Simpan = (Button) findViewById(R.id.profil_simpan);
Simpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
updateProfil();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void getEmail(){
final String email = "a";
StringRequest stringRequest = new StringRequest(Request.Method.POST, PROFIL_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loadProfil();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("email", email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void loadProfil() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, PROFIL_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray profil = new JSONArray(response);
JSONObject profilObject = profil.getJSONObject(0);
String foto_user = profilObject.getString("foto_user");
String username = profilObject.getString("username");
String email = profilObject.getString("email");
String password = profilObject.getString("password");
String nohp = profilObject.getString("nohp");
Profil viewProfil = new Profil(foto_user, username, email, password, nohp);
profilList.add(viewProfil);
editTextNama.setText(username);
editTextEmail.setText(email);
editTextPassword.setText(password);
editTextNohp.setText(nohp);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProfilActivity.this, error.getMessage() + "Error Load Profil", Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
Had the same problem could not figure what was wrong, but this worked for, dont forget to add the dependency in the gradle file
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest(com.android.volley.Request.Method.POST, YOUR_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
// do work here
} catch (JSONException e) {
e.printStackTrace();
Log.d("Response", "failed: " + response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("title", title);
return params;
}
};
queue.add(postRequest);
** implementation 'com.he5ed.lib:volley:android-cts-5.1_r4'
**
Try to modify your loadProifle() method like below
// define below variable to globally
String mRequestBody=null;
private void loadProfil() {
try {
JSONObject jsonBody = new JSONObject();
jsonBody.put("namekey", "paste here name");
jsonBody.put("emailkey", "paste here email");
jsonBody.put("passkey", "paste here password");
jsonBody.put("nokey", "paste here number");
mRequestBody = jsonBody.toString();
}catch(JSONException e){
e.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, PROFIL_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray profil = new JSONArray(response);
JSONObject profilObject = profil.getJSONObject(0);
String foto_user = profilObject.getString("foto_user");
String username = profilObject.getString("username");
String email = profilObject.getString("email");
String password = profilObject.getString("password");
String nohp = profilObject.getString("nohp");
Profil viewProfil = new Profil(foto_user, username, email, password, nohp);
profilList.add(viewProfil);
editTextNama.setText(username);
editTextEmail.setText(email);
editTextPassword.setText(password);
editTextNohp.setText(nohp);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProfilActivity.this, error.getMessage() + "Error Load Profil", Toast.LENGTH_LONG).show();
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
Here is my php code for getting email variable.
Is there something wrong?
<?php
define('DB_HOST','Localhost');
define('DB_USER','id9815170_phpjember');
define('DB_PASS','phpjember');
define('DB_NAME','id9815170_phpjember');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
die('Unable to connect to database ' . mysqli_connect_error());
}
$email = $_POST['email'];
$stmt = $conn->prepare("SELECT foto_user, username, email, password, nohp FROM datauser WHERE email='$email';");
$stmt->execute();
$stmt->bind_result($foto_user, $username, $email, $password, $nohp);
$profil = array();
while($stmt->fetch()){
$temp = array();
$temp['foto_user'] = $foto_user;
$temp['username'] = $username;
$temp['email'] = $email;
$temp['password'] = $password;
$temp['nohp'] = $nohp;
array_push($profil, $temp);
}
echo json_encode($profil);
?>
I am trying to use Volley to send 3 strings to a php script that sends it to a localhost server. I have this so far;
RegisterRequest;
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://192.168.*.*:80/phptesting/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin,
Response.Listener<String> listener,
Response.ErrorListener errListener){
super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
This is CreateUser;
public class CreateUser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
this.setTitle("Create User");
final EditText username1 = findViewById(R.id.Createusername);
final EditText password1 = findViewById(R.id.CreatePassword);
final Switch isAdmin = findViewById(R.id.isadmin);
final Button createuser = findViewById(R.id.createuserbtn);
if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
isAdmin.setVisibility(View.GONE);
}
createuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response Value: ", response);
if (response.equals("success")){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
CreateUser.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
}
};Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), String.valueOf(error), Toast.LENGTH_SHORT).show();
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener,errorListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
}
Now, the only error im getting is an Undefined index. And thats because Volley isnt sending data to the php script. The php script does work properly when data is sent to it, so my question is this; what changes do i have to make to my script for it to send the 3 strings over?
Never mess with code or else it will be confusing for you to handle things properly.
So just make another class and use it in your activity.
Have a look at this class I have written, you can use it anywhere and for any type of data request.
public class SendData {
private Context context;
private String url;
private HashMap<String, String> data;
private OnDataSent onDataSent;
public void setOnDataSent(OnDataSent onDataSent) {
this.onDataSent = onDataSent;
}
public SendData(Context context, String url, HashMap<String, String> data) {
this.context = context;
this.url = url;
this.data = data;
}
public void send(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(onDataSent != null){
onDataSent.onSuccess(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(onDataSent != null){
onDataSent.onFailed(error.toString());
}
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.putAll(data);
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, 0));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
public interface OnDataSent{
void onSuccess(String response);
void onFailed(String error);
}
}
And now you can easily use it from any activity. Just give data in the constructor and use the interface to track the events this way
HashMap<String, String> data = new HashMap<>();
data.put("username", "");//define the value
data.put("password", "");//define the value
data.put("is_admin", "");//define the value
SendData sendData = new SendData(this, "", data); //defie the context and url properly
sendData.setOnDataSent(new SendData.OnDataSent() {
#Override
public void onSuccess(String response) {
//parse the response
}
#Override
public void onFailed(String error) {
//something went wrong check the error
}
});
sendData.send();
I want to use from open street map API
when i send request to Reverse Geo coding Api with volley
This error is displayed
com.android.volley.authfailureerror
But this API don't need to any token
this is my Code:
String url = "https://nominatim.openstreetmap.org/reverse?format=json&lat="+lat+"&lon="+lng;
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try
{
JSONObject address = response.getJSONObject("address");
final String city = address.getString("town");
final String county = address.getString("county");
selectcity = true;
String temp = county.substring(county.indexOf(" "),county.length());
ed.putString("lat", lat+"");
ed.putString("lng", lng+"");
ed.putString("location", temp);
ed.apply();
progressDialog.dismiss();
RequestQueue mRequestQueue;
mRequestQueue =AppController.getInstance().getRequestQueue();
mRequestQueue.cancelAll("AppController");
locationManager.removeUpdates(LocationActivity.this);
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Erorr", Toast.LENGTH_LONG).show();
RequestQueue mRequestQueue;
mRequestQueue =AppController.getInstance().getRequestQueue();
mRequestQueue.cancelAll("AppController");
progressDialog.dismiss();
locationManager.removeUpdates(LocationActivity.this);
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
RequestQueue mRequestQueue;
mRequestQueue =AppController.getInstance().getRequestQueue();
mRequestQueue.cancelAll("AppController");
progressDialog.dismiss();
locationManager.removeUpdates(LocationActivity.this);
}
};
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, listener, errorListener){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
headers.put("accept-language", "fa");
return headers;
}
};
request.setTag("AppController");
AppController.getInstance().addToRequestQueue(request);
In addition when I use from this URL in postman It works correctly
try this way
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.GET, Your_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("===","onErrorResponse "+error)
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
Log.d("===","AuthFailureError");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
try {
} catch (Exception e) {
}
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
stringRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 50000;
}
#Override
public int getCurrentRetryCount() {
return 50000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
requestQueue.add(stringRequest);
I am making a post request in Android studio using string request, when I debug,i get no error. I don't get the JSON object in the code when i debug. It skips the login request and debug is ended.if I'm not doing something correct.please try and correct it
This is the JSON object
{"RESPONSECODE":200,
"RESPONSEDATA:[{"id_User":"120","FirstName":"King",
"LastName":"Dosty","Role_Id":"2","Email":"donmister5000#gmail.com","location":null,"Password":"$2y$10$fJJH6qOuhhXaDadHQhZefemBwHPZ3aHid\/WF579DwVJo8XyVGaEN6",
}],"Success":true}
This is the loginRequest java class
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://localhost/project/index.php/clientapinew/post_login2";
private Map<String, String> params;
public LoginRequest(String Email,String Password, Response.Listener<String> listener){
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("Email", Email);
params.put("Password", Password);
}
#Override
public Map<String, String> getParams(){
return params;
}
}
This is the login button to sent the request on click in the activity
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = emailEdt.getText().toString();
String Password = passwordEdt.getText().toString();
LoginRequest loginRequest = new LoginRequest(Email, Password,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
Log.d(TAG, jsonResponse.getString("SUCCESS"));
boolean success = jsonResponse.getBoolean("SUCCESS");
if (success)
{
Intent intent = new Intent (LoginActivity.this,MainActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this, "Login Successful",
Toast.LENGTH_SHORT).show();}
else {
AlertDialog.Builder builder = new
AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed").setNegativeButton("Retry", null)
.create().show();
}
}
catch (JSONException e)
{ e.printStackTrace();}}
});
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
This is the url get and the params when i debug
[ ] localhost/project/index.php/clientapinew/post_login2
0x59c3b57d NORMAL null
Email : john#gmail.com
Password: azerty
I'd suggest you ditch the LoginRequest Class, and add this method in your LoginActivity:
private void login(final String email, final String password){
String LOGIN_REQUEST_URL = "http://localhost/project/index.php/clientapinew/post_login2";
// JSON data
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put("Email", email);
jsonObject.put("Password", password);
} catch (JSONException e){
e.printStackTrace();
}
// Json request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
LOGIN_REQUEST_URL,
jsonObject,
new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject response){
//Toast.makeText(context, "Product successfully added", Toast.LENGTH_SHORT).show();
try{
//use the response JSONObject now like this log
Log.d(TAG, response.getString("Success"));
boolean success = response.getBoolean("Success");
if (success) {
//...
}
} catch (JSONException e) {
System.out.println("Error logging in");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Toast.makeText(LoginActivity.this, "Can't connect to Internet. Please check your connection.", Toast.LENGTH_LONG).show();
}
else if (error instanceof ServerError) {
Toast.makeText(LoginActivity.this, "Unable to login. Either the username or password is incorrect.", Toast.LENGTH_LONG).show();
}
else if (error instanceof ParseError) {
Toast.makeText(LoginActivity.this, "Parsing error. Please try again.", Toast.LENGTH_LONG).show();
}
else if (error instanceof NoConnectionError) {
Toast.makeText(LoginActivity.this, "Can't connect to internet. Please check your connection.", Toast.LENGTH_LONG).show();
}
else if (error instanceof TimeoutError) {
Toast.makeText(LoginActivity.this, "Connection timed out. Please check your internet connection.", Toast.LENGTH_LONG).show();
}
//Do other stuff if you want
error.printStackTrace();
}
}){
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String,String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
3600,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueueSingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
And then your onClick should look something like
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = emailEdt.getText().toString();
String Password = passwordEdt.getText().toString();
login(Email, Password);
}
}
Create RequestQueueSingleton.java class and use something like this:
public class RequestQueueSingleton {
private static RequestQueueSingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private RequestQueueSingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized RequestQueueSingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new RequestQueueSingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}
The first character in the response is ">". When it tries to run this line:
JSONObject jsonResponse = new JSONObject(response);
It can't find a JsonObject in the response and your code won't work.
My suggestion is to remove ">" from your response and try again.
I am able to consume api via volley library which use normal get post method but my php team just changed my api which accept json . i know there is is JsonObjectrequest in volley but i don't know how to put parameters in `JsonObjectRequest. Any help is appriciated.
PHP API
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$data_back = json_decode(file_get_contents('php://input'));
header("Content-type: application/json");
require "conn.php";
$id = $data_back->{"id"};
$address = $data_back->{"address"};
$pincode = $data_back->{"pincode"};
$name = $data_back->{"name"};
$mobile = $data_back->{"mobile"};
$sql = "UPDATE tbl_addressbook SET name = '$name', address = '$address', pincode = '$pincode', mobile = '$mobile' WHERE id = $id";
if(mysqli_query($conn,$sql)){
echo 'Address Book Updated Successfully';
}
else{
echo 'Could Not Update Your Address Book';
}
}
?>
Volley Request
StringRequest stringRequest=new StringRequest(Request.Method.POST, Config.UPDATE_ADDRESS_BOOK,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(mContext,"Address Changed",Toast.LENGTH_LONG).show();
list.set(getAdapterPosition(),new AddressBookModel(bookModel.getId(),
etName.getText().toString(),
etAddress.getText().toString(),
etPinCode.getText().toString(),
etPhone.getText().toString(),
bookModel.getDefAddress()));
d.dismiss();
progress.dismiss();
((Activity)mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext,"Something Went Wrong \n ttry again later",Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map=new HashMap<String, String>();
map.put("id",bookModel.getId());
map.put("name",etName.getText().toString());
map.put("address",etAddress.getText().toString());
map.put("pincode",etPinCode.getText().toString());
map.put("phone",etPhone.getText().toString());
return checkParams(map);
}
private Map<String, String> checkParams(Map<String, String> map){
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
if(pairs.getValue()==null){
map.put(pairs.getKey(), "");
}
}
return map;
}
};
VolleySingleton.getInstance(mContext).addToRequestQueue(stringRequest);
Easy cheesy lemon squeezy!
Some code
HashMap<String, String> params = new HashMap<String, String>();
params.put("id", "300");
params.put("address", "Mars");
params.put("pincode", "***");
params.put("name", "Jon Skeet");
params.put("mobile", "911");
JsonObjectRequest request = new JsonObjectRequest(
/*URL*/,
new JSONObject(params),
new Response.Listener<JSONObject>(){/*...*/});
First Create your JsonObject like
JSONObject js = new JSONObject();
try {
js.put("email", "adasda");
js.put("address", "adasd");
js.put("pincode", "adadasd");
}catch (JSONException e) {
e.printStackTrace();
}
Then your JSON request, take a careful look at get headers.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
private void getWalletDetails(){
final ProgressDialog pDialog; // = new ProgressDialog(mcontext);
StringRequest stringRequest;
pDialog = GifDialog.ctor(mcontext);
pDialog.show();
stringRequest = new StringRequest(Request.Method.POST, place your url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
pDialog.dismiss();
//Showing toast message of the response
try {
JSONObject jsonObject = new JSONObject(s);
totbal.setText("\u20B9 "+jsonObject.getString("avail_balance"));
JSONArray jsonArray = jsonObject.getJSONArray("tx_detail");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
mode = new Model_Wallet_Transaction();
mode.setStr1(object.getString("date"));
mode.setStr4(object.getString("insert_time"));
mode.setStr2(object.getString("name"));
mode.setStr3(object.getString("transaction_id_no"));
mode.setAmount(object.getString("amount"));
mode.setTxtype(object.getString("tx_type"));
modlist.add(mode);
}
// Collections.sort(modlist, new StringDateComparator());
adp = new CustomAdapter_Wallet_Transaction(getApplicationContext(), modlist);
list.setAdapter(adp);
} catch (Exception e) {
Log.e("Error", e.toString());
}
// Toast.makeText(Wallet_Transaction.this, s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
pDialog.dismiss();
//Showing toast
//Toast.makeText(Wallet_Transaction.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put("user_id", UserId);
params.put("deviceId", DeviceId);
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}