Mande Kira Mande Kira - 5 months ago 41
Java Question

Return Value In Runnable

I have a custom adapter that

buttons
and
TextView
, the
TextView
is changed on a
button
click within
listview
and it after sending and receiving feedback from
http
Post
via
Json
response, I tried using
runnable
and
assynctask
but no success. In the runnable, I can not return a value from the method.

What I wanted is to send
http
request to the server and return
json
results, based on the returned results, the
TextView
will change.

What is the best approach to use to achieve this.

If any one can help point me to a resource that will help me to achieve this will be highly welcome.

Thanks in advance!

Here is my code..

public String getStatus(final String id, final String user){
final String[] resp = {"0/0/0"};

new Thread(new Runnable() {
@Override
public void run() {

// Building Parameters
final List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("id", id));

Log.d("Nay Params", "" + params);
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(NAY_URL, "POST",
params);

// check your log for json response
// json success tag

try {

Log.d("Nay Response", ""+ json);
success = json.getBoolean(TAG_SUCCESS);
yeaSt = json.getBoolean(TAG_E_STATUS);
naySt = json.getBoolean(TAG_A_STATUS);
yeaC = json.getInt(TAG_YEA);
nayC = json.getInt(TAG_NAY);
if (success){
resp[0] = yeaS + "/" + naySt + "/" + yeaC + "/" + nayC;

return resp[0];
//Can not return return value within void method that is; Class void run()

}



} catch (JSONException e) {
e.printStackTrace();
//return resp[0];

}

}



}).start();
//Can not acces json result outside the try catch block
Log.d("sux", ""+success);

// Log.d("Rest1", resp[0]);

return resp[0];
}

Answer

You could use Callable interface in order to run a thread and get the thread's result.

Here's the Callable documentation.

And Jakob explains how to use it here.

Hope that helped, if you need a concrete example I recently used this approach in my project, and I'll be happy to provide you with a sample.

Edit: Here is a simple example of using callable, I changed a little bit my code so it is more clear:

public class Test {
ExecutorService executor;

public Test() {
    /* I used an executor that creates a new thread every time creating a server requests object
     * you might need to create a thread pool instead, depending on your application
     * */
    executor = Executors.newSingleThreadExecutor();
}

private JSONObject doTheWork() {
    // init 
    Callable<JSONObject> callable;
    Future<JSONObject> future;
    JSONObject jsonResult = null;

    try {
        // create callable object with desired job
        callable = new Callable<JSONObject>() {
            @Override
            public JSONObject call() throws Exception {
                JSONObject jsonResult = new JSONObject();

                // connect to the server

                // insert desired data into json object

                // and return the json object 
                return jsonResult; 
            }
        };

        future = executor.submit(callable);
        jsonResult = future.get();
    } catch(InterruptedException ex) {
        // Log exception at first so you could know if something went wrong and needs to be fixed
    } catch(ExecutionException ex) {
        // Log exception at first so you could know if something went wrong and needs to be fixed
    }

    return jsonResult;
}

}

Another approach would be creating a class that implements Callable. Whatever of these approaches you choose depends on your application, and maybe person's taste :). Happy that I helped.