插入后无法从SQLite中找到列

时间:2017-05-12 20:29:35

标签: java android sqlite

内部课程DataBaseSqlite我在方法DATABASE_CREATE_CLIENT中使用onCreate来创建数据库。

package DataBaseSqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by jur_1 on 02-Apr-17.
 */

public class MySQLiteHelper extends SQLiteOpenHelper
{
    //CLIENT VARIABLES
    public static final String TABLE_CLIENT = "clients";
    public static final String CLIENT_ID = "rowid ";
    public static final String CLIENT_NAME = "name";
    public static final String CLIENT_CONTACT_ID = "contactId";

    private static final String DATABASE_NAME = "JurBankTransactions.db";
    private static final int DATABASE_VERSION = 5;


    //CLIENT TABLE
    private static final String DATABASE_CREATE_CLIENT = "create table " + TABLE_CLIENT + "( " + CLIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
            + CLIENT_NAME + " text not null, " + CLIENT_CONTACT_ID + " text not null)";
    private static final String DATABASE_CREATE_TRANSACTIONS = "create table transactions( _id integer key auto increment, clientID integer, typeID integer, debt integer, quantity integer, date text)";
    private static final String DATABASE_CREATE_TYPE = "create table types( _id integer key auto increment, name text not null)";


    public MySQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL(DATABASE_CREATE_CLIENT);
        db.execSQL(DATABASE_CREATE_TRANSACTIONS);
        db.execSQL(DATABASE_CREATE_TYPE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.w(MySQLiteHelper.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS clients");
        db.execSQL("DROP TABLE IF EXISTS transactions");
        db.execSQL("DROP TABLE IF EXISTS types");
        onCreate(db);
    }
}

MainActivity 内部之后,我调用intent打开联系人并检索有关用户选择的联系人的数据。然后我调用方法 createClient ,它位于类 CliendDataSource 内,其中 cursorToClient 被调用,我不能' retrive contactId value。

package CustomListView;

/**
 * Created by jur_1 on 10-May-17.
 */

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import DataBaseSqlite.Client;
import DataBaseSqlite.MySQLiteHelper;

public class ClientDataSource
{
    private SQLiteDatabase database;
    private MySQLiteHelper dbHelper;
    private String[] allColumns = {MySQLiteHelper.CLIENT_ID, MySQLiteHelper.CLIENT_NAME};

    public ClientDataSource(Context context)
    {
        dbHelper = new MySQLiteHelper(context);
    }

    public void open() throws SQLException
    {
        database = dbHelper.getWritableDatabase();
    }

    public void close()
    {
        dbHelper.close();
    }

    public Client createClient(String name, String contactId)
    {
        ContentValues values = new ContentValues();
        values.put(MySQLiteHelper.CLIENT_NAME, name);
        values.put(MySQLiteHelper.CLIENT_CONTACT_ID, contactId);
        Log.d("CREATE_CLIENT", "values contact id: " + contactId);
        Log.d("CREATE_CLIENT", "values length: " + values.size());
        long insertId = database.insert(MySQLiteHelper.TABLE_CLIENT, null,
                values);
        System.out.println("new id: " + insertId);
        Cursor cursor = database.query(MySQLiteHelper.TABLE_CLIENT,
                allColumns, MySQLiteHelper.CLIENT_ID + " = " + insertId, null,
                null, null, null);
        cursor.moveToFirst();
        Client newClient = cursorToClient(cursor);
        cursor.close();
        return newClient;
    }

    public void deleteClient(Client client)
    {
        long id = client.getId();
        System.out.println("Client deleted with id: " + id);
        database.delete(MySQLiteHelper.TABLE_CLIENT, MySQLiteHelper.CLIENT_ID
                + " = " + id, null);
    }

    public List<Client> getAllClients()
    {
        List<Client> clients = new ArrayList<Client>();

        Cursor cursor = database.query(MySQLiteHelper.TABLE_CLIENT,
                allColumns, null, null, null, null, null);

        cursor.moveToFirst();
        while (!cursor.isAfterLast())
        {
            Client client = cursorToClient(cursor);
                clients.add(client);
                cursor.moveToNext();
        }
        // make sure to close the cursor
        cursor.close();
        return clients;
    }

    private Client cursorToClient(Cursor cursor)
    {
        Log.d("cursorToClient", "cursor num of columsn: " + cursor.getColumnCount());
        Client client = new Client();
        client.setId(cursor.getLong(0));
        Log.d("cursorToClient", "column id: " + cursor.getLong(0));
        client.setName(cursor.getString(1));
        Log.d("cursorToClient", "cursor name: " + cursor.getString(1));
        String[] columnNames = cursor.getColumnNames();
        for(String columnName : columnNames)
        {
            System.out.println("Column: " + columnName);
        }
        Log.d("cursorToClient", "column name 2: " + cursor.getColumnName(2));
        client.setContactsId(cursor.getString(2));
        return client;
    }
}

日志输出为:

19:32.067 8647-8647/com.jurbank.jurbank.jurbank D/cursorToClient: cursor num of columsn: 2
05-12 22:19:32.068 8647-8647/com.jurbank.jurbank.jurbank D/cursorToClient: column id: 1
05-12 22:19:32.068 8647-8647/com.jurbank.jurbank.jurbank D/cursorToClient: cursor name: Alen Ban
05-12 22:19:32.068 8647-8647/com.jurbank.jurbank.jurbank I/System.out: Column: rowid
05-12 22:19:32.068 8647-8647/com.jurbank.jurbank.jurbank I/System.out: Column: name

错误:

05-12 22:19:32.069 8647-8647/com.jurbank.jurbank.jurbank E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.jurbank.jurbank.jurbank, PID: 8647
                                                                           java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.contacts/contacts/lookup/549i30872f420c7a3b2e.1115i91.1419r1625-293F31432B2943/95 flg=0x1 }} to activity {com.jurbank.jurbank.jurbank/com.jurbank.jurbank.jurbank.MainActivityClients}: java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
                                                                               at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)

2 个答案:

答案 0 :(得分:1)

我认为问题出在您的陈述DATABASE_CREATE_CLIENT中。由于在结束CLIENT_CONTACT_ID之前缺少space,可能无法添加列")"

更新您的创建表statement,如下所示:

//CLIENT TABLE
private static final String DATABASE_CREATE_CLIENT = "CREATE TABLE " + TABLE_CLIENT + "( " + CLIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
        + CLIENT_NAME + " TEXT NOT NULL, " + CLIENT_CONTACT_ID + " TEXT NOT NULL )";

同时从列名CLIENT_ID中删除空格。

使用:

public static final String CLIENT_ID = "rowid";

代替:

public static final String CLIENT_ID = "rowid ";

最后uninstall&amp; install再次申请。

希望这会有所帮助〜

答案 1 :(得分:1)

并非我确定问题,但基于您的代码,以下内容有效。我确实有一个问题(根据Ferdous的帖子中的评论)和#34; rowid&#34;有空间。但是,这是使用传递给getColumnIndex()的变量,即返回的空间为-1(未找到)。

无论如何,这里有一些适用于我的代码,它非常基于你的代码(减去Client类的东西): -

DBHelper(addClientgetAllClients用于作证): -

public class DBHelperClients extends SQLiteOpenHelper {

    //CLIENT VARIABLES
    public static final String TABLE_CLIENT = "clients";
    public static final String CLIENT_ID = "rowid";
    public static final String CLIENT_NAME = "name";
    public static final String CLIENT_CONTACT_ID = "contactId";

    private static final String DATABASE_NAME = "JurBankTransactions.db";
    private static final int DATABASE_VERSION = 5;


    //CLIENT TABLE
    private static final String DATABASE_CREATE_CLIENT = "create table " + TABLE_CLIENT +
            "( " + CLIENT_ID + " INTEGER PRIMARY KEY, "
            + CLIENT_NAME + " text not null, "
            + CLIENT_CONTACT_ID + " text not null)";

    public DBHelperClients(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE_CLIENT);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {

    }

    public long addClient(String name, String contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(CLIENT_NAME,name);
        cv.put(CLIENT_CONTACT_ID,contact);
        return db.insert(TABLE_CLIENT,null,cv);
    }

    public Cursor getAllClients() {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.query(TABLE_CLIENT,null,null,null,null,null,null);
    }
}

调用活动如下: -

public class MainActivity extends AppCompatActivity {
    //DBHelper db;
    DBHelperClients db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        db = new DBHelperClients(this);
        db.addClient("Fred","email");
        db.addClient("Bert","snailmail");
        db.addClient("Harry","smoke signals");

        Cursor myclients = db.getAllClients();
        while (myclients.moveToNext()) {
            Log.d("MYCLIENT","Client name=" +
                    myclients.getString(myclients.getColumnIndex(DBHelperClients.CLIENT_NAME)) +
                    "\tClient Contact=" +
                    myclients.getString(myclients.getColumnIndex(DBHelperClients.CLIENT_CONTACT_ID)) +
                    "\tID=" + Long.toString(myclients.getLong(myclients.getColumnIndex(DBHelperClients.CLIENT_ID)))
            );
        }
    }
}

日志(第二次运行后,重复数据): -

05-13 18:49:16.058 7260-7260/mjt.testvcsuse D/MYCLIENT: Client name=Fred    Client Contact=email    ID=1
05-13 18:49:16.058 7260-7260/mjt.testvcsuse D/MYCLIENT: Client name=Bert    Client Contact=snailmail    ID=2
05-13 18:49:16.058 7260-7260/mjt.testvcsuse D/MYCLIENT: Client name=Harry   Client Contact=smoke signals    ID=3
05-13 18:49:16.058 7260-7260/mjt.testvcsuse D/MYCLIENT: Client name=Fred    Client Contact=email    ID=4
05-13 18:49:16.058 7260-7260/mjt.testvcsuse D/MYCLIENT: Client name=Bert    Client Contact=snailmail    ID=5
05-13 18:49:16.058 7260-7260/mjt.testvcsuse D/MYCLIENT: Client name=Harry   Client Contact=smoke signals    ID=6

无法解决任何问题的细微差别是

我使用while(cursor.moveToNext()) {}循环游标,而不是在从光标获取数据时使用列的特定偏移量。我使用了cursor.getColumnIndex(name of the column)更灵活。

也许尝试使用上述内容,看看它是否有效,然后根据您的需要进行调整。