Dara Sok
Dara Sok

Reputation: 59

Android studio access variable inner class

How can I access string value "data" outside class onResponse. Always i use Toast outside class response is display null.

String data; 

JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {
                   try {

                     data = response.getString("name"));

                       } catch (JSONException e) {
                             e.printStackTrace();
                   }
             }
             }, new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.toString(),Toast.LENGTH_SHORT).show();
                    }
                });
                RequestQueue queue = Volley.newRequestQueue(this);
                queue.add(objectRequest);
}

Toast.makeText(getApplicationContext(), "Display: " + data,Toast.LENGTH_SHORT).show();

Upvotes: 1

Views: 106

Answers (2)

SpiritCrusher
SpiritCrusher

Reputation: 21043

JsonObjectRequest which i assume is a volley request is an asynchronous task . So it will run background thread and code on UI thread run as on to end . That's the reason data variable is null .

Volley result back the callback on main thread so you can directly show toast or do Update UI inside callback methods .

 JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
               String data = response.getString("name"));
                Toast.makeText(getApplicationContext(), "Display: " + data,Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), error.toString(),Toast.LENGTH_SHORT).show();
        }
    });

NOTE:- if you want to define variable data previously then it has to be as instance variable(class level) . Because you can not use a non-final local variable inside inner class i.e Response.Listener .

Upvotes: 0

Merthan Erdem
Merthan Erdem

Reputation: 6058

You are probably accessing "data" at the wrong time, try showing the toast directly after it has been set, if it says null there aswell, data really is null. ( > and < to show an empty string, if it is empty).

Toast.makeText(getApplicationContext(), ">" + data+"<",Toast.LENGTH_SHORT).show();

Upvotes: 1

Related Questions