#String variable using in background task and return it

5 messages · Page 1 of 1 (latest)

fresh comet
#

Have a look at below code:

public String getQuote() {
        final String[] fullQuoteData = {""};

        OkHttpClient client = new OkHttpClient();
        okhttp3.Request request = new okhttp3.Request.Builder()

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                   try{
                        res = response.body().string();
                        myResponse = new JSONArray(res);
                        if(myResponse != null && myResponse.length() > 0){
                            String quote = "", author = "", category = "";
                            for (int i = 0; i < myResponse.length(); i++) {
                                JSONObject object = myResponse.getJSONObject(i);
                                quote = object.getString("quote");
                                author = object.getString("author");
                                category = object.getString("category");
                            }
                            fullQuoteData[0] = quote + "-" + author + "-" + category;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                  // 
            }
return fullQuoteData[0];

THIS IS AN ASYNC like TASK and after completing network call I need to return a STRING then why I need to make it FINAL variable
And why it forces me to make the String as ARRAY 😭
Any hints!

vivid juniperBOT
#

This post has been reserved for your question.

Hey @fresh comet! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

tame hedge
#

I think it is requiring the string to be final because you are referencing it from within an anonymous object definition
you could try creating a class that extends callback with the same overrides and passing that as the callback
then you can access the string as an instance variable of your callback class and it should not need to be final
e.g.

class OtherCallback extends Callback
{
  String fullQuoteData;
  // Method overrides here
}
#
OtherCallback callback = new OtherCallback();
client.newCall(request).enqueue(callback);

you may want to give the class a better name than 'OtherCallback' depending on what it is doing