简体   繁体   中英

Android - Cannot refer to a non-final variable test inside an inner class defined in a different method

I'm currently creating an app utilizing Facebook's Android SDK. Below is the attached code:

private void checkIfPostLiked(final String post_id) {
    String isLiked = null;
    new Request(Session.getActiveSession(), post_id + "/likes/", null,
            HttpMethod.GET, new Request.Callback() {

                @Override
                public void onCompleted(Response response) {

                    try {
                        JSONObject json;
                        json = new JSONObject(response.getRawResponse());
                        JSONArray jArray = json.getJSONArray("data");
                        for (int i = 0; i < jArray.length(); i++) {
                            user_like_name = jArray.getJSONObject(i)
                                    .get("name").toString();
                            if (user_like_name.equals(user_me.getName())) {
                                isLiked= "true";
                            }
                            else{
                                                      isLiked = "false";
                            }
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    // Get message data
                }
            }).executeAsync();
}

I would like to return the string isLiked , and return it, but the issue is that I keep on getting Cannot refer to a non-final variable isLiked inside an inner class defined in a different method . I have to use this method ( checkifPostLiked ) as a function in another iteration within a loop, therefore putting the variable isLiked as member variable would not work as well. I really hope that anyone could help me on this!

You need to initialize isLiked and finalize it:

final String isLiked = new String();

/* Rest of the code remains the same. */
new Request(Session.getActiveSession(), post_id + "/likes/", null,
        HttpMethod.GET, new Request.Callback() {

        ....
        ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM