Write Json record in variable

Asked

Viewed 70 times

1

Hello, I am consuming a Json and I receive it in my fragment, taken only 2 records and saved in a variable created at the beginning of the class, the 2 of the String type, thus:

public void onResponse(JSONObject response) {

        Link link = new Link();
        JSONArray json = response.optJSONArray("link");
        JSONObject jsonObject = null;

        try {
            jsonObject = json.getJSONObject(0);
            link.setTitulo(jsonObject.optString("titulo"));
            link.setLink(jsonObject.optString("link"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        titulo = link.getTitulo().toString();
        linkWeb = link.getLink().toString();
        //Toast.makeText(getContext(), titulo + " - " + linkWeb, Toast.LENGTH_SHORT).show();
    }

I tested with Toast and it’s ok, The problem is that when I use these variables outside of this method, it’s like null. which is wrong?

1 answer

0


Your Jsonobject is being declared within the method onResponse(JSONObject response)

In order to access the variable in another method, it will be necessary to declare the same globally.

Ex:

Classe pai {
  JSONArray jsonArrayGlobal;
  JSONObject jsonObjectGlobal;

  public void onResponse(JSONObject response){
     try {
        jsonArrayGlobal = jsonArrayGlobal.optJSONArray("link");
        jsonObjectGlobal = jsonArrayGlobal.getJSONObject(0);
        restante do seu try...
     }catch(JSONException e) {...}
  }

  public void outroMetodo() {
       //Aqui voce pode chamar seu Json que ja esta declarado no metodo acima
  }
}
  • Vlw #Davi Ferreira, solved!

  • opa, good! I’m glad I helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.