Android - Method with return using thread

0

Hello everyone, I'm developing an android application that uses the volley library (google) to perform my http requests. I have a method that returns a Boolean and depends on the return of the request, then that is the badness, 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 do any Thread's control? Thanks!

    
asked by anonymous 15.01.2015 / 18:58

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 thread to finish executing. (But be careful not to block interaction with the user) 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 option of using AsyncTask where you can stipulate the Boolean return at the end of the thread, by defining the types of variables AsyncTask handles and overriding the onPostExecute method.     

16.01.2015 / 19:18