Sebastian Sebastian - 2 months ago 6
Java Question

How to show multiple columns values from db in a single row android

This is my code :

@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);
}
});

}


This is my getallcontact code.....

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;
}


And the output is..
output

How can i show both name and email in a single row?

Answer

You are adding both name and email as separate listitems in your list so combine them as a single entry.

do this in your while loop

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

instead of this

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

Plus for little better formatting you can use new line escape sequence "\n"

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