Reputation: 23
I have a tables and records like :
EmployeeName
------------
Ram
Laxman
Bharat
Shatrugn
where i want to output to concat all values in one row in a single query:
I want result like:
Ram,Laxman,bharat,shatrugn
Concat string with ,(comma) in singlee line.. but i don't know that how to concat in android using cursor...
Upvotes: 1
Views: 766
Reputation: 4140
String values;
if (cursor.moveToFirst()) {
do {
values=values + cursor.getString(0)+",";
} while (cursor.moveToNext());
remove last comma
if (values.length() > 0)
{
values= values.substring(0,values.length() - 1);
}
Upvotes: 2
Reputation: 620
Here is my code i used...hope it helps you.
private SQLiteDatabase myDataBase;
Cursor cursor;
String S="";
String myPath2 = yourDBpath + yourDBNAME;
try{
myDataBase = SQLiteDatabase.openDatabase(myPath2, null,SQLiteDatabase.OPEN_READWRITE);
String sql="your query";
cursor=myDataBase.rawQuery(sql, null);
if(cursor != null)
{
while(cursor.moveToNext())
{
S=S.append(cursor.getString(0));
}
}
}
}catch(Exception e){
}finally{
myDataBase.close();
}
Final result will be there in String S.
Upvotes: 2
Reputation: 247860
In SQLite, you can use GROUP_CONCAT()
:
select Group_Concat(EmployeeName)
from table1
If you had multiple fields that you want to return, then you would use a GROUP BY
with the query, similar to this:
select id, Group_Concat(EmployeeName)
from table1
group by id
Upvotes: 4