gpt4 book ai didi

java - 插入后无法从 SQLite 中找到列

转载 作者:行者123 更新时间:2023-12-02 02:50:23 25 4
gpt4 key购买 nike

在类DataBaseSqlite内,我在方法onCreate内使用DATABASE_CREATE_CLIENT来创建数据库。

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 内的方法 createClient,在该类中调用 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(未找到)。

无论如何,这里有一些适合我的代码,它们很大程度上基于您的代码(减去 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);
}
}

调用 Activity 如下:-

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)

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

关于java - 插入后无法从 SQLite 中找到列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43946004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com