Android. Making a synchronous Request with RequestFuture get() and AsyncTask - android

i think i need some help with android volley. I am trying to make a simple HTTP request and wait for the response, because i need the response data for further processing. I have been trying for three days now, but wasn't able to get it done yet.
Basically i want to click a button -> make a request -> get a response -> handle it -> make a new request depending on the previous response -> handle the secon response -> and then show the results on my activity.
Is started the request in an AsysncTask as recommended but it always times out without response. I hope you can help me.
public class Connection extends AsyncTask<Object, Void, String>{
private static RequestQueue queue;
#Override
protected String doInBackground(Object... params) {
String response = null;
Context context = (Context) params[0];
String url = (String) params[1];
queue = getQueue(context.getApplicationContext());
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = new StringRequest(Request.Method.GET, url, future, future);
queue.add(request);
try {
response = future.get(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return response;
}
private static RequestQueue getQueue(Context context) {
if (queue == null) {
queue = Volley.newRequestQueue(context.getApplicationContext());
}
return queue;
}
}
The call is started from an extra Thread:
public class MyThread extends Thread {
#Override
public synchronized void start() {
super.start();
String url = UrlRequestGenerator.buildUrl(originLat, originLong, context); // context from calling activity
try {
response = new HAFASConnection().execute(context, url).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(response);
}
}

I did that recently but in the same thread. You could check first in the same thread if it works. If it doesn't, it means it could come from your url.
RequestQueue queue = Volley.newRequestQueue(getBaseContext());
String url ="http://....";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyError r = error;
}
});
queue.add(stringRequest);
If it goes on onErrorResponse, check your url and your server.

Related

Indeterminate Progress-Bar Situation

I added a progressbar as indeterminate state and put in a class extends asynctask.
In doInBackground method, i added one method (say m_one) with volley-library.
In m_one(), i have called method m_two();.
In m_two(), i have called m_three();.
Now, the problem is, progressbar only works till m_one() executes and then progressbar visibility goes invisible and remaining methods executes in background thread.
How do i keep rotating progressbar until all the methods done receiving data using volley request?
Try this code.
private static final String TAG = "LoginActivity.this";
Button button_login;
Context context;
ProgressBar progressBar;
//some variables for accepting the volley response data
DBUtils dbUtils;
Calendar calendar_2;
public SimpleDateFormat dateFormat;
public SimpleDateFormat timeformat;
Date date;
TreeSet<Integer> idSet;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
button_login = findViewById(R.id.btn_login);
context = getApplicationContext();
progressBar = findViewById(R.id.progress_id_1);
calendar_2 = Calendar.getInstance();
dbUtils = new DBUtils(this);
//clear the db tables on start of app
dbUtils.ClearTables();
date = Calendar.getInstance().getTime();
Log.e(TAG, "\n current time: " + date);
dateFormat = new SimpleDateFormat("dd-MM-yyyy");
idSet = new TreeSet<>();
//Login button click event ********************
button_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkNetwork();
}
});
}
private void checkNetwork() {
progressBar.setVisibility(View.VISIBLE);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
try {
if (netInfo != null) {
NetworkInfo.State state = conMgr.getActiveNetworkInfo().getState();
if (state == NetworkInfo.State.CONNECTED) {
Log.e(TAG, "nw info: " + netInfo.getExtraInfo());
Log.e(TAG, "Network Connected ");
method1();
Thread.sleep(3000);
} else {
Log.e(TAG, "Network Disconnected");
}
} else if (netInfo == null) {
Log.e(TAG, "Network Not Found !");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// ********************************************
// ********************************************
//to get the response of requested url
public void method1() {
try {
//url without api for login session
URL loginURL = new URL(your url 1);
HttpURLConnection urlconnect = (HttpURLConnection) loginURL.openConnection();
;
//http connection for webpage permission
//type of request get / post...
urlconnect.setRequestMethod("POST");
//allow the post request for user
urlconnect.setDoOutput(true);
/*
Singleton_Volley is the class for volley initialize
you can skip Singleton_Volley class..its correct
*/
// Get a RequestQueue in required page
RequestQueue queue = Singleton_Volley.getInstance(this.getApplicationContext()).
getRequestQueue();
// Request a string response from the provided URL.(my case, url)
StringRequest stringRequest = new StringRequest(Request.Method.POST, "" + loginURL.toString(),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//accept the data from request and set in our views like list,text, etc...
try {
/* your response data stored in variables first and then stored in sqlite you have to consider this strictly, make sure you also have array in response to wait for a while */
method2();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//popup an error message...(Toast)
}
})
} ;
// Add the request to the RequestQueue.
Singleton_Volley.getInstance(this).addToRequestQueue(queue.add(stringRequest));
} catch(
IOException e)
{
e.printStackTrace();
} catch(
JSONException e)
{
e.printStackTrace();
}
}
public void method2() {
try {
url_2 = new URL(your url 2);
HttpURLConnection urlconnect = (HttpURLConnection)
url_2.openConnection();
;
//http connection for webpage permission
//type of request get / post...
urlconnect.setRequestMethod("POST");
//allow the post request for user
urlconnect.setDoOutput(true);
RequestQueue contactQueue = Singleton_Volley.getInstance(this).
getRequestQueue();
// Request a string response from the provided URL.(in my case, url_2)
StringRequest stringRequest = new StringRequest(Request.Method.GET, "" + url_2.toString(),
new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onResponse(String response) {
//accept the data from request and set in our views like list,text, etc...
try {
/*
your response data stored in variables first and then stored in sqlite
you have to consider this strictly
make sure you also have array in response to wait for a while
*/
method3(); //method3() called here
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//popup an error messege...(Toast)
Toast.makeText(LoginActivity.this, "" + error, Toast.LENGTH_SHORT).show();
}
})
} ;
// Add the request to the RequestQueue.
Singleton_Volley.getInstance(this).addToRequestQueue(contactQueue.add(stringRequest));
} catch(Exception e){
e.printStackTrace();
}
}
// ********************************************
// ********************************************
private void method3(){
try{
URL url_3=new URL(your url 3);
HttpURLConnection urlconnect=(HttpURLConnection)url_3.openConnection();
;
//http connection for webpage permission
//type of request get / post...
urlconnect.setRequestMethod("POST");
//allow the post request for user
urlconnect.setDoOutput(true);
RequestQueue stageQueue=Singleton_Volley.getInstance(this).
getRequestQueue();
// Request a string response from the provided URL.(in my case, url_3)
StringRequest stringRequest=new StringRequest(Request.Method.GET,""+url_3.toString(),
new Response.Listener<String>(){
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onResponse(String response){
//accept the data from request and set in our views like list,text, etc...
try{
progressBar.setVisibility(View.GONE);
/*
make sure you also have array in response to wait for a while
*/
}catch(Exception ex){
ex.printStackTrace();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
//popup an error messege...(Toast)
}
})
};
// Add the request to the RequestQueue.
Singleton_Volley.getInstance(this).addToRequestQueue(stageQueue.add(stringRequest));
}catch(Exception ec){
ec.printStackTrace();
}
startActivity(new Intent(LoginActivity.this,Page2.class));
}
}
}}
Please manage the closing } and it should work.

Getting Null value from 1 class to other after storing value object

I have Authentication class which have method Auth with 2 arguments.
after calling that method a volley request generated and response catch through other function because of aSync. that object is a Static object and accessible in other class but that shows null always after making object or initializing it onCreate of activity.
Let check my Authenticate class:
public class Authenticate {
private static final String URL = "http://allskkc/zaigham/idsrs_authentication.php";
public static JSONObject finalresult;
public Authenticate() {
}
public static void Auth(String IEMI, String PIN) throws TimeoutException {
final JSONObject params = new JSONObject();
finalresult = new JSONObject();
RequestQueue queue = Volley.newRequestQueue(Splash.context);
try {
params.put("iemi", IEMI);
params.put("pin", PIN);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("params to server", params.toString());
JsonObjectRequest jsOBJRequest = new JsonObjectRequest
(Request.Method.POST, URL, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("response from server", response.toString());
ftn(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response error",error.toString());
}
});
queue.add(jsOBJRequest);
}
public static void ftn(JSONObject jsonObject) {
finalresult = jsonObject;
Log.e("as", "Response in ftn() = " + finalresult.toString());
}
}
final finalresult have value when I call that Auth() method but in my Login class it shows {}
let check my method call:
try {
Authenticate.Auth("358607051299527","1122");
} catch (TimeoutException e) {
e.printStackTrace();
}
Log.e("as","Prefrences Saved");
Log.e("as","My final result = "+Authenticate.finalresult.toString());
I attached my Log.e Image that may help more to understand.
You can see in your logs that application tries to get the result of request before request is done. Network request is asynchronous, it is done on background thread.
You should get the result after request is finished in some sort of callback.

Cannot assign value to final Volley variable response

I am familiar with Volley and creating a Singleton class, and adding requests to the queue. However, I wish to increase the modularity of volley and simply call all requests through method call to another class instead. I have setup the present action as basis for the common GET request:
public Object getRequest(String params) {
final JSONObject getRequestReturn = new JSONObject();
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
getRequestReturn = response;
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return getRequestReturn;
}
However, I have a the perplexing catch 22 error on the assignment of response at:
getRequestReturn = response;
The error notes that getRequestReturn must be declared final to allow for use within the inner class, but upon assigning final, another error appears noting that you cannot assign a value to a final variable.
How can this method be handled?
Declare JSONObject as global and initialize in same place like this.
JSONObject getRequestReturn ;
getRequestReturn = new JSONObject();
public Object getRequest(String params) {
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return new JSONObject();
}
U can't get response when u return!Volley request is async!
I use EventBus and I do it like this :
When I need to get data from web , i add a request like this.
Then when i get response from web ,I use EventBus to post a event.
I get the event and update my page.
Or U can try the RxAndroid.

Android Volley multiple Requests

I try to execute a new volley request in the current volley request, but when the new request is called it don't step into the onrespond method.
The new request should be executed before the first ends. (Last in, first out)
How can I execute the new request succesfully ?
private void makeJsonObjectRequest() {
ac = new AppController();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("test", response.toString());
try {
// Parsing json object response
// response will be a json object
JSONArray name = response.getJSONArray("data");
for (int i = 0; i < name.length(); i++) {
JSONObject post = (JSONObject) name.getJSONObject(i);
try {
objectid = post.getString("object_id");
newRequest(objectid);
}
catch (Exception e) {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("test", "Error: " + error.getMessage());
}
});
// Adding request to request queue
ac.getInstance().addToRequestQueue(jsonObjReq);
}
Try it Work 100%
public class Utility {
String result = "";
String tag_string_req = "string_raq";
private Activity activity;
Context context;
private LinearLayout mLinear;
private ProgressDialog pDialog;
public Utility(Context context) {
this.context = context;
}
public String getString(String url, final VolleyCallback callback) {
showpDialog();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
result = response;
hideDialog();
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onRequestError(error);
hideDialog();
/*LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, null);
((Activity) context).setContentView(layout);*/
}
});
VolleySingleton.getInstance().addToRequestQueue(stringRequest, tag_string_req);
stringRequest.setRetryPolicy(
new DefaultRetryPolicy(1 * 1000, 1, 1.0f));
return result;
}
public interface VolleyCallback {
void onSuccess(String result);
void onRequestError(VolleyError errorMessage);
//void onJsonInvoke(String url, final VolleyCallback callback);
}
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
private void showpDialog() {
onProgress();
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
public void onProgress() {
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
Call Fragment
Utility utility = new Utility(getContext());
utility.getString(urls, new Utility.VolleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject toplinks = new JSONObject(result);
JSONObject data = toplinks.getJSONObject("toplinks");
M.i("============LS", "" + data);
} catch (JSONException e) {
e.printStackTrace();
}
finally {
}
}
#Override
public void onRequestError(VolleyError errorMessage) {
errorJson.setVisibility(View.VISIBLE);
String msg = VolleyException.getErrorMessageFromVolleyError(errorMessage);
errorJson.setText(msg);
}
});
all this about
Request Prioritization
Networking calls is real time operation so let consider we have multi request like in your case , Volley processes the requests from higher priorities to lower priorities , in first-in-first-out order.
So all you need change priority (set Priority.HIGH) to request you want process first.
here is a piece of code
public class CustomPriorityRequest extends JsonObjectRequest {
// default value
Priority mPriority = Priority.HIGH;
public CustomPriorityRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public CustomPriorityRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
#Override
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority p){
mPriority = p;
}
}
As others mentioned one way is to put a high priority on the request.
Another option as it seems you have the first request depending on the inner one wrapped in the try-catch block which seems to me you want to achieve a synchronous/blocking behavior for this specific case. then you can use RequestFuture :
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = newRequest(objectid, future);
requestQueue.add(request);
String result = future.get();

How do you use the Android Volley API?

I am thinking of implementing the Android Volley library in my next projects (Google IO presentation about Volley).
However, I haven't found any serious API for that library.
How do I upload files, do POST/GET requests, and add a Gson parser as a JSON parser using Volley?
Source code
Edit: finally here it is an official training about "Volley library"
I found some examples about Volley library
6 examples by Ognyan Bankov :
Simple request
JSON request
Gson request
Image loading
with newer external HttpClient (4.2.3)
With Self-Signed SSL Certificate.
one good simple example by Paresh Mayani
other example by Hardik Trivedi
(NEW) Android working with Volley Library by Ravi Tamada
Unfortunately there is no documentation for a Volley library like JavaDocs until now. Only repo on github and several tutorials across the Internet. So the only good docs is source code :) . When I played with Volley I read this tutorial.
About post/get you can read this : Volley - POST/GET parameters Hope this helps
This is an illustration for making a POST request using Volley. StringRequest is used to get response in the form of String.
Assuming your rest API returns a JSON. The JSON response from your API is received as String here, which you can covert again to JSON and process it further. Added comments in code.
StringRequest postRequest = new StringRequest(Request.Method.POST, "PUT_YOUR_REST_API_URL_HERE",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
final JSONObject jsonObject = new JSONObject(response);
// Process your json here as required
} catch (JSONException e) {
// Handle json exception as needed
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String json = null;
NetworkResponse response = error.networkResponse;
if(response != null && response.data != null){
switch(response.statusCode) {
default:
String value = null;
try {
// It is important to put UTF-8 to receive proper data else you will get byte[] parsing error.
value = new String(response.data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
json = trimMessage(value, "message");
// Use it for displaying error message to user
break;
}
}
loginError(json);
progressDialog.dismiss();
error.printStackTrace();
}
public String trimMessage(String json, String key){
String trimmedString = null;
try{
JSONObject obj = new JSONObject(json);
trimmedString = obj.getString(key);
} catch(JSONException e){
e.printStackTrace();
return null;
}
return trimmedString;
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("abc", "pass abc");
params.put("xyz", "pass xyz");
// Pass more params as needed in your rest API
// Example you may want to pass user input from EditText as a parameter
// editText.getText().toString().trim()
return params;
}
#Override
public String getBodyContentType() {
// This is where you specify the content type
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
// This adds the request to the request queue
MySingleton.getInstance(YourActivity.this)
.addToRequestQueue(postRequest);
// Below is MySingleton class
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(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);
}
}
Just add volley.jar library to your project.
and then
As per Android documentation :
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// process your response here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//perform operation here after getting error
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
For more help refer How to user Volley
In simple way
private void load() {
JsonArrayRequest arrayreq = new JsonArrayRequest(ip.ip+"loadcollege.php",
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Album a;
try {
JSONArray data = new JSONArray(response.toString());
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
one = c.getString("cname").split(",");
two=c.getString("caddress").split(",");
three = c.getString("image").split(",");
four = c.getString("cid").split(",");
five = c.getString("logo").split(",");
a = new Album(one[0].toString(),two[0].toString(),ip.ip+"images/"+ three[0].toString(),four[0].toString(),ip.ip+"images/"+ five[0].toString());
albumList.add(a);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON array request "arrayreq" to the request queue
requestQueue.add(arrayreq);
}
Before testing all of the above answers, include
compile 'com.android.volley:volley:1.0.0'
in your gradle file and don't forgot to add the Internet permission to your Manifest file.
Use this class. It provides you an easy way to connect to the database.
public class WebRequest {
private Context mContext;
private String mUrl;
private int mMethod;
private VolleyListener mVolleyListener;
public WebRequest(Context context) {
mContext = context;
}
public WebRequest setURL(String url) {
mUrl = url;
return this;
}
public WebRequest setMethod(int method) {
mMethod = method;
return this;
}
public WebRequest readFromURL() {
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(mMethod, mUrl, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
mVolleyListener.onRecieve(s);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
mVolleyListener.onFail(volleyError);
}
});
requestQueue.add(stringRequest);
return this;
}
public WebRequest onListener(VolleyListener volleyListener) {
mVolleyListener = volleyListener;
return this;
}
public interface VolleyListener {
public void onRecieve(String data);
public void onFail(VolleyError volleyError);
}
}
Example usage:
new WebRequest(mContext)
.setURL("http://google.com")
.setMethod(Request.Method.POST)
.readFromURL()
.onListener(new WebRequest.VolleyListener() {
#Override
public void onRecieve(String data) {
}
#Override
public void onFail(VolleyError volleyError) {
}
});
private void userregister() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
RequestQueue queue = Volley.newRequestQueue(SignupActivity.this);
String url = "you";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.cancel();
try {
JSONObject jsonObject= new JSONObject(response.toString());
Log.e("status", ""+jsonObject.getString("status"));
if(jsonObject.getString("status").equals("success"))
{
String studentid=jsonObject.getString("id");
Intent intent=new Intent(SignupActivity.this, OTPVerificationActivity.class);
startActivity(intent);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("String ", ""+response);
}
}, 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("password", input_password.getText().toString());
params.put("cpassword", input_reEnterPassword.getText().toString());
params.put("email", input_email.getText().toString());
params.put("status", "1");
params.put("last_name", input_lastname.getText().toString());
params.put("phone", input_mobile.getText().toString());
params.put("standard", input_reStandard.getText().toString());
params.put("first_name", input_name.getText().toString());
params.put("refcode", input_reReferal.getText().toString());
params.put("created_at","");
params.put("update_at", "");
params.put("address", input_address.getText().toString());
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
Get full code here

Categories

Resources