I am sending some post data using volley. Here is my code . It's a snippet from background service. Let me know if you want other files also. I've added the internet permission.
public void onLocationChanged(final Location location) {
mCurrentLocation = location;
pref.setLocation(location);
String url = getResources().getString(R.string.hostname); // it's a normal http
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), "Location sent", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String errorMessage = "Err - data:"+error.getMessage();
Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERID,pref.getUserId());
params.put(KEY_LAT,String.valueOf(location.getLatitude()));
params.put(KEY_LNG,String.valueOf(location.getLongitude()));
return params;
}
};
queue.add(stringRequest);
}
Actually i saw that the one of the param UserId was having the Null value, That was creating the problem
Related
I am working with volley library in my android app development.
I have a base url and I need to append some value at the end of the url,click here,
So, this value "ZGxb87HuJK" keeps changing dynamically in my program and need to append this value at the end of url. How to add this in params?
Use this way.
StringRequest strreq = new StringRequest(Request.Method.GET,
"https://sample.com/testing/" + Hear Your dynamic value,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
// get response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
e.printStackTrace();
}
});
Volley.getInstance(this).addToRequestQueue(strreq);
String URL = "https://sample.com/testing/" + "dynamic value e.g ZGxb87HuJK";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL, null,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});
// Adding the request to the queue along with a unique string tag
MyApplication.getInstance().addToRequestQueue(jsonObjectReq, "getRequest");
Change your code like this
How to get first value of array using Volley in android? this method is successfully for me to get all value from array, but i just want to get first value only.
private void getValue(PriceModel priceModel, final ViewHolderPrice holder) {
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL + priceModel.get_id(),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(!response.isEmpty()) {
Gson gson = new Gson();
PriceModel[] priceModels = gson.fromJson(response, PriceModel[].class); for(PriceModel price: priceModels) holder.tvPrice.setText(variantModels.getPrice());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getLocalizedMessage());
}
}
);
Volley.newRequestQueue(mContext).add(request);
}
I am Creating an application which perform an OTP verification method..
I implemented the code as described in this link http://www.androidhive.info/2015/08/android-adding-sms-verification-like-whatsapp-part-2/
But when i click the NEXT button in app app is force closing
The function i get error is :
private void requestForSMS(final String name, final String email, final String mobile) {
StringRequest strReq = new StringRequest(Request.Method.POST,
Config.URL_REQUEST_SMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
// Parsing json object response
// response will be a json object
boolean error = responseObj.getBoolean("error");
String message = responseObj.getString("message");
// checking for error, if not error SMS is initiated
// device should receive it shortly
if (!error) {
// boolean flag saying device is waiting for sms
pref.setIsWaitingForSms(true);
// moving the screen to next pager item i.e otp screen
viewPager.setCurrentItem(1);
txtEditMobile.setText(pref.getMobileNumber());
layoutEditMobile.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Error: " + message,
Toast.LENGTH_LONG).show();
}
// hiding the progress bar
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
//Toast.makeText(getApplicationContext(),"Error: " + e.getMessage(),Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Log.e(TAG, "Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}) {
/**
* Passing user parameters to our server
* #return
*/
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("mobile", mobile);
//Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
Log is :
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.my.application.activity.SmsActivity.requestForSMS(SmsActivity.java:245)
at com.my.application.activity.SmsActivity.validateForm(SmsActivity.java:157)
at com.my.application.activity.SmsActivity.onClick(SmsActivity.java:117)
at android.view.View.performClick(View.java:4211)
at android.view.View$PerformClick.run(View.java:17446)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5336)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Volley library is used..
Any help??
public void confirmOTP() throws JSONException {
LayoutInflater lf = LayoutInflater.from(SignUp.this);
View view = lf.inflate(R.layout.confirm_dialog, null);
confirmButton = (Button) view.findViewById(R.id.buttonConfirm);
inputOTP = (EditText) view.findViewById(R.id.editTextOtp);
AlertDialog.Builder dialog = new AlertDialog.Builder(SignUp.this);
dialog.setView(view);
final AlertDialog alertDialog = dialog.create();
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);
confirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.dismiss();
final ProgressDialog load = ProgressDialog.show(SignUp.this, "Authenticating", "Please Wait ...", false, false);
load.setCanceledOnTouchOutside(false);
final String otp = inputOTP.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, ConfingDetalsActivity.CONFIRM_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Confirm Response Check>",response.toString());
String mesage;
try {
JSONObject jsonObject=new JSONObject(response);
mesage=jsonObject.getString("msg");
if(mesage.equals("success")){
Toast.makeText(SignUp.this, "Registerd sucessfully", Toast.LENGTH_LONG).show();
load.dismiss();
Intent in = new Intent(SignUp.this, SignupSucess.class);
startActivity(in);
} else {
load.dismiss();
Toast.makeText(SignUp.this, "Wrong OTP Please try again", Toast.LENGTH_SHORT).show();
confirmOTP();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
load.dismiss();
Toast.makeText(SignUp.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map params = new HashMap();
//Adding the parameters otp and username
params.put(ConfingDetalsActivity.KEY_OTP, otp);
if (businessFrag) {
} else {
params.put(ConfingDetalsActivity.CONSUMER_EMAIL, constant.EMAIl);
}
return params;
}
};
requestQueue.add(stringRequest);
}
});
}
public void register() {
Log.d("RegisterCalled>>>>>>>>>", "register");
final ProgressDialog load = ProgressDialog.show(SignUp.this, "Loading", "Pleas wait...", false, false);
load.setCanceledOnTouchOutside(false);
StringRequest request = new StringRequest(Request.Method.POST, ConfingDetalsActivity.REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response Check>>>",response.toString());
load.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String message=jsonObject.getString("msg");
if (message.equals("success")) {
confirmOTP();
} else {
Toast.makeText(SignUp.this, "User Name or phone already register", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
load.dismiss();
Toast.makeText(SignUp.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parms = new HashMap<String,String>();
if (businessFrag) {
parms.put(ConfingDetalsActivity.BUSINESS_ZIP_CODE, constant.B_ZIP_CODE);
parms.put(ConfingDetalsActivity.BUSINESS_INDUSTRY, constant.B_INDUSTRY);
parms.put(ConfingDetalsActivity.BUSINESS_PHONE, constant.B_MOBILE);
parms.put(ConfingDetalsActivity.BUSINESS_EMAIL, constant.B_EMAIl);
parms.put(ConfingDetalsActivity.BUSINESS_PASSWORD, constant.B_PASSSOWRD);
parms.put(ConfingDetalsActivity.SIGNUP_TYPE,"1");
} else {
parms.put(ConfingDetalsActivity.CONSUMER_FNAME, constant.F_NAME);
parms.put(ConfingDetalsActivity.CONSUMER_LNAME, constant.L_NAME);
parms.put(ConfingDetalsActivity.CONSUMER_PHONE, constant.MOBILE);
constant.EMAIl);
parms.put(ConfingDetalsActivity.CONSUMER_PASSWORD, constant.PASSSOWRD);
parms.put(ConfingDetalsActivity.SIGNUP_TYPE,"0");
}
return parms;
}
};
requestQueue.add(request);
}
I'm unable to get JSON Response when using Android Volley. No Error also No Succesfull response see (Log.d("logr=",_response);). I use StringRequest to get JSON text from Google Map API Android V2. Here're the code
private String urla = "https://maps.googleapis.com/maps/api/place/search/json?location=";
private String urlb = "&types=hotel&radius=500&sensor=false&key=YOUR_KEY";
#Override //::LocationListener (Interface)
public void onLocationChanged(Location location) {
//Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()), 13);
googleMap.animateCamera(cameraUpdate);
double x = location.getLatitude();
double y = location.getLongitude();
String request = urla+x+","+y+urlb;
Log.d("log1=",request);
StringRequest stringRequest = new StringRequest(Request.Method.GET, request,
new Response.Listener<String>() {
#Override
public void onResponse(String _response) {
Log.d("logr=",_response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Error handling
Log.d("log2=", error.toString());
Log.e("log3=", error.toString());
}
});
Toast.makeText(activity, "Update location user ==>" + mCurrentLocation.getLatitude() + "," + mCurrentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "Current Location :" + mCurrentLocation.getLatitude() + "," + mCurrentLocation.getLongitude());
}
Any Solution to this problem ?
Where do you actually excecute the request? You have to add() it to Volley's RequestQueue, otherwise the request does not get send at all.
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = urla + x + "," + y + urlb;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String _response) {
Log.d("logr=",_response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Error handling
Log.d("log2=", error.toString());
Log.e("log3=", error.toString());
}
});
//excecute your request
queue.add(stringRequest);
See more here: Learn volley
Try this:
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
final StringRequest stringRequest = new StringRequest(Request.Method.POST, urlString, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
strr = response;
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.hide();
Log.e("Volley", "ERROR");
}
});
requestQueue.add(stringRequest);
I want to pass a response outside of my classes (many classes)
public static void userLocation()
{
RequestQueue queue = Volley.newRequestQueue(context);
String url = "http://www.jobdiagnosis.com/iphone/userlocation.php";
StringRequest dr = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
//Toast.makeText(context, ""+response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error.
// Toast.makeText(getApplicationContext(), "error"+error, Toast.LENGTH_LONG).show();
Log.d("error", ""+error);
}
}
);
queue.add(dr);
}
Please suggest how I can pass a response outside of the class
In volly its difficult to return response outside the class.because request on server run in background and if we return value followed by queue.add(url) then it will return null.So there is no solution till now.Thanks!!