传递数据数组到Android的SQLite数据库 [英] Passing an array of data into a SQLite Database in android

查看:131
本文介绍了传递数据数组到Android的SQLite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是阵列将数据发送到我的SQLite数据库。结果
该数组包含所有选定的数值。

I am using an array to send data to my SQLite Database.
The array contains all the selected values.

 private void addContacts(String[] selectedItems) {

    manager.Insert_phone_contact(selectedItems);
    Intent i = new Intent(this, MainActivity.class);    
    startActivity(i);
}

我的SQLite DATABSE code插入在contentvalues​​上述selectedItems排列如下:

My SQLite databse code to insert the above mentioned "selectedItems" array in contentvalues is as follows:

public void Insert_phone_contact(String [] contact){
    try{

        SQLiteDatabase DB = this.getWritableDatabase();
        for(int i=0;i<contact.length;i++){
            ContentValues cv = new ContentValues();
            cv.put(CONTACT_NAME, contact[i]);
            DB.insert(TABLE_CONTACTS, null, cv);
            DB.close();
        }
        }
    catch(Exception ex){
        Log.e("Error in phone contact insertion", ex.toString());
    }

只有第一个数组元素存储在 ContentValues​​ 的简历,不是所有的数组元素。结果
什么是错在这code?结果
我怎样才能插入所有数组项中的TABLE_CONTACTS表?结果
任何帮助将AP preciated。

Only the first array item is stored in ContentValues cv, not all the array elements.
What's wrong in this code?
How can I insert all the array items in the "TABLE_CONTACTS" table?
Any help will be appreciated.

推荐答案

您必须修复code的几行字,第一是删除Db.Close()和循环结束后添加
你试图将code的第一次插入后关闭数据库对象和循环迭代的其余部分不可用。

You have to fix few lines of code, First is to delete Db.Close() and add it after loop The code you were trying was closing the Db object after first insertion and unavailable for the rest of loop iterations.

public void Insert_phone_contact(String [] contact){
try{

    SQLiteDatabase DB = this.getWritableDatabase();
    ContentValues cv = new ContentValues(); //Declare once
    for(int i=0;i<contact.length;i++){            
        cv.put(CONTACT_NAME, contact[i]);
        DB.insert(TABLE_CONTACTS, null, cv); //Insert each time for loop count            
    }
    DB.close(); // Now close the DB Object
    }
catch(Exception ex){
    Log.e("Error in phone contact insertion", ex.toString());
}

这篇关于传递数据数组到Android的SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆