简体   繁体   中英

failed to process json data in android

[{"acteurid":"86744570","productions":[{"variete":"Riz","recolte":"10000"}],"nom":"Charles Diouf"},{"acteurid":"6535150","productions":[{"variete":"Riz","recolte":"1000"}],"nom":"Daba Diouf"},{"acteurid":"86817462","productions":[{"variete":"Riz","recolte":"8000"}],"nom":"Diel Ndour"},{"acteurid":"14047190","productions":[{"variete":"Ble","recolte":"10000"},{"variete":"Mais","recolte":"1000"},{"variete":"Mais","recolte":"2000"},{"variete":"Riz","recolte":"5000"},{"variete":"Ble","recolte":"8000"}],"nom":"Hamady Diouf"}]

How do i read the above json data? I want to display it in a ListView as follows:

  1. nom
  2. variete
  3. recolte
  4. .variete
  5. .recolte
  6. . . . .
  7. nom
  8. variete
  9. recolte

I tried the following code but the list isn't showing. I have

FATAL EXCEPTION: main
java.lang.NullPointerException at 
       pcom.jsontest.MyCustomAdapter.getView(MyCustomAdapter.java:32)

code is

for(int i=0;i<jarray.length();i++){
            JSONObject json=jarray.getJSONObject(i);

            JSONArray prodar=json.getJSONArray("productions");
            for(int j=0;j<prodar.length();j++){
                JSONObject prod=prodar.getJSONObject(j);
                Production production = new Production(prod.getString("variete"),prod.getString("recolte"));
                productions.add(production);
            }

            Producteur producteur=new Producteur(json.getString("acteurid"),productions,json.getString("nom"));
            producteurs.add(producteur);
        }


MyCustomAdapter adapter = new MyCustomAdapter(this,producteurs);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);

Custom array adapter

public class MyCustomAdapter extends ArrayAdapter<Producteur> {
    public MyCustomAdapter(Context context, ArrayList<Producteur> prods) {
        super(context, 0, prods);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        Producteur producteur = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
        }
        // Lookup view for data population
        TextView name = (TextView) convertView.findViewById(R.id.name);
        name.setText(producteur.getNom());

        ArrayList<Production> productions=producteur.getProductions();
        ListView listprod = (ListView) convertView.findViewById(R.id.list);
        ArrayAdapter<Production> productionsAdapter = new ArrayAdapter<Production>(getContext(), R.layout.list_prod_item, productions);
        listprod.setAdapter(productionsAdapter);

       // Return the completed view to render on screen
        return convertView;
    }
}

list_item.xml

 <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/nom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    </LinearLayout>

list_prod_item.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/variete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/recolte"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>

To complete dilix's example, let's say your model is called Producteur :

public class Producteur {
    // Private attributes
    private int mId;
    // List of Produit, which is another model or object (call it however you want) created by you.
    private List<Produit> mProduits;
    private String mNom;

    // Attributes getters and setters (they are optionnal in this example, but it's always good idea to have them)
    public int get_mId() { return this.mId; }
    public void set_mId(int id) { this.mId = id; }

    public List<Produit> get_mProduits() { return this.mProduits; }
    public void set_mProduits(List<Produit> produits) { this.mProduits = produits; }

    public String get_mNom() { return this.mNom; }
    public void set_mNom(String nom) { this.mNom= nom; }

    // Constructor
    public Producteur(int id, List<Produit> produits, String nom) {
        this.mId = id;
        this.mProduits = produits;
        this.mNom = nom;
    }
}

And then you would have your model Produit which would represent one of a productor's product:

public class Produit {
    // A product has two attributes: variete and recolte. I'll let you complete 
    // this class, you can inspire yourself of the above example.
}

Now it's time to use these two objects in your data reading:

// Instead of a hashmap, we'll be using a list of "Producteur"
List<Producteur> producteurs = new List<Producteur>();
JSONArray jarray=new JSONArray(resSel);
//String acteur_id="";
for(int i=0;i<jarray.length();i++){
    JSONObject json = jarray.getJSONObject(i);

    int id = json.getInt("acteurid");
    // Note the name is not part of the "productions" JSONArray
    String nom = json.getString("nom");

    // Here we'll declare the productor's productions
    List<Produit> productions = new List<Produit>();

    JSONArray prodar=json.getJSONArray("productions");
    for(int j=0;j<prodar.length();j++){
        JSONObject prod=prodar.getJSONObject(j);
        String variete = prod.getString("variete");
        int recolte = Integer.parseInt(prod.getString("recolte"));

        // We'll create a new "Produit" at each loop and add it to the productor's product list.
        Produit unProduit = new Produit(variete, recolte);
        productions.add(unProduit);
    }

    // We'll create a new productor at each loop and add it to the productors list
    Producteur unProducteur = new Producteur(id, productions, nom); 
    producteurs.add(unProducteur);
}

Then, to add it in a listView, you would use an ArrayAdapter<Producteur> :

ListView listprod = (ListView)findViewById(R.id.list);
// We will passe the list of "Producteur" we just created above as the objects to represent in the ListView
ArrayAdapter<Producteur> producteursAdapter = new ArrayAdapter<Producteur>(this, R.layout.list_item, producteurs);
listprod.setAdapter(producteursAdapter);

Note that this is the most basic way to show your Productors in the ListView. Check this link if you want to customize your objects display.

If you visualize you json for example by http://json.parser.online.fr/ You'll see hierarchy of the whole JSON.

From this point I'd recommend you to have you model as:

public class Model {
    int mId;
    List<Product> mProducts;
    String mName;
}

You should be able to parse your json according to this model and then use it to visualize you item in list or wherever you want.

For example when you have

List<Model>;

You could use

ArrayAdapter<Model>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM