如何使用Loop将数据插入Sqlite数据库?

时间:2013-09-24 13:34:50

标签: android netbeans android-sqlite

这是我的短代码,我在表中插入了10行,但是在完成循环之后 为什么我有十次像“0 Net 0”这样的可视化? //表格结构

 String creater = "CREATE TABLE IF NOT EXISTS est (ID INTEGER PRIMARY KEY AUTOINCREMENT,codigo VARCHAR(10),"
    + "produto VARCHAR(1000), "
    + "qtd VARCHAR(10) ) ";
    sql.execSQL(creater);

//插入循环

   for(int i=0;i<10;i++)
    {
    ContentValues values=new ContentValues(); 
    values.put("codigo", String.valueOf(i));
    values.put("produto", "Net");
    values.put("qtd", String.valueOf(i));
    sql.insert("est", null, values);
    }

// ArrayList的

public  ArrayList<String>  estoque(SQLiteDatabase sql)
     {
    ArrayList<String> lst = new ArrayList<String>();
    try{
    String cmd ="select * from est";
    Cursor c = sql.rawQuery(cmd,null);
    c.moveToFirst();
    int i=0;
    while(c.getCount() > i )
    {
    lst.add(c.getString(1)+"|"+c.getString(2)+"|"+c.getString(3));
    i++;
    }
    }catch(Exception ex){Log.e("ERROR", ex.getStackTrace().toString());}
    return lst;
    };

//的ListView

 ListView  listview =(ListView)findViewById(R.id.listview);
ArrayList<String> estoque = new db().estoque(sql);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, estoque);
adapter1.setDropDownViewResource(android.R.layout.simple_list_item_1);
listview.setAdapter(adapter1);

//可视化 "0 Net 0" 10次相同。请问有什么不对吗?

1 个答案:

答案 0 :(得分:1)

在您从数据库中读取的while循环中(在增加i变量之前或之后),您应该调用c.moveToNext();。否则你会一遍又一遍地读同一行。

The documentation states:

public abstract boolean moveToNext ()
Move the cursor to the next row.
This method will return false if the cursor is already past the last entry in the result set.

Returns
    whether the move succeeded.