1

Let's say I have this Dashboard.java:

public class DashboardActivity extends ActionBarActivity {

    private TextView login_response;
    private static String TAG = DashboardActivity.class.getSimpleName();

    final static String API_URL_ACCOUNT = "http://www.example.com/apiv2/account";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

        login_response = (TextView) findViewById(R.id.login_response);

        Intent intent = getIntent();

        if(intent.hasExtra("TOKEN"))
        {
            String token = intent.getStringExtra("TOKEN");

            getShopName(token);

        }
        else
        {
        }

And this is the getShopName method:

private void getShopName(String token) {
        JsonObjectRequest req = new JsonObjectRequest(API_URL_ACCOUNT + "?token=" + token, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            VolleyLog.v("Response:%n %s", response.toString(4));

                            JSONArray account = response.getJSONArray("account");
                            //Log.d(TAG, "Account: "+account.toString());

                            JSONObject shop = account.getJSONObject(0);
                            String name_shop = shop.getString("name_shop");


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.e("Error: ", error.getMessage());
            }
        });

        // add the request object to the queue to be executed
        VolleyController.getInstance().addToRequestQueue(req);

    }

My goal is to have

if(intent.hasExtra("TOKEN"))
        {
            String token = intent.getStringExtra("TOKEN");

            String shop_name = getShopName(token);

        }

The "shop_name" in variable, to reuse in other part.

So, I know that void doesn't return nothing, but, I tried to edit like this answer, without success:

How can I return value from function onResponse of Volley?

Thank you

Community
  • 1
  • 1
sineverba
  • 5,059
  • 7
  • 39
  • 84

1 Answers1

1

The issue is not returning a value from a JsonObjectRequest, but rather that you're trying to do an asynchronous operation in a synchronous way.

Here is a great explanation: Asynchronous vs synchronous execution, what does it really mean?

And to your specific question: I advise using an AsyncTask for your network operation.

Community
  • 1
  • 1
Vaiden
  • 15,728
  • 7
  • 61
  • 91