How to make Volley request in loop until specific response come?
package raju.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
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 com.skyfishjy.library.RippleBackgroun;
public class xxx extends AppCompatActivity {
int xi= 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xxx);
StringRequest sr = new StringRequest("http://reju.pe.hu/test.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.contains("1")){
xi=1;
}
Log.w("res",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
while (xi==0){
try {
Thread.sleep(1000);
RequestQueue xx = Volley.newRequestQueue(this);
xx.add(sr);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Here I have created a method called runRequest, which has the code you've given above. The only changes I've made to the code is that I am waiting for the response to the request, checking if it's a specific response. If it's not the specific response, the method runRequest is called again, and if it's the specific response, nothing is done.
public void runRequest() {
StringRequest sr = new StringRequest("http://reju.pe.hu/test.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.contains("1")) {
//here comes the specific response
} else {
runRequest();
//re run the request
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue xx = Volley.newRequestQueue(this);
xx.add(sr);
}
Related
When tapping an image (from a previous activity) I get to this activity (where I pass the clientid) that reads a JSONArray and use a setter to set the nick.
I then use a getter to do a textview setText.
The problem is that the first time no nick is set. When I go back to the previous activity and tap the same image again, only then the nick is set.
Why isn't the nick displayed from the first time.
(ps: I'm quite new to Java/Android Studio)
package com.smartvibes.smartbeat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class profileViewActivity extends AppCompatActivity {
RequestQueue rs;
String url, id, nick, age, city, mainpic, numpics, extrapic0, extrapic1, extrapic2, extrapic3, extrapic4, extrapic5;
TextView profileIntro;
static String pnick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_view);
Bundle getProfileId = getIntent().getExtras();
if (getProfileId == null) {
return;
}
String profileid = getProfileId.getString("profileid");
url = "https://www.smartvibes.be/profiles/api/profileview.php?id=" + profileid;
rs = Volley.newRequestQueue(this);
sendjsonrequest();
profileIntro = (TextView) findViewById(R.id.profileIntro);
profileIntro.setText(getPnick());
}
public void sendjsonrequest() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
setPnick(response.getString("nick"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
rs.add(jsonObjectRequest);
}
public static void setPnick(String nick) {
pnick = nick;
}
public static String getPnick(){
return pnick;
}
}
Because sendjsonrequest is an async call
You need to update textView in onResponse Method itself, like below
setPnick(response.getString("nick"));
profileIntro.setText(getPnick());
I am trying to call this method from another class; it should return true or false after checking user ID and password on the server.
It always returns false even if the login process is successful because it returns the default value false before i got the request response!
I made a lot of search before posting this question but there is no clear answer on how to solve this problem.
MyHelper myHelper = new MyHelper();
myHelper.setVolleyResponseListener(new MyHelper.OnVolleyResponse()
{
#Override
public void onResponse(JSONObject jsonObject)
{
// do watever you want here with response.
}
});
if (myHelper.doBackgroundLogin(getApplicationContext())) {
uploadImageToServer();
}else{
finish();
startActivity(new Intent(AccountProfileImageActivity.this, AccountLoginActivity.class));
}
package com.company.testApp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by Aly on 1/11/2017.
*/
public class MyHelper {
private static AlertDialog.Builder builder;
public static Context ctx;
public static ValuesManager vm;
public static boolean status = false;
public static boolean doBackgroundLogin(final Context context) {
vm = new ValuesManager( context, context.getString(R.string.saved_values_file_name) );
String user_email = vm.retrieveSharedPreferences("user_email");
String user_password = vm.retrieveSharedPreferences("user_password");
Toast.makeText(context, user_email + " - " + user_password, Toast.LENGTH_SHORT).show();
//------------------------------------------------------------------------------------------
// final MyProgressDialog progressDialog;
// progressDialog = MyProgressDialog.show(context, "title", "message");
// //------------------------------------------------------------------------------------------
String url = context.getString(R.string.server_path);
Log.d("URL : ", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response : ", response); // log the error to trace it and print message to user
// progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
if( code.equals("login_true") ) {
status = true;
vm.saveSharedPreferences( "user_token", JO.getString("user_token") );
Log.d("trace","code = " + code);
Log.d("trace","statusUpdated = " + status);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("vERROR : ", error.toString()); // log the error to trace it and print message to user
// progressDialog.dismiss();
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("action","account_login");
params.put("email_address",vm.retrieveSharedPreferences("user_email"));
params.put("password",vm.retrieveSharedPreferences("user_password"));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
//------------------------------------------------------------------------------------------
Log.d("trace","status = " + status);
return status;
}
public interface OnVolleyResponse
{
void onResponse(JSONObject jsonObject);
}
public void setVolleyResponseListener(OnVolleyResponse responseListener)
{
this.volleyResponse = volleyResponse;
}
}
You have to use interface callback for this.
Why?
Because this is asynchronous call, and work on different thread. so your Main Thread will not wait for result of it.
Solution
Create interface in your MyHelper class
Edit
OnVolleyResponse onVolleyResponse;
public interface OnVolleyResponse
{
void onResponse(JSONObject jsonObject);
}
Create setter method for callback
public void setVolleyResponseListener(OnVolleyResponse responseListener)
{
this.volleyResponse = volleyResponse;
}
Now call this method from your Activity
MyHelper myHelper = new MyHelper();
myHelper.setVolleyResponseListener(new OnVolleyResponse()
{
#Override
public void onResponse(JSONObject jsonObject)
{
// do watever you want here with response.
}
});
if (myHelper.doBackgroundLogin(getApplicationContext())) {
uploadImageToServer();
}else{
finish();
startActivity(new Intent(AccountProfileImageActivity.this, AccountLoginActivity.class));
}
Note
Remove static from doBackgroundLogin method, and call it with instance of MyHelper.
Make an interface
public interface VolleyCallback{
public void onSuccess(boolean status);}
After this when you get a response you should change your doBackgroundLogin() method like this.
public static boolean doBackgroundLogin(final Context context,VolleyCallback callback) {
vm = new ValuesManager( context, context.getString(R.string.saved_values_file_name) );
String user_email = vm.retrieveSharedPreferences("user_email");
String user_password = vm.retrieveSharedPreferences("user_password");
Toast.makeText(context, user_email + " - " + user_password, Toast.LENGTH_SHORT).show();
String url = context.getString(R.string.server_path);
Log.d("URL : ", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response : ", response); // log the error to trace it and print message to user
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
if( code.equals("login_true") ) {
status = true;
vm.saveSharedPreferences( "user_token", JO.getString("user_token") );
Log.d("trace","code = " + code);
Log.d("trace","statusUpdated = " + status);
callback.onSuccess(status);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("vERROR : ", error.toString()); // log the error to trace it and print message to user
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("action","account_login");
params.put("email_address",vm.retrieveSharedPreferences("user_email"));
params.put("password",vm.retrieveSharedPreferences("user_password"));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
Log.d("trace","status = " + status);
return status; }
Just see this callback.onSuccess(status);
This would send the response as soon as the login is successful.
onResponse method is for you volley handle this waiting for you and call onResponse method after fetching data or response from specific url.
final TextView mTextView = (TextView) findViewById(R.id.text);
...
// 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) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
I want to get the variable "response" from the BDDRequest class for using it in a ListView in my MainActivity class, how i can do ?
public class BDDRequest implements Serializable {
private final long serialVersionUID = 1L;
static private Activity activity;
public String req;
public BDDRequest(){}
public static void GetRequest(final Context t, UserEmployeeInfo User) {
activity = (Activity) t;
RequestQueue queue = Volley.newRequestQueue(t);
ParamsSend params = new ParamsSend();
params.setUser(User);
ParserJson<ParamsSend> pj = new ParserJson<>(params);
String strJson;
try {
strJson = pj.writeJSON();
} catch (JsonProcessingException e) {
strJson = "null";
}
final String data = strJson;
String REST_API_URL = "http://212.227.53.116:8080/WSmartgroom/rest/perso/request";
Log.d("lol", strJson);
StringRequest myReq = new StringRequest(Request.Method.PUT,
REST_API_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("reponse:", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("That didn't work!", "Error");
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
return data.getBytes();
}
};
queue.add(myReq);
}
}
Use an interface for it,
import android.app.Activity;
import android.content.Context;
import android.util.Log;
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.io.Serializable;
public class BDDRequest implements Serializable {
private final long serialVersionUID = 1L;
static private Activity activity;
public String req;
public BDDRequest() {
}
public static void GetRequest(final Context t, UserEmployeeInfo User, final Callback callback) {
activity = (Activity) t;
RequestQueue queue = Volley.newRequestQueue(t);
ParamsSend params = new ParamsSend();
params.setUser(User);
ParserJson<ParamsSend> pj = new ParserJson<>(params);
String strJson;
try {
strJson = pj.writeJSON();
} catch (JsonProcessingException e) {
strJson = "null";
}
final String data = strJson;
String REST_API_URL = "http://212.227.53.116:8080/WSmartgroom/rest/perso/request";
Log.d("lol", strJson);
StringRequest myReq = new StringRequest(Request.Method.PUT,
REST_API_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("reponse:", response);
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("That didn't work!", "Error");
callback.onError();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
return data.getBytes();
}
};
queue.add(myReq);
}
public interface Callback {
void onSuccess(String response);
void onError();
}
}
And implement the interface on your class .
Use like this,
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.example.BDDRequest.Callback;
public class MainActivity extends FragmentActivity implements Callback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BDDRequest.GetRequest(this, new UserEmployeeInfo(), this);
}
#Override
public void onSuccess(String response) {
// Bind the data to the listview
}
#Override
public void onError() {
//Show fallback message here
}
}
You're declaring onResponse method. Inside it, response is a parameter. Why do you want to get a parameter which you're putting into? The question is not clear.
I have one method with this url:
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + value;
And i want to return the result of this method.
i have tried the VolleyCallback callback but i cant send the value to the method
package com.example.fabio.domoticaa;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
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.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Divi_Dispo extends AppCompatActivity {
String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_divi__dispo);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String[] count = new String[1];
final String[] id = new String[1];
Intent intent = getIntent();
String value = intent.getStringExtra("divisao");
final EditText nomediv = (EditText) findViewById(R.id.editText4);
Count(value);
nomediv.setText(x);//want set th result of Count(value)
}
public void Count(String value) {
final String[] count = new String[1];
// Send data
try {
RequestQueue queue = Volley.newRequestQueue(Divi_Dispo.this);
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + value ;
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jObj = new JSONObject(String.valueOf(response.get(0)));
count[0] = jObj.getString("COUNT(id)");//want return this valor
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
} catch (Exception ex) {
} finally {
}
}
public interface VolleyCallback {
void onSuccess(String result);
}
}
package com.newsak.services;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import com.android.volley.Cache;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.newsak.controller.NewsakContoller;
import com.newsak.data.FeedItem;
import com.newsak.parse.XmlParser;
import com.newsak.constants.SportsUrls;
public class FetchBackgroundData extends IntentService {
private List<FeedItem> feedItems;
public static List<FeedItem> largeFeedItems;
boolean cachedFalg = false;
public static final int FINISHED_STATE = 0;
ResultReceiver receiver;
int counter = 0 ;
public String [] MY_URLS = SportsUrls.SPORTS_URLS;
public FetchBackgroundData() {
super("FetchBackgroundData");
}
#Override
protected void onHandleIntent(Intent intent) {
receiver = intent.getParcelableExtra("receiver");
GO();
}
public void GO() {
feedItems = new ArrayList<FeedItem>();
largeFeedItems = new ArrayList<FeedItem>();
// check for the cache
Cache cache = NewsakContoller.getInstance().getRequestQueue().getCache();
List<Cache.Entry> entry = new ArrayList<Cache.Entry>();
for(String url : MY_URLS){
entry.add(cache.get(url));
}
for (Cache.Entry en : entry) {
if (en != null) {
// fetch the data from the cache ...
try {
String data = new String(en.data, "UTF-8");
feedItems = XmlParser.getItem(data);
largeFeedItems.addAll(feedItems);
cachedFalg = true;
Log.d("cache_start", "cache start");
if(feedItems.size() > 0){
counter++;
feedItems = null ;
if(counter == 7){
receiver.send(FINISHED_STATE, Bundle.EMPTY);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
if (!cachedFalg) {
for(String url : MY_URLS){
getRequest(url);
}
Log.d("without_cache_start", "cache start");
}
}
public void getRequest(String url) {
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
public void onResponse(String result) {
feedItems = XmlParser.getItem(result);
largeFeedItems.addAll(feedItems);
if(feedItems.size() > 0){
counter++;
feedItems = null ;
if(counter == 7){
receiver.send(FINISHED_STATE, Bundle.EMPTY);
}
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError arg0) {
}
});
//handle return twice data
request.setRetryPolicy(new DefaultRetryPolicy( 0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES ,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
NewsakContoller.getInstance().addToRequestQueue(request);
}
}
this is my intentservice get the data by xml parser .
so can any one help me to figure what the problem is ?? I used this
Android volley sending data twice
but this solution doesn't wotk with my code
Your this code
request.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Replace this code
request.setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));