简体   繁体   中英

Not able to display the listView in android while getting the JSON data

This is my MainActivity.java :

package example.com.getdata;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
public static final String JSON_URL = "http://172.31.131.52:8081/application/status";
private Button buttonGet;
private ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buttonGet = (Button) findViewById(R.id.button2);

}
private void sendRequest(){
    StringRequest stringRequest = new StringRequest(JSON_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    showJSON(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();
                }
            });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
private void showJSON(String json) {
    Product product = new Product(json);
    ArrayList<JSONObject> listItems= product.parseJSON();
    listView = (ListView) findViewById(R.id.list_view);
    CustomList customerList = new CustomList(this,R.layout.list_view_layout,R.id.textViewName, listItems);
   //customerList.notifyDataSetChanged();
    listView.setAdapter(customerList);
}
public void clickHere(View v) {
    sendRequest();
}
}

Product.java

package example.com.getdata;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import static com.android.volley.VolleyLog.TAG;


public class Product {

public String productName;
public String description;
public int priceInDollars;
//public int productID;

public static final String KEY_Name = "productName";
public static final String KEY_Desc = "description";
//public static final String KEY_ID= "ProductID";
public static final String KEY_Price ="priceInDollars" ;

private JSONArray users = null;

private String json;

public Product(String json){
    this.json =json;
}

protected ArrayList<JSONObject> parseJSON(){
    JSONArray jsonArray=null;
    ArrayList<JSONObject> aList=new ArrayList<JSONObject>();
    try {
        jsonArray = new JSONArray(json);
        Log.d("Debugging...", jsonArray.toString());
        if(jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jo = jsonArray.getJSONObject(i);
                productName = jo.getString(KEY_Name);
                description = jo.getString(KEY_Desc);
                priceInDollars = jo.getInt(KEY_Price);
                aList.add(jsonArray.getJSONObject(i));
                // productID = jo.getInt(KEY_ID);
                }
            return aList;
        }
        else {
                Log.d(TAG, "parseJSON: Null condition");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}
}

CustomList.java

package example.com.getdata;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class CustomList extends ArrayAdapter<String> {

private ArrayList<JSONObject> list;

private int vg;
private Activity context;

public CustomList(Activity context,int vg, int id, ArrayList<JSONObject> list ) {
    super(context,R.layout.list_view_layout, id);
    this.vg = vg;
    this.context = context;
    this.list=list;
   // this.productID=productID;
}

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View listViewItem = inflater.inflate(vg, parent, false);
    TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
    TextView textViewDescription = (TextView) listViewItem.findViewById(R.id.textViewDescription);
    TextView textViewPrice = (TextView) listViewItem.findViewById(R.id.textViewPrice);
   // TextView textViewID = (TextView) listViewItem.findViewById(R.id.textViewID);
    try {
        textViewName.setText(list.get(position).getString("productName"));
        textViewDescription.setText(list.get(position).getString("description"));
        textViewPrice.setText(list.get(position).getString("priceInDollars"));
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
   // textViewID.setText(productID);
    return listViewItem;
}
}

I have tried and searched for answers online and I am still not able to figure out the problem. I am unable to see the list of objects. Through debugging, I am sure that the objects are read into the json objects, still I am not able to display the objects in a listView.

Any help is appreciated.

You need to crate constructor with all variables of Product class and put all values in Product class object and add into ArrayList .

See Product Class :

public class Product {

    public String productName;
    public String description;
    public int priceInDollars;
//public int productID;

    public static final String KEY_Name = "productName";
    public static final String KEY_Desc = "description";
    //public static final String KEY_ID= "ProductID";
    public static final String KEY_Price ="priceInDollars" ;

    private JSONArray users = null;

    private String json;

    public Product(String productName, String json, JSONArray users, int priceInDollars, String description) {
        this.productName = productName;
        this.json = json;
        this.users = users;
        this.priceInDollars = priceInDollars;
        this.description = description;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public static String getKEY_Name() {
        return KEY_Name;
    }

    public static String getKEY_Price() {
        return KEY_Price;
    }

    public String getJson() {
        return json;
    }

    public void setJson(String json) {
        this.json = json;
    }

    public JSONArray getUsers() {
        return users;
    }

    public void setUsers(JSONArray users) {
        this.users = users;
    }

    public static String getKEY_Desc() {
        return KEY_Desc;
    }

    public int getPriceInDollars() {
        return priceInDollars;
    }

    public void setPriceInDollars(int priceInDollars) {
        this.priceInDollars = priceInDollars;
    }
}

And When your are parsing your data you need to change like below code:

 protected ArrayList<Product> parseJSON(){
        JSONArray jsonArray=null;
        ArrayList<Product> aList=new ArrayList<Product>();
        try {
            jsonArray = new JSONArray(json);
            Log.d("Debugging...", jsonArray.toString());
            if(jsonArray != null) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jo = jsonArray.getJSONObject(i);
                    String productName = jo.optString(KEY_Name);
                    String description = jo.optString(KEY_Desc);
                    String priceInDollars = jo.optInt(KEY_Price);
                    Product product = new Product(productName,json,
                            jsonArray.getJSONObject(i),priceInDollars,description);
                    aList.add(product);
                    // productID = jo.getInt(KEY_ID);
                }
                return aList;
            }
            else {
                Log.d(TAG, "parseJSON: Null condition");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

Also you need to change in Adapter class where you have passes ArrayList<JsonArray> in this case you have to pass ArrayList<Product> .

You missed

@override
public int getCount()
{
    return list.size();
}

and make sure you either "setAdapter" on your listview after getting the json or call "notifydatasetchanged" method

Make sure getCount() is properly implemented in Adapterclass:

 @Override
 public int getCount(){
       return list.size();
 }

Use

super(context,R.layout.list_view_layout, list);

instead of

super(context,R.layout.list_view_layout, id);

将CustomList类扩展为:输入JSONObject而不是类型String

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