插入后找不到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 打开联系人并检索有关用户选择的联系人的数据。然后我调用方法创建客户端,它位于类 CliendDataSource 中,其中调用 cursorToClient,我无法检索 contactId 值。

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)

并不是说我确定问题,但根据您的代码,以下内容有效。我确实有一个问题(根据 Ferdous 帖子中的评论("rowid"有空间。但是,这是使用传递给getColumnIndex()的变量,即使用它返回的空格 -1(未找到(。

无论如何,这里有一些对我有用的代码,它在很大程度上基于您的代码(而不是客户端类的东西(:-

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)

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

我认为问题出在您的陈述DATABASE_CREATE_CLIENT.可能是由于在结束")"之前缺少space而未添加列CLIENT_CONTACT_ID

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 ";

最后,再次uninstallinstall您的应用程序。

希望这会有所帮助~

最新更新