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

标签 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);
    }

//数组列表

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 次相同。有什么问题请帮忙吗?

最佳答案

在从数据库读取数据的 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. 

关于android - 如何使用 Loop 将数据插入 Sqlite 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18983147/

相关文章:

android - 如何将listview的所有价格相加并显示在底部的textview中?

java - 使用 jasper 报告或 iText for Java 打印页面大小(20.5 x 14 厘米)的自定义发票

java - 为什么循环不将 long 作为其条件中的有效类型?

java - E/SQLite数据库 : Error inserting with SQLiteConstraintException

android - 无法识别 OBB 文件

android - 使用 mupdf 将 Pdf 页面转换为图像

java - ORMlite 注释中 native SQL 函数的使用

java - 安装 JAX-RPC Web 服务插件后无法启动 Netbeans 8.0.1

java - 我可以安全地将一个完全随机的字符串(任何 16 位值)存储到 SQLiteDB 中吗?

android - Sqlite 按日期列排序