在类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,该意图将打开Contacts并检索有关用户选择的联系人的数据。然后,我调用位于类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(使用addClient
和getAllClients
进行验证):-
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)
,它更灵活。也许尝试使用上面的方法,看看它是否有效,然后根据需要进行调整。