这是我尝试将元素从 cursor 添加到 ArrayList 的类。
public ArrayList<String> getArrayList()
{
int i;
sdb=this.getReadableDatabase();
c=null;
ArrayList<String> list=null;
try{
c=sdb.rawQuery("select * from Products", null);
c.moveToFirst();
if(c!=null)
{
list=new ArrayList<String>();
do
{
for(i=1;i<=c.getColumnCount();i++)
{
list.add(c.getString(c.getColumnIndex("ProductName")));
list.add(c.getString(c.getColumnIndex("ProduceType")));
list.add(c.getString(c.getColumnIndex("Company")));
list.add(c.getString(c.getColumnIndex("Price")));
list.add(c.getString(c.getColumnIndex("Quantity")));
}
}while(c.moveToNext());
}
else
System.out.println("c null");
}catch(Exception e)
{
e.printStackTrace();
//c=null;
}
/*finally{
if(c!=null && !c.isClosed())
{
c.close();
c=null;
}
close();
}*/
return list;
}
这是我尝试从 ArrayList 检索数据并将它们添加到 expandablelistview 的地方。我想要组 View 中游标中每一行的第一列和 subview 中相应行的其余列查看。
private void loadData(){
db=new DatabaseHelper(this);
//db.open();
System.out.println("returned from db.open() in loadData");
ArrayList<String> al=db.getArrayList();
db.close();
int count=al.size();
int i,j;
try{
for(i=1;i<=count;i=i+5)
{
String pn=al.get(i);
for(j=i;j<=i+5;j++)
{
String inf=al.get(j);
addProduct(pn,inf);
}
}
}catch(StackOverflowError e)
{
e.printStackTrace();
}
}
据我所知,我的 for 循环出错了。Logcat 显示以下错误
07-04 02:44:14.747: E/CursorWindow(1881): Failed to read row 0, column -1 from a CursorWindow which has 3 rows, 5 columns.
请告诉我arraylist数据检索的正确用法。提前致谢。
最佳答案
我建议采用这种方法,因为您使用的方法是一种不好的做法。
不使用字符串列表,而是使用名为 ProductInfo
的自定义类的对象(包括所有这些字符串),并从该列表中添加和检索数据。
public class ProductInfo{
String productName, productType, company, price, quantity;
//getter setter
}
// add data
List<ProductInfo> productList = new ArrayList<ProductInfo>();
Cursor c = null;
do {
for (int i = 1; i <= c.getColumnCount(); i++) {
ProductInfo pInfo = new ProductInfo();
pInfo.setProductName(c.getString(c
.getColumnIndex("ProductName")));
pInfo.setProductType(c.getString(c
.getColumnIndex("ProduceType")));
pInfo.setCompany(c.getString(c.getColumnIndex("Company")));
pInfo.setPrice(c.getString(c.getColumnIndex("Price")));
pInfo.setQuantity(c.getString(c.getColumnIndex("Quantity")));
productList.add(pInfo);
}
} while (c.moveToNext());
// retrieve data
for (int i = 0; i < productList.size(); i++) {
System.out.println("Info of Product "+(i+1));
ProductInfo pInfo = productList.get(i);
System.out.println("Prod name: "+ pInfo.getProductName());
System.out.println("Prod Type: "+pInfo.getProductType());
System.out.println("Company: "+pInfo.getCompany());
System.out.println("Price: "+pInfo.getPrice());
System.out.println("Quantity: "+pInfo.getQuantity());
}
关于android - 如何使用 2 个 for 循环从 ArrayList 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24568247/