List Data Format - android

I'm fetching Data form Table as list and adding that to sub list but i'm getting output that i didn't expect. I don't know how to Fix that so that i can get the output what i need
I have attached the code please help me to solve this issue??
public List<List<String>> fetchData(){
List<List<String>> main= new ArrayList<List<String>>();
List<String> sub= new ArrayList<String>();
String qry="SELECT * FROM "+myTable+"";
SQLiteDatabase db= this.getReadableDatabase();
Cursor cursor=db.rawQuery(qry, null);
if (cursor.moveToFirst()) {
do {
System.out.println("-TblPOmaster-");
sub.add(cursor.getString(0));
sub.add(cursor.getString(1));
sub.add(cursor.getString(2));
main.add(sub);
System.out.println("Data:"+main);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return main;
}
Output what i'm Getting Now
Data:[[a1,a2,a3]]
Data:[[a1,a2,a3,b1,b2,b3],[a1,a2,a3,b1,b2,b3]]
Data:[[a1,a2,a3,b1,b2,b3,c1,c2,c3],[a1,a2,a3,b1,b2,b3,c1,c2,c3],[a1,a2,a3,b1,b2,b3,c1,c2,c3]]
Output what i need
Data:[[a1,a2,a3]]
Data:[[a1,a2,a3],[b1,b2,b3]]
Data:[[a1,a2,a3],[b1,b2,b3],[c1,c2,c3]]

if (cursor.moveToFirst()) {
do {
List<String> sub= new ArrayList<String>();
System.out.println("-TblPOmaster-");
sub.add(cursor.getString(0));
sub.add(cursor.getString(1));
sub.add(cursor.getString(2));
main.add(sub);
System.out.println("Data:"+main);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return main;
}
try to declare sub list inside the cursor and it will work fine

Related

return ArrayList<String> with specific record from SQLiteDataBase

I want to get values but the function always returns null. Even though I debug and there is value inside variable rv.
This is my method:
public ArrayList<String> getList(int id) {
try {
ArrayList<String> rv = new ArrayList<String>();
open();
Cursor c = db.rawQuery("select * from reviews where IDRE="+id, null);
if(c.moveToFirst() || c.getColumnCount()==1) {
rv.add(String.valueOf(c.getInt(c.getColumnIndex("IDRE"))));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("ID_FK"))));
rv.add(c.getString(c.getColumnIndex("DATE")));
rv.add(c.getString(c.getColumnIndex("TYPE")));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("COST"))));
rv.add(c.getString(c.getColumnIndex("SERVICE")));
rv.add(c.getString(c.getColumnIndex("ATMOSPHERE")));
rv.add(c.getString(c.getColumnIndex("OVERALL")));
rv.add(c.getString(c.getColumnIndex("COMMENT")));
}
c.close();
close();
return rv;
}catch(Exception e) {
return null;
}
}
Some logging would help determine if you're throwing an error and ending up in that catch block, as #Daniel Nugent is saying.
But I think the issue is with your if expression. c.moveToFirst is going to move your cursor to the first row of your data source, and then return true unless that data source is empty, so the only time that if block does not occur is when your data source is empty. The only way c.getColumnCount()==1 is having any effect on the evaluation of your expression is if you have a table with only one column and no rows. Let us know what you're trying to achieve with that, and add some logging, and we'll be better able to help you.
I have edited your code ...and given two example , you can refer any one...
public ArrayList<String> getList(int id) {
try {
ArrayList<String> rv = new ArrayList<String>();
open();
Cursor c = db.rawQuery("select * from reviews where IDRE="+id, null);
if(c==null)
return null;
c.moveToFirst();
rv.add(String.valueOf(c.getInt(c.getColumnIndex("IDRE"))));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("ID_FK"))));
rv.add(c.getString(c.getColumnIndex("DATE")));
rv.add(c.getString(c.getColumnIndex("TYPE")));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("COST"))));
rv.add(c.getString(c.getColumnIndex("SERVICE")));
rv.add(c.getString(c.getColumnIndex("ATMOSPHERE")));
rv.add(c.getString(c.getColumnIndex("OVERALL")));
rv.add(c.getString(c.getColumnIndex("COMMENT")));
c.close();
close();
return rv;
}catch(Exception e) {
return null;
}
}
Second way:
public ArrayList<String> getList(int id) {
try {
ArrayList<String> rv = new ArrayList<String>();
open();
String[] columns=new String[]{"IDRE","ID_FK","DATE","TYPE","COST","SERVICE","ATMOSPHERE","OVERALL","COMMENT"};
Cursor c=sql_db.query("reviews", columns, "IDRE"+"=?", new String[] {String.valueOf(id)}, null, null, null);
if(c==null)
return null;
c.moveToFirst();
rv.add(String.valueOf(c.getInt(c.getColumnIndex("IDRE"))));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("ID_FK"))));
rv.add(c.getString(c.getColumnIndex("DATE")));
rv.add(c.getString(c.getColumnIndex("TYPE")));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("COST"))));
rv.add(c.getString(c.getColumnIndex("SERVICE")));
rv.add(c.getString(c.getColumnIndex("ATMOSPHERE")));
rv.add(c.getString(c.getColumnIndex("OVERALL")));
rv.add(c.getString(c.getColumnIndex("COMMENT")));
c.close();
close();
return rv;
}catch(Exception e) {
return null;
}
}

Bind Arrayadapter to textview android

i want to display data from sqlite to textview,here is my code.What i have dont wrong.It is not displaying the data no error but crashes
main class
private void loadTextViewData()
{
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<String> lables = db.getAllLabels();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.test_list_item, lables);
text.setText(??);
}
sql class
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
instead of ArrayAdapter use for example SimpleCursorAdapter (or any subclass of CursorAdapter)

SQLite to ListView(androidhive's version)

I am trying to insert data from SQLite to a listview. I have tried look for example codes but they do not work. The database part is from AndroidHive's SQL tutorial. In his post the code to get all data in DB is(i edited the data fields) :
// Getting All carts item
public List<Cart> getAllCart() {
List<Cart> cartList = new ArrayList<Cart>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Cart cart = new Cart();
cart.setID(Integer.parseInt(cursor.getString(0)));
cart.setPID(Integer.parseInt(cursor.getString(1)));
cart.setName(cursor.getString(2));
cart.setPrice(Double.parseDouble(cursor.getString(3)));
cart.setQut(Integer.parseInt(cursor.getString(4)));
// Adding cart to list
cartList.add(cart);
} while (cursor.moveToNext());
}
// return cart list
return cartList;
}
how do put this "getAllCart()" to my listview. Thanks alot!!
to get data from SQLite you can try like this:
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","name","number","skypeId","address" },
null, null, null, null, "name asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
and to show it in a list view :
List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
names2 = dm.selectAll();
stg1=new String[names2.size()];
int x=0;
String stg;
for (String[] name : names2) {
stg = name[1]+" - "+name[2]+ " - "+name[3]+" - "+name[4];
stg1[x]=stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_list_item_1,
stg1);
this.setListAdapter(adapter);
}
refer this tutorial you will get an idea: http://www.vogella.com/articles/AndroidSQLite/article.html
you will need to create an Database class instance in your Activity or ListActivity to access getAllCart as
public class TempActivity extends Activity {
DatabaseHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = new DatabaseHandler(TempActivity.this);
// Reading all Carts
List<Cart> Carts = db.getAllCart(); //<< get all Cart details here
//... your code here..
and for showing Carts ArrayList values in ListView you will need to create an Custom Adapter for Adding all items in ListView rows .
for Create ListView with Custom Adapter you can view these tutorials :
Customizing Android ListView Items with Custom ArrayAdapter
Android ListView example

Querying Multiple Fields in a Database

For example, I have this table:
I am using the following method to query from that table:
public ArrayList<ArrayList<String>> getAllViandCategory() {
ArrayList<ArrayList<String>> data2 = new ArrayList<ArrayList<String>>();
ArrayList<String> data = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + "tbl_viand_category";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
data.add(cursor.getString(0));
data.add(cursor.getString(1));
data2.add(data);
} while (cursor.moveToNext());
}
return data2;
}
I am not getting the desired output. I am getting this: [1,Fish,2,Vegetables,3,Meat,4,Rice,5,Etc] instead of [[1,Fish],[2,Vegetables],[3,Meat],[4,Rice],[5,Etc]]
What you have is a List of Lists. The outer list has objects which has lists.
// Code to add a list object into outer list.
data2.add(data);
You will notice that you have created the data object just once. So basically the same object is inserted into data2 again and again.
You need to create a new data object for each iteration.
// New Code
if (cursor.moveToFirst()) {
do {
data = new ArrayList<String>();
data.add(cursor.getString(0));
data.add(cursor.getString(1));
data2.add(data);
} while (cursor.moveToNext());
}
Hope that helps :D

How to store object return by a cursor into a arraylist?

I am taking object from sqlite database with the help of cursor. And I would like to store them into an arraylist. THe problem is that I dont know the size of my returned data in advance. So How do I put them into an arraylist?
code:
public Student findAll()
{
db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery("select sid, name, age from t_student", null
);
if(cursor.moveToNext())
return new Student(cursor.getInt(cursor.getColumnIndex("sid")), cursor.getString(cursor.getColumnIndex("name")), cursor.getInt(cursor.getColumnIndex("age")));
return null;
}
Main:
ArrayList<Student> studentArrayList = new ArrayList<Student>();
studentArrayList.add(dao.findAll()); //doing this will only return the first object from the database
According to the ArrayList docs
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
This will help you to understand ArrayList in a better way.
public List<Student> findAll() {
List<Student> studentArrayList = new ArrayList<Student>();
db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery("select sid, name, age from t_student", null
);
while(cursor.moveToNext()) {
studentArrayList.add(new Student(cursor.getInt(cursor.getColumnIndex("sid")), cursor.getString(cursor.getColumnIndex("name")), cursor.getInt(cursor.getColumnIndex("age"))));
}
return studentArrayList ;
}
ArrayList<Student> studentArrayList = new ArrayList<Student>();
studentArrayList=findAll();
Try this:
public List<Student> findAll() {
List<Student> studentArrayList = new ArrayList<Student>();
db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery("select sid, name, age from t_student", null
);
while(cursor.moveToNext()) {
studentArrayList.add(new Student(cursor.getInt(cursor.getColumnIndex("sid")), cursor.getString(cursor.getColumnIndex("name")), cursor.getInt(cursor.getColumnIndex("age"))));
}
return studentArrayList ;
}
Your problem is that instead of:
if(c.moveToNext()) {
// ...
}
you have to iterate with a while loop:
while(c.moveToNext()) {
// ...
}
Thus:
List<Student> myList = new ArrayList<String>();
Cursor c = ...
while(c.moveToNext()) {
myList.add(new Student(cursor.getInt(cursor.getColumnIndex("sid")), cursor.getString(cursor.getColumnIndex("name")), cursor.getInt(cursor.getColumnIndex("age")));
}
c.close();

Categories

Resources