如何在单行android中显示来自db的多个列值

时间:2016-09-22 06:57:15

标签: java android xml sqlite listview

这是我的代码:

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   //populateListView();
    mydb = new DBHelper(this);
    ArrayList<String> array_list = mydb.getAllCotacts();
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, array_list);

    ListView obj = (ListView) findViewById(R.id.listView);
    obj.setAdapter(arrayAdapter);
    obj.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // TODO Auto-generated method stub
            int id_To_Search = arg2 + 1;

            Bundle dataBundle = new Bundle();
            dataBundle.putInt("id", id_To_Search);

            Intent intent = new Intent(getApplicationContext(), DisplayContact.class);

            intent.putExtras(dataBundle);
            startActivity(intent);
        }
    });


    b1=(Button)findViewById(R.id.button);
    b1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(getApplicationContext(),DisplayContact.class);
            startActivity(i);
        }
    });

}

这是我的getallcontact代码.....

          public ArrayList<String> getAllCotacts()
{
    ArrayList<String> array_list = new ArrayList<>();

    //hp = new HashMap();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from contacts", null );
    res.moveToFirst();

    while(!res.isAfterLast()){
        array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
        array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_EMAIL)));
        res.moveToNext();
    } 
    return array_list;
}

输出是...... output

如何在一行中同时显示名称电子邮件

1 个答案:

答案 0 :(得分:3)

您要在列表中添加 name email 作为单独的 listitems combine 将它们作为单个条目。

在你的while循环中执行此操作

 array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)) +"  "+res.getString(res.getColumnIndex(CONTACTS_COLUMN_EMAIL)));

而不是

 array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
 array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_EMAIL)));

另外,为了更好的格式化,您可以使用新的换行符序列“\ n”

 array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)) +"\n"+res.getString(res.getColumnIndex(CONTACTS_COLUMN_EMAIL)));