How do I grab each JSON object, add it to a list, and show it in Activity?

Asked

Viewed 1,132 times

0

I have to develop an Ecommerce app and I have a question about lists. I’m getting a JSON with some product data from an API and I’m trying to take each object of that JSON, put it in a list and show each product with its data in an Activity. But I have tried everything and still do not list anything, the screen is blank

JSON that is returned

[
  {
  "id": 7,
  "name": "Repelente Premium Bite Stop",
  "price": "35.5000",
  "description": "O repelente Premium Bite Stop é indicado para cães, gatos, 
                  cavalos, ferrets e roedores. Protege objetos e móveis que os 
                  animais possam lamber, mastigar ou morder. Pode ser utilizado 
                  sobre a pele para desencorajar automutilação e para proteção de 
                  talas, feridas pós-cirúrgicas e curativos. Não é tóxico.",
  "discountPromotion": "0.00",
  "activeProduct": 1,
  "minimumStockQuantity": 30,
  "image": "FFD8FFE000104A46494600010101006000600000FFE100224578696600004D4D002A000000...",
  "categoryId": 3
 },
 {
  "id": 6,
  "name": "Dry Shampoo Banho a Seco",
  "price": "25.0000",
  "description": "Indicado para:\r\n\r\nCachorro, todas as raças;\r\nA partir de 
                  2 meses de idade;\r\nA embalagem é de 150ml;\r\nPet Clean / 
                  Linha Shampoo Banho Seco;\r\n\r\nBenefícios:\r\n\r\nEconomiza 
                  água e deixa seu pet limpo e cheiroso;\r\nFácil e prático de 
                  aplicar;\r\nIndicado para todos os tipos de pelo;\r\nNão 
                  precisa enxágue;\r\nAroma de Morango e Limonada;",
  "discountPromotion": "3.00",
  "activeProduct": 1,
  "minimumStockQuantity": 10,
  "image": ""FFD8FFE000104A46494600010101006000600000FFDB0043...",
  "categoryId": 5
 }
]

Mainactivity code

import java.text.NumberFormat;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ListView list_products;
    private ImageView product_picture;
    private TextView product_name;
    private TextView product_price;
    private TextView product_description;
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;


    List<Product> products = new ArrayList<Product>();


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

        NetWorkCall myCall = new NetWorkCall();
        myCall.execute("http://kanino-pi4.azurewebsites.net/Kanino/api/produtos");

        list_products = (ListView) findViewById(R.id.list_products);
        product_name = (TextView) findViewById(R.id.product_name);
        product_price = (TextView) findViewById(R.id.product_price);
        product_description = (TextView) findViewById(R.id.product_description);

        ArrayAdapter<Product> adapter = new ArrayAdapter<Product>(this, android.R.layout.simple_list_item_1, products);
        list_products.setAdapter(adapter);


        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //--------------NAVIGATION VIEW---------------------
        navigationView = (NavigationView) findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener(){
                    public boolean onNavigationItemSelected(MenuItem menuItem){
                        if(menuItem.isChecked()){
                            menuItem.setChecked(false);
                        }else{
                            menuItem.setChecked(true);
                        }

                        drawerLayout.closeDrawers();
                        if(menuItem.getItemId() == R.id.action_product){
                            ProductFragment fragment = new ProductFragment();
                            getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, fragment).commit();
                            return true;
                        }
                        if(menuItem.getItemId() == R.id.action_login){
                            LoginFragment fragment = new LoginFragment();
                            getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, fragment).commit();
                            return true;
                        }
                        if(menuItem.getItemId() == R.id.action_register){
                            RegisterFragment fragment = new RegisterFragment();
                            getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, fragment).commit();
                            return true;
                        }
                        if(menuItem.getItemId() == R.id.action_register){
                            RegisterFragment fragment = new RegisterFragment();
                            getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, fragment).commit();
                            return true;
                        }
                        return false;
                    }
                }
        );

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer);

        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.openDrawer, R.string.closeDrawer){};
        drawerLayout.setDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();
        //--------------------------------------------------------
    }

    public boolean onOptionsItemSelected(MenuItem item){
        if(actionBarDrawerToggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);
    }



    public class NetWorkCall extends AsyncTask<String, Void, String>{
        @Override
        protected String doInBackground(String... params) {
            try{
                HttpURLConnection urlConnection = (HttpURLConnection) new URL(params[0]).openConnection();
                urlConnection.setConnectTimeout(4000);
                InputStream in =  urlConnection.getInputStream();
                BufferedReader bufferedReader =  new BufferedReader(new InputStreamReader(in, "UTF-8"));
                StringBuilder resultado = new StringBuilder();
                String linha = bufferedReader.readLine();



                while(linha != null){
                    resultado.append(linha);
                    linha = bufferedReader.readLine();
                }

                String respostaCompleta = resultado.toString();

                return respostaCompleta;

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(String result){
            super.onPostExecute(result);
            try{
                JSONArray json = new JSONArray(result);
                for(int i = 0; i < json.length(); i++) {
                    JSONObject j = json.getJSONObject(0);
                    Product product =  new Product(j.getInt("id"),
                                                   j.getString("name"),
                                                   j.getString("price"),
                                                   j.getString("description"),
                                                   j.getString("discountPromotion"),
                                                   j.getInt("activeProduct"),
                                                   j.getInt("minimumStockQuantity"),
                                                   j.getString("image"));
                    addAtTheList(product);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void addAtTheList(Product product){
            products.add(product);
        }
    }
}
  • So Francisco, has a framework called Retrofit, she and for deserialization of Json called Gson, may help you in what you need

  • Oh thanks for the tip Matheus, I’ll take a look yes

1 answer

1


Ideally, you can create object classes with attribute names identical to those of json (or if you prefer you can map using the @Serializedname annotation). I suggest you download the Gson library for serialization and deserialization of json. What this library will do is turn json’s into objects and json’s objects

Example:

public class Produto{
    private int id; //Ou String se preferir
    private String name;
    private float price;
    //outros atributos, getters e setters
}

For in case an object would be:

String produtoJson = "{\"id\": 7,\"name\": \"Repelente Premium Bite Stop\",\"price\":\"35.5000\"}"
Produto produto = new Gson().fromJson(produtoJson,Produto.class);

But in your case, you are working with a json array, so it is necessary to deserialize the json in a List or Array, so:

String variosProdutosJson = "[{\"id\": 7,\"name\": \"Repelente Premium Bite Stop\",\"price\":\"35.5000\"},{\"id\": 8,\"name\": \"Produto Y\",\"price\":\"45.5000\"},{\"id\": 9,\"name\": \"Produto X\",\"price\":\"15.5000\"}]"
List<Produto> produtos = new Gson().fromJson(variosProdutosJson, new TypeToken<List<Produto>>(){}.getType());

Hugs

  • Thank you very much, it worked the way I wanted xD

  • What a great partner :) XD

Browser other questions tagged

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