0

I am new to android. I searched the web and found how to do a simple array adapter that will show all the contacts saved on your device in a list view. The code was running well until I was asked to do it in background.

When I update the code to do it in AsyncTask the items of the list view are added with a defalut white color as the background color and you can see what is written in the row when you click on the item.

 public class MainActivity extends Activity {

    ListView lv;
    ArrayAdapter<String> adapter;
    public String num1;
    ArrayList<String> arr = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv=(ListView) findViewById(R.id.listView1);
        progress=(ProgressBar) findViewById(R.id.progressBar1);

        new background().execute();
    public class background extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            displayContacts();
            return "success";
        }
        @Override
        protected void onPostExecute(String result) {
          Toast.makeText(getApplicationContext(), "Connection successfull "+result, Toast.LENGTH_SHORT).show();
          String [] values=arr.toArray(new String[arr.size()]);
            adapter = new ArrayAdapter<String>(getApplicationContext(),
                    android.R.layout.simple_list_item_1, android.R.id.text1, values);

            // Assign adapter to ListView
            lv.setAdapter(adapter);
            lv.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                      // ListView Clicked item index
                      int itemPosition     = position;

                      // ListView Clicked item value
                      String  itemValue    = (String) lv.getItemAtPosition(position);

                       // Show Alert 
                       Toast.makeText(getApplicationContext(),
                         "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                         .show();
                     }

            }); 

            registerForContextMenu(lv);
            progress.setVisibility(View.GONE);
        }

    }
    @Override
      public void onCreateContextMenu(ContextMenu menu, View v,
              ContextMenuInfo menuInfo) {

          super.onCreateContextMenu(menu, v, menuInfo);
          AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;

          // We know that each row in the adapter is a Map
          String num= adapter.getItem(aInfo.position);
          this.num1=num;
          menu.setHeaderTitle("Options for " + num);
          menu.add(1, 1, 1, "Send ");
          menu.add(1, 2, 2, "Delete");

      }

    public boolean onContextItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        // Implements our logic
        // Toast.makeText(this, "Item id ["+itemId+"]",
        // Toast.LENGTH_SHORT).show();
        if (itemId == 1) {
            Toast.makeText(this, "number is:"+this.num1, Toast.LENGTH_LONG).show();
        }
        return true;
    }
    private void displayContacts() {
            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                    null, null, null, null);
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cur.getString(
                            cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                         Cursor pCur = cr.query(
                                 ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                                 null, 
                                 ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                                 new String[]{id}, null);
                         while (pCur.moveToNext()) {
                             String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    //                       Toast.makeText(this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_LONG).show();
                             arr.add(phoneNo);
                         } 
                    pCur.close();
                }
                }
            }
        }

the displayContacts() will add all the contacts to the ArrayList arr that will be used to be displayed in the list view.

I searched for changing the list view items text color and did it but still no changes in the text color. I was able to change the background color of the list item row only.

Here is a picture showing how the 6 items are being created in the list view but with white color as the background and the item that is clicked show what is the text inside the item row.

Image showing 6 items of list view

the activity_main.xml code is:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true" />

<ProgressBar
    android:id="@+id/progressBar1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" />

</RelativeLayout>
user2771059
  • 298
  • 1
  • 4
  • 12
kingk110
  • 33
  • 1
  • 6
  • Any chance you're application theme is a 'dark' one (or defaults to a dark one)? Just asking because you're supplying the application context to the adapter. You have to be aware of its side effects if the activity in which the adapter is displayed has a different theme from the global application theme. – MH. Sep 26 '13 at 19:27

1 Answers1

0

You need to use a custom adapter for you list view. That's how you style your list view as you want. you can also add more textview for other info like name. and assign different color for each element.

for a fast solution check the following question and answer about a custom adapter: Custom Adapter for List View

Good Luck.

Community
  • 1
  • 1
hasan
  • 23,815
  • 10
  • 63
  • 101
  • Got error in p.getId() and p.getCategory().getId() and p.getDescription() Is there any simple adapter that is clarified because I spent 2 weeks to understand how an adapter works and till now I didn't understand anything :( – kingk110 Sep 26 '13 at 20:30
  • sure you will have error his adapter consists of objects of Item class. your adapter consists of strings. modify the custom adapter to take strings. – hasan Sep 26 '13 at 20:33
  • You can search for other examples and tutorials of custom adapter. easy to find on the internet. this example is not complete. – hasan Sep 26 '13 at 20:35