ashkufaraz
ashkufaraz

Reputation: 5297

List view getChildAt() is null

My code

public class Products extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.addproducts);
        FillList fillList = new FillList();
        fillList.execute("");

    }
    public class FillList extends AsyncTask<String, String, String> {

        List<Map<String, String>> prolist = new ArrayList<Map<String, String>>();
        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onPostExecute(String r) {


            String[] from = { "E","D", "C", "B","A"};
            int[] views = { R.id.lblMondeh,R.id.lblBes,R.id.lblBed,R.id.lblSharh,R.id.lblDate};
            final SimpleAdapter ADA = new SimpleAdapter(Products.this,
                    prolist, R.layout.lsttemplate, from,
                    views);
            lstSoratHesab.setAdapter(ADA);
            lstSoratHesab.setVisibility(View.VISIBLE);

        if(lstSoratHesab.getChildAt(0-lstSoratHesab.getFirstVisiblePosition())!=null)//all time this line is null
                lstSoratHesab.getChildAt(0).setBackgroundColor(Color.parseColor("#ff00aa63"));//i want change color first row

        }

        @Override
        protected String doInBackground(String... params) {

            Map<String, String> datanum = new HashMap<String, String>();

            datanum.put("E", "e");
            datanum.put("D", "d");
            datanum.put("C", "c");
            datanum.put("B", "b");
            datanum.put("A", "a");
            prolist.add(datanum);

        }
    }
}

I want set background color for first row.

why lstSoratHesab.getChildAt(0-lstSoratHesab.getFirstVisiblePosition()) or lstSoratHesab.getChildAt(0) all time is null?

But list view has 20 row

enter image description here

Upvotes: 1

Views: 226

Answers (2)

Blo
Blo

Reputation: 11978

getChildAt(0) will retrieve the first row element, but you will need to get it in a thread to let the time for the layout to be displayed on screen, which can be set as:

lstSoratHesab.post(new Runnable() {
    @Override
    public void run() {
        if (lstSoratHesab.getChildAt(0) != null) {
            lstSoratHesab.getChildAt(0)
                    .setBackgroundColor(Color.parseColor("#ff00aa63"));
        }
    }
});

Upvotes: 2

F43nd1r
F43nd1r

Reputation: 7749

I suspect that 0-lstSoratHesab.getFirstVisiblePosition() is negative. getChildAt always returns null for negative values.

Upvotes: 0

Related Questions