Android - Return method using thread

Asked

Viewed 1,086 times

0

Hello guys I am developing an android application that uses the library Volley (google) to perform my requests http. I have a method that returns a Boolean and depends on the return of the request, that is the wickedness, the method returns the value before finishing the request.

public class MyService implements IMyService {
    private Context context = null;
    private Boolean result = false;

    public MyService(Context context){
        this.context = context;  Thread
    }

    @Override
    public Boolean isUrlValida(final String url){
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        result = true;
                        Log.w("isUrlValida", "onResponse");
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.w("isUrlValida", "onErrorResponse");
                    }
                }
        );

        ((AppApplication) context).getRequestQueue().add(stringRequest);
        ((AppApplication) context).getRequestQueue().start();
        return result;
    }
}

Will I need to perform some Thread’s control ? Thanks !

  • what return there is?

  • 200 - ok, it enters onResponse() the problem that already returns false without waiting for the request

  • I believe that the way to work with Volley is almost the same when working with Asynctasks, you will have to implement a "wait" for the user until you get the content you need.

  • Add this: if (s == null) { }- TO TEST.

  • @wryel I’ll take a look at the Asynctasks.

  • @Rafael remains the same, thank you all.

  • Debug each line to identify where it enters or not.

Show 2 more comments

1 answer

1


If you want to wait for a thread you can use the Join() method of the Thread class, which waits for a given thread to finish running. (But be careful not to block user interaction) Example:

Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {}
        }
    });
    t.start();

    try {
        t.join();
    } catch (InterruptedException e) {}

    System.out.println("Acabou.");

You always have the alternative of using Asynctask where you can stipulate the Boolean return at the end of the thread to end, simply define the types of variables that Asynctask handles and override the onPostExecute method(..)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.