使用JSONObject在Listview中填充Listview绑定

时间:2014-08-05 09:30:57

标签: android android-layout listview android-listview android-adapter

您好我是一个python的人试图为我们的python团队创建一个框架应用程序,我从我的Android应用程序调用一个函数到python服务,并作为回报获取一个JSONObject,它将具有以下方式的对象。对象中的元素数量将是动态的,但JSONObject的结构将是相同的:

{
    'Data': [
        {
            'Title': 'XPSi1',
            'WarehouseData': [
                {
                    'WareHouse1': '10'
                },
                {
                    'WareHouse2': '20'
                }
            ]
        },
        {
            'Title': 'XPSi2',
            'WarehouseData': [
                {
                    'WareHouse1': '10'
                },
                {
                    'WareHouse2': '20'
                }
            ]
        }
    ]
}

我想在我的列表视图中显示如下所示的数据:

XPS i3

芝加哥仓库:15

伯明翰仓库:20

贵公司:16

XPS i5

芝加哥仓库:0

伯明翰仓库:2

贵公司:5

XPS i7

芝加哥仓库:5

伯明翰仓库:0

贵公司:10

。 。 。 。

现在因为这是一个JSONObject而我无法将其转换为hashmap,所以创建了一个自定义适配器:

// Custom hashmap adapter for displaying stock data for product.template


public class TemplateMapAdapter extends BaseAdapter {
//      JSONObject return_data;
        private final JSONObject mData;

        public TemplateMapAdapter(JSONObject jName) {
            mData = new JSONObject();
            try {
                mData.getJSONObject(jName.toString());
                Log.i("JSON", "mData-----"+mData);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

//      @Override
//      public int getCount() {
//          return mData.size();
//      }
//
//      @Override
//      public Map.Entry<String, String> getItem(int position) {
//          return (Map.Entry) mData.get(position);
//      }

        @Override
        public long getItemId(int position) {
            // TODO implement you own logic with ID
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final View result;

            if (convertView == null) {
                result = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.product_stockview_layout, parent, false);
            } else {
                result = convertView;
            }

//          Map.Entry<String, String> item = getItem(position);

            ((TextView) result.findViewById(R.id.textViewProductName)).setText(mData.getString("name"));

            mView = getActivity().getLayoutInflater().inflate(R.id.listViewWarehouse,
                     parent, false);
            Log.i("mData value-------",mData.getString("name")+"");
            Log.i("result-------",result.toString()+"");
            mView = createListViewRow(mView, position,item.getValue());
                return mView;


            return result;
        }
    }

    @SuppressLint("CutPasteId")
    private View createListViewRow(View mView, final int position,JSONObject moveLinesObjectData) {

//      final OEDataRow row = (OEDataRow) moveLinesObjectData.get(position);
        TextView txtProductName = (TextView) mView.findViewById(R.id.txtMoveLineName);
        txtProductName.setText(row.getString("name"));

        TextView txtProductQty = (TextView) mView.findViewById(R.id.txvQuantity);
        txtProductQty.setText(row.getString("product_qty"));

        TextView txtProductState = (TextView) mView.findViewById(R.id.txvStatus);
        txtProductState.setText(row.getString("state"));
        return mView;
    }

我知道它非常不合适,并准备废弃整个代码,但请指出正确的方向,过去几天我一直坚持这个。

2 个答案:

答案 0 :(得分:2)

JSON STRING FORMAT:

{
    'Data': [
        {
            'Title': 'XPSi1',
            'WarehouseData': [
                {
                    'data': 'WareHouse1: 10'
                },
                {
                    'data': 'WareHouse2: 20'
                }
            ]
        },
        {
            'Title': 'XPSi2',
            'WarehouseData': [
                {
                    'data': 'WareHouse1: 10'
                },
                {
                    'data': 'WareHouse2: 10'
                }
            ]
        }
    ]
}

<强> ADAPTER:

public class TemplateMapAdapter extends BaseAdapter {

        private final JSONArray mData;

        public TemplateMapAdapter(JSONArray mData) 
        {
        try {
               this.mData = mData.getJSONArray("Data");
            } catch (JSONException e) {

                e.printStackTrace();
            }


        }

      @Override
      public int getCount() {
          return mData.length();
      }

        @Override
        public long getItemId(int position) 
       {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            convertView = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.product_stockview_layout, parent, false);

            TextView Header =(TextView) convertView.findViewById(R.id.textViewProductName)
            TextView Content =(TextView) convertView.findViewById(R.id.textViewWarehouse)

            try {
            String strHeader  = mData.getJSONObject(position).getString("Title");
            JsonArray dataArr = mData.getJSONObject(position).getJSONArray("WarehouseData");
            String strData="";
            for(int i = 0; i<dataArr.length(); i++)
        {
               strData += dataArr.getJSONObject(i).getString("data")+"\n\n"
            }
            Header.setText(strHeader);
            Content.setText(strData);
               } catch (JSONException e) {

                e.printStackTrace();
            }
            return convertView; 
        }
    }

XML FOR ROW:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 

<TextView 
android:id="@+id/textViewProductName" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="Pname" 
android:textAppearance="?android:attr/textAppearanceLarge" 
android:textStyle="bold" /> 

<TextView 
android:paddingLeft="25dp" 
android:id="@+id/textViewWarehouse" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:textAppearance="?android:attr/textAppearanceMedium" 
android:text="Wname" /> 
</LinearLayout>

答案 1 :(得分:1)

请尝试这种方式,希望这有助于您解决问题。

<强> activity_main.xml中

<ListView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<强> list_item.xml

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

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="20sp"/>

    <TextView
        android:id="@+id/txtWareHouse1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="16sp"/>

    <TextView
        android:id="@+id/txtWareHouse2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="16sp"/>

    <TextView
        android:id="@+id/txtCompany"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="16sp"/>

</LinearLayout>

<强> MainActivity.java

public class MainActivity extends Activity {

    private ListView listView;
    private ArrayList<HashMap<String,String>> listData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);

        try{
            listData = new ArrayList<HashMap<String, String>>();
            String jsonResponse = "{'Data':[{'Title':'XPS i1','WarehouseData':[{'WareHouse1':'10'},{'WareHouse2':'20'}],'Company':'05'},{'Title':'XPS i2','WarehouseData':[{'WareHouse1':'10'},{'WareHouse2':'20'}],'Company':'10'}]}";

            JSONObject dataJson = new JSONObject(jsonResponse);
            JSONArray dataArray = dataJson.getJSONArray("Data");
            for (int i=0;i<dataArray.length();i++){
                HashMap<String,String> row = new HashMap<String, String>();
                row.put("Title",dataArray.getJSONObject(i).getString("Title"));
                JSONArray whereHouseArray = dataArray.getJSONObject(i).getJSONArray("WarehouseData");
                row.put("WareHouse1",whereHouseArray.getJSONObject(0).getString("WareHouse1"));
                row.put("WareHouse2",whereHouseArray.getJSONObject(1).getString("WareHouse2"));
                row.put("Company",dataArray.getJSONObject(i).getString("Company"));
                listData.add(row);
            }
            listView.setAdapter(new CustomAdapter(this,listData));
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(MainActivity.this,listData.get(position).get("Title"),Toast.LENGTH_SHORT).show();
                }
            });

        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    class CustomAdapter extends BaseAdapter{

        private Context context;
        private ArrayList<HashMap<String,String>> data;
        public CustomAdapter(Context context,ArrayList<HashMap<String,String>> data){
            this.context = context;
            this.data = data;
        }

        class ViewHolder{
            TextView txtTitle;
            TextView txtWareHouse1;
            TextView txtWareHouse2;
            TextView txtCompany;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if(convertView==null){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.list_item,null);
                holder.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
                holder.txtWareHouse1 = (TextView) convertView.findViewById(R.id.txtWareHouse1);
                holder.txtWareHouse2 = (TextView) convertView.findViewById(R.id.txtWareHouse2);
                holder.txtCompany = (TextView) convertView.findViewById(R.id.txtCompany);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            holder.txtTitle.setText(data.get(position).get("Title"));
            holder.txtWareHouse1.setText("Chicago Warehouse: "+data.get(position).get("WareHouse1"));
            holder.txtWareHouse2.setText("Birmingham Warehouse: "+data.get(position).get("WareHouse2"));
            holder.txtCompany.setText("Your Company: "+data.get(position).get("Company"));
            return convertView;
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

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