我的应用程序应该将数据保存在数据库中,然后将其显示在listView中。 问题是listView没有显示任何内容。 查看错误日志,似乎说它在保存数据方面存在问题。
提前致谢
将对DBAdapter
package se.welovecode.wdmmg;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_TRANSACTIONS = "transactions";
public static final String KEY_ITEM = "item";
public static final String KEY_SUM = "sum";
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_TRANSACTIONS, KEY_ITEM, KEY_SUM,};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_TRANSACTIONS = 1;
public static final int COL_ITEM = 2;
public static final int COL_SUM = 3;
// DataBase info:
public static final String DATABASE_NAME = "db";
public static final String DATABASE_TABLE = "mainTransactions";
public static final int DATABASE_VERSION = 1; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_TRANSACTIONS + " TEXT NOT NULL, "
+ KEY_ITEM + " TEXT NOT NULL, "
+ KEY_SUM + " INTEGER"
+ ");";
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
Context context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to be inserted into the database.
public long insertRow(String transactions) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TRANSACTIONS, transactions);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
public long insertRow2(String item) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ITEM, item);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
public long insertRow3(int sum) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_SUM, sum);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String transaction, String item, String sum) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_TRANSACTIONS, transaction);
newValues.put(KEY_ITEM, item);
newValues.put(KEY_SUM, sum);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
MainActivity
package se.welovecode.wdmmg;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
DBAdapter myDB;
TextView Balance;
Double value;
ListView lwTransactions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Balance = (TextView) findViewById(R.id.tvBalance);
refreshSum();
openDB();
populateListView();
}
@Override
protected void onResume() {
super.onResume();
refreshSum();
populateListView();
}
protected void onDestroy(){
super.onDestroy();
closeDb();
}
private void openDB(){
myDB = new DBAdapter(this);
myDB.open();
}
private void closeDb(){
myDB.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_add:
Intent intent = new Intent(MainActivity.this, AddTransaction.class);
startActivity(intent);
default:
return super.onOptionsItemSelected(item);
}
}
private void refreshSum(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
value = (double) prefs.getFloat("KEY", 0f);
Balance.setText(value.toString());
}
private void populateListView(){
Cursor cursor = myDB.getAllRows();
String[] fromFieldNames = new String[]{DBAdapter.KEY_ROWID, DBAdapter.KEY_TRANSACTIONS, DBAdapter.KEY_ITEM, DBAdapter.KEY_SUM,};
int[] toViewIDs = new int[] {R.id.textViewRowID, R.id.textViewStore, R.id.textViewService, R.id.textViewCost};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.layout.item_layout, cursor, fromFieldNames,toViewIDs,0);
lwTransactions = (ListView) findViewById(R.id.lwTransactions);
lwTransactions.setAdapter(myCursorAdapter);
}
}
错误日志
06-12 17:33:38.383 29168-29168/se.welovecode.wdmmg E/SQLiteLog﹕ (1299) abort at 7 in [INSERT INTO mainTransactions(transactions) VALUES (?)]: NOT NULL constraint failed: mainTransactions.item
06-12 17:33:38.383 29168-29168/se.welovecode.wdmmg E/SQLiteDatabase﹕ Error inserting transactions=hsns
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: mainTransactions.item (code 1299)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:952)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1595)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1465)
at se.welovecode.wdmmg.DBAdapter.insertRow(DBAdapter.java:68)
at se.welovecode.wdmmg.AddTransaction.onClick_AddTransaction(AddTransaction.java:55)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4268)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:20983)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6141)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
06-12 17:33:38.393 29168-29168/se.welovecode.wdmmg E/SQLiteLog﹕ (1299) abort at 6 in [INSERT INTO mainTransactions(item) VALUES (?)]: NOT NULL constraint failed: mainTransactions.transactions
06-12 17:33:38.393 29168-29168/se.welovecode.wdmmg E/SQLiteDatabase﹕ Error inserting item=bsb
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: mainTransactions.transactions (code 1299)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:952)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1595)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1465)
at se.welovecode.wdmmg.DBAdapter.insertRow2(DBAdapter.java:76)
at se.welovecode.wdmmg.AddTransaction.onClick_AddTransaction(AddTransaction.java:58)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4268)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:20983)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6141)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
06-12 17:33:38.393 29168-29168/se.welovecode.wdmmg E/SQLiteLog﹕ (1299) abort at 6 in [INSERT INTO mainTransactions(sum) VALUES (?)]: NOT NULL constraint failed: mainTransactions.transactions
06-12 17:33:38.393 29168-29168/se.welovecode.wdmmg E/SQLiteDatabase﹕ Error inserting sum=120
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: mainTransactions.transactions (code 1299)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:952)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1595)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1465)
at se.welovecode.wdmmg.DBAdapter.insertRow3(DBAdapter.java:83)
at se.welovecode.wdmmg.AddTransaction.onClick_AddTransaction(AddTransaction.java:61)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4268)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:20983)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6141)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
答案 0 :(得分:0)
你得到KEY_TRANSACTIONS TEXT NOT NULL而KEY_ITEM TEXT NOT NULL
但是你只在insertRow中传入KEY_TRANSACTION,但是你还需要把KEY_ITEM传递给
public long insertRow(String transactions) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TRANSACTIONS, transactions);
initialValues.put(KEY_ITEM, "some key item");
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
或从KEY_ITEM列约束中删除NOT NULL