Not able to set the background color of each item in a ListView when data is coming dynamically in android

StackOverflow https://stackoverflow.com/questions/22682257

Pregunta

I want to set the background color for the list which has the different values in an textbox like happy, sad coming from database and i want when in my text box happy comes background color changes to red and when angry it changes to green like this...

Here is my code....

class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Feeds.this);
            pDialog.setMessage("Loading Feeds. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All moods from url
         * */
        protected String doInBackground(String... args) {

            // Session class instance




            // get user data from session
            HashMap<String, String> user = session.getUserDetails();

            // email
            String email = user.get(SessionManage.KEY_EMAIL).toString();

            Log.d("seesion", email);
            // Building Parameters
            List<NameValuePair> para = new ArrayList<NameValuePair>();
            para.add(new BasicNameValuePair("email", email));

            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_get_moods, "GET",
                    para);

            // Check your log cat for JSON reponse
            Log.d("All Moods: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                Log.d("yjyth", Integer.toString(success));

                if (success == 1) {
                    String data = null;
                    // Moods found

                    // looping through All Products
                    for (int i = 1; i <= json.length(); i++) {
                        try {

                            JSONObject c = json.getJSONObject(Integer
                                    .toString(i));

                            Log.d("Loop", Integer.toString(i));
                            Log.d("Value of c", c.toString());

                            JSONObject dd = c.getJSONObject("data");
                            Log.d("value of dta", dd.toString());

                            String type = dd.getString("type");
                            Log.d("value of type", type);

                            String because = dd.getString("because");
                            Log.d("value of type", because);


                            String created = dd.getString("created");
                            Log.d("value of type", type);

                            String description = dd.getString("description");
                            Log.d("value of des", description);

                            //String datetime1 = dd.getString("datetime");
                             img=(ImageView)findViewById(R.id.imageFeeds);
                             LinearLayout l=(LinearLayout)findViewById(R.id.lisfeeds);
                            // creating new HashMap
                            HashMap<String, Object> map = new HashMap<String, Object>();

                            // adding each child node to HashMap key => value

                            map.put("type", type);
                            map.put("because", because);
                            map.put("description", description);
                            map.put("created", created);
                            if(type.equals("Feeling Happy")){
                                map.put("img", R.drawable.happyhov);
                                map.put("color", R.drawable.angrygrad);
                            }
                            else if(type.equals("Feeling Angry")){
                                map.put("img", R.drawable.angryhov);

                            }
                            else if(type.equals("Feeling Confused")){
                                map.put("img", R.drawable.confusdhov);

                            }

                            else if(type.equals("Feeling Confident")){
                                map.put("img", R.drawable.confihov);
                            }

                            else if(type.equals( "Feeling Frustrated")){
                                map.put("img",R.drawable.frusthov);
                            }

                            else if(type.equals("Feeling Lonely")){
                                map.put("img", R.drawable.loneyhov);
                            }
                            else if(type.equals("Feeling Ecstatic")){
                                map.put("img", R.drawable.esthov);
                            }
                            else if(type.equals("Feeling Sad")){
                                map.put("img",R.drawable.sadhov);
                            }


                            // adding HashList to ArrayList
                            moodsList.add(map);
                        } catch (Exception e) {
                            Log.e(" Parser", "Error data " + e.toString());
                        }
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(), Home.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
            MyAdapter adapter = new MyAdapter(Feeds.this,
                            moodsList, R.layout.item_list, 
                             new String[] {
                    "img",TAG_TYPE,TAG_BECAUSE, TAG_DESCRIPTION, TAG_CREATED},
                            new int[] { R.id.imageFeeds,R.id.type, R.id.texbec, R.id.des,R.id.date });
                    // updating listview
                    lv.setAdapter(adapter);
                }
            });


    }


    }

    class MyAdapter extends SimpleAdapter {

        private String[] names;
        private Activity c;


        public MyAdapter(Context context, List<? extends Map<String, ?>> data,
                int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
        }

        class ViewHolder {
            public TextView texttype,bec,des,date;
            public ImageView image;
          }

        public MyAdapter(Activity c, String[] names) {
            super(c, moodsList, R.layout.item_list, names, null);
            this.c = c;
            this.names = names;
          }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View vi = convertView;
            Context context = null;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            final ViewHolder holder;
            try {
                if (convertView == null) {
                    vi = inflater.inflate(R.layout.item_list, null);
                    holder = new ViewHolder();
                    holder.texttype = (TextView) vi.findViewById(R.id.type);
                    holder.image = (ImageView) vi
                        .findViewById(R.id.imageFeeds);
                    holder.bec = (TextView) vi.findViewById(R.id.texbec);
                    holder.des = (TextView) vi.findViewById(R.id.des);
                    holder.date = (TextView) vi.findViewById(R.id.date);
                    vi.setTag(holder);
                } else {
                    holder = (ViewHolder) vi.getTag();
                }
                Log.d("fchs","dfvhes");
               //holder.image.setBackgroundResource(TAG_IMAGE);
               holder.texttype.setText(TAG_TYPE);
               holder.bec.setText(TAG_TYPE);
               holder.des.setText(TAG_TYPE);

                if (TAG_TYPE.equals("Happy") ) {
                    vi.setBackgroundColor(Color.BLUE);

                } else {
                    vi.setBackgroundColor(Color.RED);
                }
            }catch(Exception e)
            {

            }
            return vi;
    }
    }
¿Fue útil?

Solución

Inside your custom adapter (SimpleAdapter) class --> got to --> public View getView Method make sure that your code is simmiler with this

        View vi = convertView;
        final ViewHolder holder;
        try {
            if (convertView == null) {
                vi = inflater.inflate(R.layout.my_group_list_item, null);
                holder = new ViewHolder();
                vi.setTag(holder);
            } else {
                holder = (ViewHolder) vi.getTag();
            }


            if (if sad if happy clause here ) {
                vi.setBackgroundColor(Color.parseColor("#a1cc3b"));

            } else {
                vi.setBackgroundColor(Color.parseColor("#cfd0d1"));
            }

hope this could help you.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top