Create objects after external server response via API

Asked

Viewed 62 times

0

Here’s the thing, I created a php API that generates a Json. THE LINK IS THIS for those who want to view.

I was able to access the link and rescue the information, because I used a Toast to show them. But for some reason, which I don’t know, I can’t use this information to create objects.

Below is the function I’m using within Mainactivity:

listaHome = new ArrayList<>();

    RequestQueue request = Volley.newRequestQueue(getApplicationContext());

    JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, "http://qsmidia.com.br/androidTeste/", null,new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            try {
                JSONArray postagens = response.getJSONArray("anotacao");
                for (int i = 0; i < postagens.length(); i++){
                    JSONObject post = postagens.getJSONObject(i);
                    // aqui ele deveria adicionar a lista
                    listaHome.add(new Anotacoes(post.getString("id_anotacao"), post.getString("titulo"), post.getString("texto")));
                    // aqui ele mostra o título no toast (2 registros)
                    Toast.makeText(getApplicationContext(), post.getString("titulo"), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.i("Erro: ", e.getMessage());
                Toast.makeText(getApplicationContext(), "Erro exception > " + e.toString(), Toast.LENGTH_LONG).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), "Erro de resposta > " + error.getMessage(), Toast.LENGTH_LONG).show();
        }
      }
    );
    request.add(objectRequest);

That one listaHome is stated as private List<Anotacoes> listaHome; within the same function class.

Before you ask me I put it in the manifest:

<uses-permission android:name="android.permission.INTERNET" />

And on the premises:

compile 'com.android.volley:volley:1.1.0'

The List<Anotacoes> listaHome is empty, that is, no object is inserted.

One remark: When I TRY TO MANUALLY INSERT INSIDE THE TRY, ALSO NOT INSERTED. In this way:

try {
       JSONArray postagens = response.getJSONArray("anotacao");
       for (int i = 0; i < postagens.length(); i++){
          JSONObject post = postagens.getJSONObject(i);

          // aqui ele deveria inserir, mas não insere
          listaHome.add(new Anotacoes("1","Teste 1", "texto de teste 1"));

          // aqui ele mostra o título no toast (2 registros)
          Toast.makeText(getApplicationContext(), post.getString("titulo"), Toast.LENGTH_SHORT).show();
       }
     }

Why does this happen? How can I create objects and insert them into a list with the variables that are retrieved through the API?

1 answer

1


You want to fill in your list and then make use of it. However, the completion and use should take place one after the other. I believe in your code this is not happening.

First you are declaring the list:

listaHome = new ArrayList<>();

then declares your HTTP request:

JsonObjectRequest objectRequest = new JsonObjectRequest( ... );
request.add(objectRequest);

and then probably try to use the list (that part is not in the code you included in the question, but I am deducing).

Keep in mind that the HTTP request is being declared more will not be executed immediately. So if you want to use the list next to that statement you will have to wait for it to run and at the end of that run make use of the list, and do not try to use immediately after the statement.

In other words, the correct thing would be for you to move the code that makes use of the list to right after the block for who is filling in the list.

  • Got it. HTTP request is executed here request.add(objectRequest); right?

  • 1

    Then it is placed in the execution queue. When this line request.add(objectRequest); finish executing the request has not yet been executed. So if the code that comes under that line is waiting for the list to be filled in, it won’t be. Execution will be done later (asynchronously). The correct place to make use of the filled-in list is just below the blog for.

  • 1

    Thank you so much! I was burning the "fuzivi" here.

Browser other questions tagged

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