-1

i want to set the background color of listview using java... Below is the code in which i want to set the background color of list view.
value in the name,address,varificationtype comes from server. now i want to set the background color of listview to RED.
I already defined

 public class GetLead extends ListActivity implements OnClickListener{

    private ProgressDialog pDialog;

    // URL to get contacts JSON
//    private static String url = "104.25.125.70/verification/getCaf";

    // JSON Node names

    private static final String TAG_ID = "cid";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
//    private static final String TAG_CONTACTS = "contacts";
//    
        String priority="high";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_STATUS = "status";

    private static final String TAG_VARTYPE = "verification";
    private long backPressedTime = 0; 

    GlobalClass gclass;


    // contacts JSONArray
    JSONArray contacts = null;
    Button refresh, logout;
    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_getjson);

    //  startService(new Intent(this, LocationBackgroundService.class));
        contactList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                // getting values from selected ListItem
                String custid = ((TextView) view.findViewById(R.id.custId))
                        .getText().toString();
                String name = ((TextView) view.findViewById(R.id.name))
                        .getText().toString();
                String address = ((TextView) view.findViewById(R.id.address))
                        .getText().toString();

                String verType = ((TextView) view.findViewById(R.id.verificationType))
                        .getText().toString();

                // Starting single contact activity

                if(verType.equals("reside")){
                    Intent in = new Intent(getApplicationContext(),
                            resideVarStatusUpdate.class);
                    in.putExtra(TAG_ID, custid);
                    in.putExtra(TAG_NAME, name);
                    in.putExtra(TAG_ADDRESS, address);
                    startActivity(in);
                }
                else if(verType.equals("reside1")){
                     Intent in = new Intent(getApplicationContext(),
                            reside1VarStatusUpdate.class);
                    in.putExtra(TAG_ID, custid);
                    in.putExtra(TAG_NAME, name);
                    in.putExtra(TAG_ADDRESS, address);
                    startActivity(in);
                }

            }
        });

        // Calling async task to get json
        new GetContacts().execute();

        refresh = ((Button) findViewById(R.id.refresh));
        refresh.setOnClickListener(this);

        logout = ((Button) findViewById(R.id.logout));
        logout.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        if (v == refresh){
            new GetContacts().execute();
        }
        else if (v == logout){
            this.finish();
        }
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(GetLead.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            String jsonStr = null;
            // get user data from session
            final GlobalClass globalVariable = (GlobalClass) getApplicationContext();

            ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("id",globalVariable.getId()));

            // email
            try {
                jsonStr = SimpleHttpClient
                        .executeHttpPost(
                                "http://"+constantVar.ip+"/verification/getCaf",
                                postParameters);
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

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

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    contacts = jsonObj.getJSONArray("data");


                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String address = c.getString(TAG_ADDRESS);
                        String status = c.getString(TAG_STATUS);
                        String varType = c.getString(TAG_VARTYPE);


                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ID, id);
                        contact.put(TAG_NAME, name);
                        contact.put(TAG_ADDRESS, address);
                        contact.put(TAG_STATUS, status);
                        contact.put(TAG_VARTYPE, varType);
                        contact.put("priority", priority);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(GetLead.this, contactList, R.layout.list_item, new String[]{TAG_ID, TAG_NAME, TAG_ADDRESS, TAG_VARTYPE, priority}, new int[]{R.id.custId,
                    R.id.name, R.id.address, R.id.verificationType});
            if (priority.equals("high")) {
                setListAdapter(adapter);
                LinearLayout listLayout = (LinearLayout)findViewById(R.id.list_layout);
                listLayout.setBackgroundColor(Color.GREEN);

            }

        }

    }

How can I do this only using Java here?

AARUSH
  • 3
  • 2
  • The reason your code isn't working is because you're trying to `setBackgroundColor()` on an object representing/handling the data, not the actual list object itself. You need to get the actual `ListView` instance from your layout, then call `setBackgroundColor()` on that object. `ListAdapter` is not the same thing as `ListView`. – Andrew Gies Jul 19 '16 at 10:46
  • You have to make your custom adapter class witch inflates your own created layout and in this adapter class you must check if priority is "high" to set layout's parent view background color. Check this answer : http://stackoverflow.com/a/8166802/5519005 – Lubomir Babev Jul 19 '16 at 10:46

3 Answers3

0

Update your code in onPostExecute()

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

        final ListAdapter adapter = new SimpleAdapter(GetLead.this, contactList, R.layout.list_item, new String[]{TAG_ID, TAG_NAME, TAG_ADDRESS, TAG_VARTYPE, priority}, new int[]{R.id.custId,
                R.id.name, R.id.address, R.id.verificationType});

        if (priority.equals("high")) {
            GetLead.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setListAdapter(adapter);
                    getListView().setBackgroundColor(getResources().getColor(R.color.colorAccent));
                }
            });
        }
    }
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41
0

You should do this in your adapter, override getView like this:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.custom_event_row_view, parent, false);
        convertView.setBackgroundColor(Color.RED);

Now you can set the color of each entry as you wish.

Vucko
  • 7,371
  • 2
  • 27
  • 45
0

Actually you have to set the layout background color used in xml to set color accordingly.

if (priority.equals("high")) {
LinearLayout listLayout = listItem.findViewByid(R.id.list_layout);
    listLayout.setBackground(R.color.Red)
                setListAdapter(adapter);
            }
Wilson Christian
  • 650
  • 1
  • 6
  • 17