logo
down
shadow

Synchronous Volley request locks up


Synchronous Volley request locks up

By : Zsombor
Date : October 19 2020, 08:10 AM
hope this fix your issue I'm trying to implement "live" input validation. The problem I have been facing for a while now is how to live check if the username already exists in the database.
code :
private void checkTaken(String username, Context context, Callback callback){
    boolean taken;
    Volley.getInstance(context).addToRequestQueue(new StringRequest(Request.Method.POST, url, 
        output -> callback.done(output.contains("taken")), 
        error -> {
           // TODO handle this error
        }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("username", username);
            return params;
        }
        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> params = new HashMap<>();
            params.put("Content-Type", "application/x-www-form-urlencoded");
            return params;
        }
    });
}
// This method wherever this is defined also needs to accept a callback so it can be asynchronous
public void whatever(StringCallback callback) {
    // ...
    if (!email.matches(regex)){
        callback.done("Username has an invalid format");
    } else {
        checkTaken(username, context, taken -> 
                 callback.done(taken ? "Username already taken" : null));
    } 
whatever(error -> {
    if(error == null) {
        handleSuccess();
    }
    else {
        handleError(error);
    }
 );


Share : facebook icon twitter icon
Can I do a synchronous request with volley?

Can I do a synchronous request with volley?


By : shamraiz ahmad
Date : March 29 2020, 07:55 AM
will help you It looks like it is possible with Volley's RequestFuture class. For example, to create a synchronous JSON HTTP GET request, you can do the following:
code :
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(URL, new JSONObject(), future, future);
requestQueue.add(request);

try {
  JSONObject response = future.get(); // this will block
} catch (InterruptedException e) {
  // exception handling
} catch (ExecutionException e) {
  // exception handling
}
How to make a synchronous GET request with volley library? And how to parse it afterwards?

How to make a synchronous GET request with volley library? And how to parse it afterwards?


By : CliffB
Date : March 29 2020, 07:55 AM
hope this fix your issue I've seen answer to both of these questions, however, when I tried to put them together, I couldn't make it work. The problem itself is pretty simple: I want to get a string from one site and use it in a post request. That means I can only make the post request after I've finished parsing the GET request. The main ideas I'm using are these ones: , Why not do something like this:
code :
// send first request
requestQueue.add(firstRequest, null, new Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            // ** code to parse response **

            // send second request
            requestQueue.add(secondRequest, null, new Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                   // ** code to parse response **
                }
            }, new ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {
                   // ** code to handle errors **
               }
            }));
        }
    }, new ErrorListener() {
       @Override
       public void onErrorResponse(VolleyError error) {          
           // ** code to handle errors **
       }
}));
Synchronous request with volley android

Synchronous request with volley android


By : Lachlan Neeley
Date : March 29 2020, 07:55 AM
I wish this help you @Applefriend As per the description what I understood is that the code inside the CustomSignIn method makes a network call asynchronously using volley which will set the session info later when the request is complete.
So when you say
code :
AppController.getInstance().addToRequestQueue(strReq); // Dispatch async call

if(SessionHandler.logged){ // This happens in the current UI thread (which be returning the default value or an exception
    return true;
} else {
    return false;
}
Android Volley synchronous request not working

Android Volley synchronous request not working


By : xiaomizi
Date : March 29 2020, 07:55 AM
wish help you to fix your issue tl;dr; You got deceived by the try-catch
Explanation: Because the RequestFuture.get()is probably running on the UI thread you are really getting a java.util.concurrent.TimeoutException behind the scenes. That is the default behaviour when the calls gets executed on the main thread.
code :
    public class TestVolley {

    private String TAG = "SO_TEST";
    private String url = "http://pokeapi.co/api/v2/pokemon-form/1/";


    public JSONObject fetchModules(Context ctx){
        JSONObject response = null;
        RequestQueue requestQueue = Volley.newRequestQueue(ctx);


        RequestFuture<JSONObject> future = RequestFuture.newFuture();
        JsonObjectRequest request = new JsonObjectRequest(url,null,future,future);
        requestQueue.add(request);


        try {
            response = future.get(3, TimeUnit.SECONDS); // Blocks for at most 10 seconds.
        } catch (InterruptedException e) {
            Log.d(TAG,"interrupted");
        } catch (ExecutionException e) {
            Log.d(TAG,"execution");
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

        Log.d(TAG,response.toString());

        return response;
    }
}
public class MyVolleyAsyncTask extends AsyncTask<String,String, JSONObject> {

    private Context ctx;

    public MyVolleyAsyncTask(Context hostContext)
    {
        ctx = hostContext;
    }

    @Override
    protected JSONObject doInBackground(String... params) {

        // Method runs on a separate thread, make all the network calls you need
        TestVolley tester = new TestVolley();

        return tester.fetchModules(ctx);
    }


    @Override
    protected void onPostExecute(JSONObject result)
    {
       // runs on the UI thread
       // do something with the result
    }
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // this is your old code which will crash the app
        //TestVolley tester = new TestVolley();
        //tester.fetchModules(this);

        // Works!
        new MyVolleyAsyncTask(this).execute();
    }
}
com.so.henriquems.testvolleyfuture D/SO_TEST: {"id":1,"pokemon":{"url":"http:\/\/pokeapi.co\/api\/v2\/pokemon\/1\/","name":"bulbasaur"},[...]
volley synchronous request blocks forever

volley synchronous request blocks forever


By : Dilawez Simran
Date : March 29 2020, 07:55 AM
hope this fix your issue This question is old, but this doesn't have any response.
I will try write a response for other people have the same problem, I believe that the problem here is that you are running the future from the main thread, and volley user this thread by default for execute the responses.
Related Posts Related Posts :
  • How to employ keyed-hash message authentication code (HMAC) with Android Keystore
  • Prevent inviting existing users or previously invited
  • How to overwrite windowSoftInputMode using edit-config tag in cordova
  • Difference between Loader and AsyncTask
  • In Firebase Android, retrieve the value of a child node and save it in a boolean variable
  • when i scroll the custom list in my android app then the favorite icon which is part of the custom adapter changes on it
  • adding room dependency gives manifest merge error
  • Visibility of RelativeLayout change on scrolling Gridview
  • Strange LiveData behavior vs ObservableField
  • Which layout is used for clash of clans home screen? We can scroll it horizontal as well as vertical. Please illuminate
  • RxJava: Know when observable is finished and return Boolean Observable to the caller
  • how to use savedInstanceState to save camera information when the orientation change occure
  • Style React-Native via Styles.xml
  • Keyboard won't show after calling InputMethodManager.showSoftInput
  • Compiling ffmpeg for Android on OSX
  • Button does not get clicked on the first attempt
  • AR Core performance, learning curve and comparison with other frameworks
  • Codename one : Attaching images to email message fails
  • Error: Unsupported type 'viewItem' in Android build
  • setLayoutParams on ConstraintLayout does not change size
  • How to profile the fetch time of the android gradle libraries
  • Kotlin setOnclickListener
  • Naming convention for methods returning RxJava's Completable
  • Conv3D not working
  • FFmpeg audio video merge command
  • Do you have to use gradle-experimental for JNI?
  • How to get key hashes for facebook for facebook app?
  • ZXing not calling onActivityResult, When scanning QR Code
  • Integration of Android Native module with existing Xamarin Native Project
  • Restore RecyclerView state after rotating
  • ViewModelProviders java.lang.RuntimeException trying to instantiate class which inherit AndroidViewModel
  • SKD19 vs SDK24 - Usage of API documented as @since 1.8+
  • filter option in list view fragment activity
  • Picture from camera not showing up in second activity
  • How to change imageview according to screen size
  • How to copy Android Studio project to remote Git (NOT GitHub) server
  • How to get React-Native to announce specific accessibility message via AccessibiliyManager?
  • Change colors of com.tech.freak.wizardpager.ui.StepPagerStrip
  • Android fullscreen activity shows ActionBar
  • Turn on the screen when timer calls onFinish()
  • Would like a bit of clarification with SQLite database's onUpgrade method
  • Use ObjectBox with Libgdx
  • How to make combine Gregorian and Hijri calendar in Android?
  • Try to read text file from sdcard in other language
  • "App not installed" message when installed apk
  • How to execute a designated test suite class in Firebase Test Lab
  • play music with background service
  • background not visible on LG G3
  • should every View have an id?
  • Realm object server sync on low connection.
  • Correct way to add more views to adapter
  • Getting error in android support library
  • Instant app zip uploading error
  • "No emulator installed" error in Android Studio even though Intel HAXM is up and running
  • AsyncTask without leaks
  • SQLiteException : No such table found whereas a table was created
  • Using @Component.Builder with constructor params
  • No injector was found for fragment dagger 2.11
  • Android Volley Https SSL self signed and Google Maps API
  • Why does the onClickListener not work anymore in this example?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org