What Would Be The Simplest Way Of Posting Data Using Volley?
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 StringRe
Solution 1:
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.
publicclassSendData {
privateContext context;
privateString url;
privateHashMap<String, String> data;
privateOnDataSent onDataSent;
publicvoidsetOnDataSent(OnDataSent onDataSent) {
this.onDataSent = onDataSent;
}
publicSendData(Context context, String url, HashMap<String, String> data) {
this.context = context;
this.url = url;
this.data = data;
}
publicvoidsend(){
StringRequest stringRequest = newStringRequest(Request.Method.POST, url, newResponse.Listener<String>() {
@OverridepublicvoidonResponse(String response) {
if(onDataSent != null){
onDataSent.onSuccess(response);
}
}
}, newResponse.ErrorListener() {
@OverridepublicvoidonErrorResponse(VolleyError error) {
if(onDataSent != null){
onDataSent.onFailed(error.toString());
}
}
}){
@OverrideprotectedMap<String, String> getParams() throws AuthFailureError {
Map<String, String> map = newHashMap<>();
map.putAll(data);
return map;
}
};
stringRequest.setRetryPolicy(newDefaultRetryPolicy(0, 0, 0));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
publicinterfaceOnDataSent{
voidonSuccess(String response);
voidonFailed(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 = newHashMap<>();
data.put("username", "");//define the value
data.put("password", "");//define the value
data.put("is_admin", "");//define the valueSendData sendData = newSendData(this, "", data); //defie the context and url properly
sendData.setOnDataSent(newSendData.OnDataSent() {
@OverridepublicvoidonSuccess(String response) {
//parse the response
}
@OverridepublicvoidonFailed(String error) {
//something went wrong check the error
}
});
sendData.send();
hope it helps
happy coding
if some problem occur lemme Know :)
Post a Comment for "What Would Be The Simplest Way Of Posting Data Using Volley?"