Ich mache einfache listview.Ich möchte Kontakte Namen zu laden und wenn ich listview "s Element, möchte ich SetBackgroundcolor blau.Aber ich habe 3 Probleme.Vor allem meine Cursor don t laden listview korrekt.Es ist wiederhole dich selbst. Zweites Problem ist; Wenn ich ein Element in der Listenansicht anklicke, malt Meine Listenansicht mehr als 1 Elemente.Das dritte ist: Wenn ich auf die letzten Elemente klicke, bekomme mein Programm eine Exception.Wie kann ich Namen immer korrekt in listview laden? Wie kann ich das beheben?Cursor wird nicht korrekt in Listenansicht geladen?
public class display extends AppCompatActivity {
ListView lv ;
Button select;
String phoneNumber;
ArrayList <String> aa= new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView)findViewById(R.id.lv);
select = (Button) findViewById(R.id.button1);
getNumber(this.getContentResolver());}
public void getNumber(ContentResolver contentResolver) {
Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber);
aa.add(name);
}
phones.close();// close cursor
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_selectable_list_item,aa);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
parent.getChildAt(position).setBackgroundColor(Color.BLUE);
}
});
}
}
Meine Layout-Datei:
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/button1" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Select" />
</RelativeLayout>