如何存储多个JSON数组的项目并显示listview?

时间:2015-10-30 04:33:59

标签: android json android-listview textview

在我的应用程序中,我使用的是listview,我也在进行json解析。

现在问题是我想在我的视图中设置颜色,我从服务器获取颜色代码。

以下是我的json响应和java代码可以帮助我,在我的视图中设置颜色代码吗?

[
    {
        "id_product": "1445",
        "name": "Stylish Sleeveless Leather Vest",
        "price": 1990,
        "discount": 199,
        "colors": [
            "#000000",
            "#7E3517",
            "#C85A17"
        ],
        "sizes": [
            "Medium",
            "Large",
            "Small"
        ],
        "img_url": "",
        "popup_images": [

        ]
    },
    {
        "id_product": "1427",
        "name": "Stylish Slim Fit Designed PU Leather Jacket",
        "price": 3290,
        "discount": 329,
        "colors": [
            "#000000",
            "#C85A17"
        ],
        "sizes": [
            "Large",
            "Medium",
            "Small"
        ],
        "img_url": "",
        "popup_images": [

        ]
    }
]

MainActivity.java

public class Product_Listing extends Fragment{

    private ListView listview;


    private ArrayList<HashMap<String,String>> aList;
    private static String INTEREST_ACCEPT_URL = "";
   // private static final String INTEREST_ACCEPT="interestaccept";
    private static final String INTERESTACCEPT_USER_NAME="name";
    private static final String INTEREST_ACCEPT_PRICE="price";
    private static final String INTEREST_ACCEPT_PRODUCTID="id_product";
   private static final String INTEREST_ACCEPT_DISCOUNT="discount";
    private static final String INTEREST_ACCEPT_IMAGEURL="img_url";
    private static final String INTEREST_ACCEPT_COLOR="colors";
    private static final String INTEREST_ACCEPT_SIZES="sizes";
    private CustomAdapterAccept adapter;


    private String brandnms;
    String user_img;
    ArrayList<String> userImgArrayList;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
         View rootView = inflater.inflate(R.layout.product_listing_listivew, container, false);


         Bundle bundle = this.getArguments();
            brandnms = bundle.getString("Brandkeyword");
         listview=(ListView)rootView.findViewById(R.id.listview_productlistings);

            INTEREST_ACCEPT_URL = "";

            new LoadAlbums().execute();

         return rootView;
    }

    public class CustomAdapterAccept extends BaseAdapter{

        private Context context;
        private ArrayList<HashMap<String,String>> listData;
        private AQuery aQuery;
        String rup="\u20B9";
        private static final String TAG_NAME="name";
       private static final String TAG_IMAGE="img_url";
        private static final String TAG_PRICE="price";


        public CustomAdapterAccept(Context context,ArrayList<HashMap<String,String>> listData) {
            this.context = context;
            this.listData=listData;
            aQuery = new AQuery(this.context);
        }

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

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


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

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.product_listing_items, null);
               holder.propic = (ImageView) convertView.findViewById(R.id.productlist_img);
                holder.txtproname = (TextView) convertView.findViewById(R.id.productlist_name);
                holder.txtprice = (TextView) convertView.findViewById(R.id.productlist_price);
               // holder.txtpr = (TextView) convertView.findViewById(R.id.productlist_name);


                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            holder.txtproname.setText(listData.get(position).get(TAG_NAME));
            holder.txtprice.setText(listData.get(position).get(TAG_PRICE));


            aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.meracaslogo);

            // image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
            return convertView;
        }
        class ViewHolder{
            TextView txtprice;
            ImageView propic;
            TextView txtproname;
        }

    }
    class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
        private ProgressDialog pDialog;
        private String first;
        private String sizefirst;
        private JSONObject c;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Loading...");
            pDialog.setIndeterminate(true);
           // pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
            pDialog.setCancelable(false);
            pDialog.show();
        }
        protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
            ServiceHandler sh = new ServiceHandler();
            // Making a request to url and getting response
            ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
            String jsonStr = sh.makeServiceCall(INTEREST_ACCEPT_URL, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONArray jsonary = new JSONArray(jsonStr);

                    System.out.println("Test jsonObj"+jsonary);

                    // Getting JSON Array node
                  // interestaccept = jsonObj.getJSONArray(INTEREST_ACCEPT);

                    for (int i = 0; i < jsonary.length(); i++) {
                        c = jsonary.getJSONObject(i);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        map.put(INTERESTACCEPT_USER_NAME, c.getString(INTERESTACCEPT_USER_NAME));
                        map.put(INTEREST_ACCEPT_PRICE,c.getString(INTEREST_ACCEPT_PRICE));
                        map.put(INTEREST_ACCEPT_DISCOUNT, c.getString(INTEREST_ACCEPT_DISCOUNT));
                        map.put(INTEREST_ACCEPT_PRODUCTID, c.getString(INTEREST_ACCEPT_PRODUCTID));
                        map.put(INTEREST_ACCEPT_IMAGEURL, c.getString(INTEREST_ACCEPT_IMAGEURL));
                        //map.put(INTEREST_ACCEPT_AGE, c.getString(INTEREST_ACCEPT_AGE)+" years");
                        //map.put(INTEREST_ACCEPT_LOCATION, c.getString(INTEREST_ACCEPT_LOCATION));
                        // adding HashList to ArrayList

                        JSONArray colors=c.getJSONArray(INTEREST_ACCEPT_COLOR);
                        JSONArray sizes=c.getJSONArray(INTEREST_ACCEPT_SIZES);

                        user_img=c.getString(INTEREST_ACCEPT_COLOR);

                       // user_img=jsonObj.getString(USER_IMG);


                        user_img = "";
                        userImgArrayList = new ArrayList<String>();//declare userImgArrayList globally like ArrayList<String> userImgArrayList;
                        JSONArray picarray = c.getJSONArray(INTEREST_ACCEPT_COLOR);
                        for(int a=0;a< picarray.length();a++)
                        {
                            user_img = picarray.getString(a);
                            userImgArrayList.add(user_img);
                        }
                        Log.d("mylog", "curent  pro pic  = " + userImgArrayList);

                        first=userImgArrayList.get(i);
                        System.out.println("Color First"+first);

                        //first=colors.getJSONObject(a);

                       /* for(int j=0;j<colors.length();j++)
                        {
                            //first=colors.getJSONObject(j);

                        }

                        for(int s=0;s<sizes.length();s++)
                        {
                            sizefirst=sizes.getString(s);
                        }
                        System.out.println("Color First"+first);

                        System.out.println("Colors"+colors);*/
                        data.add(map);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }
            return data;
        }
        protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
            super.onPostExecute(result);

            // dismiss the dialog after getting all albums
            if (pDialog.isShowing())
                pDialog.dismiss();
            // updating UI from Background Thread
                aList = new ArrayList<HashMap<String, String>>();
                aList.addAll(result);
                adapter = new CustomAdapterAccept(getActivity(),result);
                listview.setAdapter(adapter);
                adapter.notifyDataSetChanged();

        }

    }

}

列表项

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="25dp"
        android:layout_marginTop="10dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="Colors:" />

        <TextView
            android:id="@+id/firstcolor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="7dp"
             />

        <TextView
            android:id="@+id/secondcolor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
             />

        <TextView
            android:id="@+id/thirdcolor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
             />

        <TextView
            android:id="@+id/fourthcolor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
             />
    </LinearLayout>

enter image description here

3 个答案:

答案 0 :(得分:2)

适配器内部 - &gt; getview方法会使视图膨胀并设置以下代码

view.setBackgroundColor(yourColorCode);

你可以从解析的json中获取颜色代码。

编辑:  在getView方法

getView(parameters)
{
your_current_object=objectList.get(position);
color_arraylist=your_current_object.colorsList;

if(color_arraylist.get(0)!=null)
textview1.setBackgroundColor(color_arraylist.get(0));
if(color_arraylist.get(1)!=null)
textview2.setBackgroundColor(color_arraylist.get(1));

//....so on..

}

如果color_arraylist.get(position)不能直接作为参数传递给setBackgroundColor(),则进行适当的类型转换。但我希望它能在没有任何类型转换的情况下工作。

答案 1 :(得分:2)

使用以下代码获取颜色的ArrayList

ArrayList<String> colorsList = new ArrayList<>();
JsonArray jarr = new JsonArray(result);

for(int i=0;i<jarr.length;i++)
{
  JsonArray color = jarr.get("colors");
  String myColor="";
  for(int k=0;k<color.length;k++){
    myColor = color.getString(k)+",";
  }
  colorsList.add(myColor);
}

从这段代码中你可以获得ArrayList,每个对象都包含逗号分隔的颜色为String。

使用此列表填充您的列表适配器,并在列表中获取每种颜色并用逗号分隔并将其用作背景颜色。

答案 2 :(得分:1)

您可以设置列表视图&#39;根据您的JSON响应下面的行颜色:

@Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.product_listing_items, null);
               holder.propic = (ImageView) convertView.findViewById(R.id.productlist_img);
                holder.txtproname = (TextView) convertView.findViewById(R.id.productlist_name);
                holder.txtprice = (TextView) convertView.findViewById(R.id.productlist_price);
               // holder.txtpr = (TextView) convertView.findViewById(R.id.productlist_name);


                convertView.setTag(holder);
            }else{

               **Add you code here for color.**       

                view.setBackgroundColor(listData.get(position).get(INTEREST_ACCEPT_COLOR));
                holder = (ViewHolder) convertView.getTag();
            }
            holder.txtproname.setText(listData.get(position).get(TAG_NAME));
            holder.txtprice.setText(listData.get(position).get(TAG_PRICE));


            aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.meracaslogo);

            // image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
            return convertView;
        }

编辑:

要显示TextView的颜色,首先应将所有颜色放在Hashmap中,然后将该hashmap传递给适配器。

现在,根据键,您可以为Textview设置颜色。

HashMap<String, String> hashmap;

在ArrayList中传递Hashmap的方法。

public ArrayList<HashMap<String, String>> getAllColor(String firstcolor , String second color , String thirdcolor)
    {
        ArrayList<HashMap<String, String>> array_list = new ArrayList<HashMap<String, String>>();


            hashmap = new HashMap<String, String>();
            hashmap.put("firstcolor", firstcolor);
            hashmap.put("second color",secondcolor);
            hashmap.put("thirdcolor",thirdcolor);

            array_list.add(hashmap);

        }
        return array_list;
    }

现在调用此方法传递颜色。并将你的Arraylist传递给你的 ADAPTER。。在getView()方法中,您可以通过以下键检索它:

**ArrayList<HashMap<String, String>> arrayList;** //全局声明

arrayList = "Your adapterList"; //在适配器的构造函数中声明

getView()中的

if (arrayList.size() != 0)
            {
                for (int i = 0; i < arrayList.size(); i++)
                {
                    textView1.setBackgroundColor(arrayList.get(i).get("firstcolor"));
                    textView2.setBackgroundColor(arrayList.get(i).get("secondcolor"));
                    textView3.setBackgroundColor(arrayList.get(i).get("thirdcolor"));

                }
             }

希望这次能解决你的问题。