ms4dev
ms4dev

Reputation: 3

I need help for getting SQLite data

I use this method for retrieving my data

 public String getdata() {
 String[] columns= new String[]{RowId,RowBusinessName};
 Cursor c=OurDatabase.query(TableName,columns,null,null,null,null,null);
 String Result="";
 int iRowId=c.getColumnIndex(RowId);
 int iRowBusinessName=c.getColumnIndex(RowBusinessName);
 for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
 Result=Result+c.getString(iRowBusinessName)+"\n";
 }
 return Result;

}

How can I make it return structured data (id & business_name)?
I want to display every business_name in a single textview.

Please help

Upvotes: 0

Views: 32

Answers (1)

Pavitra Kansara
Pavitra Kansara

Reputation: 828

If I understand what you are trying to do, here is the solution if you want to get only 1 RowBusinessName returned as a String. (Hoping that your RowBusinessName is type String).

public String getdata(int rowId) {

     String[] columns= new String[]{RowId,RowBusinessName};
     Cursor cursor = db.query(TABLENAME, columns, RowId + "=?", new String[]{rowId + ""}, null, null, null, null);         

     String Result="";

     if (cursor != null && cursor.moveToFirst()) {
         // not required though
         int rowId = cursor.getInt(cursor.getColumnIndexOrThrow(RowId));

         String rowBusinessName = cursor.getString(cursor.getColumnIndexOrThrow(RowBusinessName));

         result = rowBusinessName;
     }
     return result;
}

Now if you want a list of RowBusinessName, then you have to build a List<String> rather than appending it to Result. That's not really a good way!

public List<String> getAll() {
        List<String> businessNameList = new ArrayList<String>();
        String[] columns= new String[]{RowId,RowBusinessName};

        Cursor c=OurDatabase.query(TableName,columns,null,null,null,null,null);

        if (c != null && c.moveToFirst()) {
            // loop until the end of Cursor and add each entry to Ticks ArrayList.
            do {
                String businessName = cursor.getString(cursor.getColumnIndexOrThrow(RowBusinessName));
                if (businessName != null) {
                    businessNameList.add(businessName);
                }
            } while (c.moveToNext());
        }
        return businessNameList;
    }

These are work around. The appropriate answer would be to create an Object that holds id and businessName. That way, you build an object from DB and just return the entire Object.

Upvotes: 1

Related Questions