2

In my application I am using listview and I am also doing json parsing.

Now the issue is I want to set colors in my views, the color code I am getting from server.

Following is my json response and java code can any one help me, to set color codes in my views?

[
    {
        "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();

        }

    }

}

listitem

 <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 Answers 3

2

Use Following code to get ArrayList of colors

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);
}

From this code you can get ArrayList with each object contains comma seperated colors as String.

Fill Your list adapter with this list and in your list get each color and split it by comma and use it as your background color.

Sign up to request clarification or add additional context in comments.

Comments

2

Inside the adapter-> getview method inflate your view and set the following code

view.setBackgroundColor(yourColorCode);

you can take your color code from the parsed json.

EDIT: In the getView method

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..

}

And do appropriate type casting if color_arraylist.get(position) cant be directly passed as a parameter to setBackgroundColor(). But i hope it will work without any typecasting.

2 Comments

@Harikishan i have textview in my listitem..and in my arraylist i am getting all the color code which is in response..so i want to set as per index..like in first array three color are there..so in my first item i want to set them in my textview,..then in second item i have two color code so i want to set that two color code in my second item..
Ok. While parsing json, set the colors in an arraylist of strings and you can set each colors to each textview by taking the colors from their respective positions
1

You can set listview' row color as per your JSON response below :

@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;
        }

EDIT :

For showing colors to your TextView , you should first put all the colors in Hashmap and pass that hashmap to your adapter.

Now on the basis of keys you can set colors to your Textview.

HashMap<String, String> hashmap;

Method for passing Hashmap in ArrayList.

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;
    }

Now Call this method for passing your colors. And pass your Arraylist to your ADAPTER .. And In getView() method you can retrieve it by keys like below :

**ArrayList<HashMap<String, String>> arrayList;** // declare globally

arrayList = "Your adapterList"; // declare in adapter's constructor

in 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"));

                }
             }

Hope this time it will solve your problem.

5 Comments

i have textview same as like txtprice..to set my colors..how to set that?
So where you want to set color , I mean in TextView's background or Listview row's background ?
but i dont have indiuvidual key for all colors
I think here you are getting JSONArray picarray = c.getJSONArray(INTEREST_ACCEPT_COLOR); for(int a=0;a< picarray.length();a++) { user_img = picarray.getString(a); userImgArrayList.add(user_img); }. just pass userImgArrayList(0) , userImgArrayList(1) ,userImgArrayList(2) in method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.