Я опробовал несколько различных способов загрузки счетчика из базы данных SQLite, этот метод кажется самым простым и легким. Единственное, что я добавил в пару своих переменных (еще три). Когда я запускаю отредактированную версию, чтобы соответствовать моим требованиям тестирования, все работает правильно, за исключением того, что счетчик не заполняется данными из базы данных
Класс SpinnerLoad
public class SpinnerLoad extends Activity implements OnClickListener {
private Db thisTestDBAdapter;
Button save;
EditText one, two, three;
Spinner spinner;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnerform);
save = (Button) findViewById(R.id.spinLoad_save);
save.setOnClickListener(this);
one = (EditText) findViewById(R.id.spinLoad_serial);
two = (EditText) findViewById(R.id.spinLoad_name);
three = (EditText) findViewById(R.id.spinLoad_place);
fillData();
spinner = (Spinner) findViewById(R.id.spinLoad_spinner);
try {
spinner.setOnItemSelectedListener(new Person());
} catch (Exception e) {
e.printStackTrace();
}
}
public static class Person implements OnItemSelectedListener {
static String personReturn;
static boolean personTest = false;
@Override
public void onItemSelected(AdapterView<?> x, View y, int z, long w) {
personReturn = (x.getItemAtPosition(z)).toString();
personTest = true;
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
personTest = false;
}
}
private void fillData() {
try {
Cursor coloursCursor;
spinner = (Spinner) findViewById(R.id.spinLoad_spinner);
coloursCursor = thisTestDBAdapter.fetchAllColours();
startManagingCursor(coloursCursor);
String[] from = new String[] { thisTestDBAdapter.KEY_TWO };
int[] to = new int[] { R.id.tvDBViewRow };
SimpleCursorAdapter colourAdapter = new SimpleCursorAdapter(this,
R.layout.db_view_row, coloursCursor, from, to);
spinner.setAdapter(colourAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.spinLoad_save:
String bx = two.getText().toString();
/**/
String ax = one.getText().toString();
String cx = three.getText().toString();
String returned = Person.personReturn;
Db entry = new Db(this);
entry.open();
entry.createEntry(ax, bx, cx, returned);
entry.close();
fillData();
/**/
break;
}
}
}
ДБ SQL вспомогательный класс
public class Db {
private static final String TAG = "SpinnerDBHelper";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final int DATABASE_VERSION = 2;
private final Context mCtx;
/**/
private static final String KEY_DB = "DataBaseName";
private static final String KEY_TABLE = "DbTable";
public static final String KEY_ROWID = "_rowid"; // 0
public static final String KEY_ONE = "serial";
public static final String KEY_TWO = "name";
public static final String KEY_THREE = "place";
public static final String KEY_FOUR = "returned";
/**/
private static final String DATABASE_CREATE = "CREATE TABLE DbTable (_rowid INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "serial TEXT NOT NULL, "+ "name TEXT NOT NULL, " + "place TEXT NOT NULL, " + "returned TEXT NOT NULL);";
public Db(Context ctx) {
this.mCtx = ctx;
}
public Db open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createEntry(String ax, String bx, String cx, String returned) {
if (mDb == null) {
this.open();
}
ContentValues cv = new ContentValues();
cv.put(KEY_ONE, ax);
cv.put(KEY_TWO, bx);
cv.put(KEY_THREE, cx);
cv.put(KEY_FOUR, returned);
return mDb.insert(KEY_TABLE, null, cv);
}
public boolean deleteEntry(long rowId) {
return mDb.delete(KEY_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public boolean deleteAll() {
if (mDb == null) {
this.open();
}
return mDb.delete(KEY_TABLE, null, null) > 0;
}
public Cursor fetchAllColours() {
if (mDb == null) {
this.open();
}
return mDb.query(KEY_TABLE, new String[] { KEY_ROWID, KEY_TWO},
null, null, null, null, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, KEY_DB, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + KEY_TABLE);
onCreate(db);
}
}
}
LogCat
12-26 23:39:33.409: W/System.err(30879): java.lang.NullPointerException
12-26 23:39:33.409: W/System.err(30879): at com.my.examples.SpinnerLoad.fillData(SpinnerLoad.java:59)
12-26 23:39:33.409: W/System.err(30879): at com.my.examples.SpinnerLoad.onCreate(SpinnerLoad.java:30)
12-26 23:39:33.418: W/System.err(30879): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-26 23:39:33.418: W/System.err(30879): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
12-26 23:39:33.418: W/System.err(30879): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
12-26 23:39:33.418: W/System.err(30879): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
12-26 23:39:33.418: W/System.err(30879): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
12-26 23:39:33.418: W/System.err(30879): at android.os.Handler.dispatchMessage(Handler.java:99)
12-26 23:39:33.418: W/System.err(30879): at android.os.Looper.loop(Looper.java:123)
12-26 23:39:33.418: W/System.err(30879): at android.app.ActivityThread.main(ActivityThread.java:4627)
12-26 23:39:33.428: W/System.err(30879): at java.lang.reflect.Method.invokeNative(Native Method)
12-26 23:39:33.428: W/System.err(30879): at java.lang.reflect.Method.invoke(Method.java:521)
12-26 23:39:33.428: W/System.err(30879): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-26 23:39:33.428: W/System.err(30879): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-26 23:39:33.428: W/System.err(30879): at dalvik.system.NativeStart.main(Native Method)
12-26 23:40:00.628: E/Database(30879): Error inserting place=zyxwvutsr returned=null serial=123456789 name=abcdefghij
12-26 23:40:00.628: E/Database(30879): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
12-26 23:40:00.628: E/Database(30879): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
12-26 23:40:00.628: E/Database(30879): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:55)
12-26 23:40:00.628: E/Database(30879): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1549)
12-26 23:40:00.628: E/Database(30879): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)
12-26 23:40:00.628: E/Database(30879): at com.my.examples.Db.createEntry(Db.java:56)
12-26 23:40:00.628: E/Database(30879): at com.my.examples.SpinnerLoad.onClick(SpinnerLoad.java:86)
12-26 23:40:00.628: E/Database(30879): at android.view.View.performClick(View.java:2408)
12-26 23:40:00.628: E/Database(30879): at android.view.View$PerformClick.run(View.java:8816)
12-26 23:40:00.628: E/Database(30879): at android.os.Handler.handleCallback(Handler.java:587)
12-26 23:40:00.628: E/Database(30879): at android.os.Handler.dispatchMessage(Handler.java:92)
12-26 23:40:00.628: E/Database(30879): at android.os.Looper.loop(Looper.java:123)
12-26 23:40:00.628: E/Database(30879): at android.app.ActivityThread.main(ActivityThread.java:4627)
12-26 23:40:00.628: E/Database(30879): at java.lang.reflect.Method.invokeNative(Native Method)
12-26 23:40:00.628: E/Database(30879): at java.lang.reflect.Method.invoke(Method.java:521)
12-26 23:40:00.628: E/Database(30879): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-26 23:40:00.628: E/Database(30879): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-26 23:40:00.628: E/Database(30879): at dalvik.system.NativeStart.main(Native Method)
12-26 23:40:00.628: W/System.err(30879): java.lang.NullPointerException
12-26 23:40:00.639: W/System.err(30879): at com.my.examples.SpinnerLoad.fillData(SpinnerLoad.java:59)
12-26 23:40:00.639: W/System.err(30879): at com.my.examples.SpinnerLoad.onClick(SpinnerLoad.java:89)
12-26 23:40:00.639: W/System.err(30879): at android.view.View.performClick(View.java:2408)
12-26 23:40:00.639: W/System.err(30879): at android.view.View$PerformClick.run(View.java:8816)
12-26 23:40:00.639: W/System.err(30879): at android.os.Handler.handleCallback(Handler.java:587)
12-26 23:40:00.639: W/System.err(30879): at android.os.Handler.dispatchMessage(Handler.java:92)
12-26 23:40:00.639: W/System.err(30879): at android.os.Looper.loop(Looper.java:123)
12-26 23:40:00.639: W/System.err(30879): at android.app.ActivityThread.main(ActivityThread.java:4627)
12-26 23:40:00.639: W/System.err(30879): at java.lang.reflect.Method.invokeNative(Native Method)
12-26 23:40:00.649: W/System.err(30879): at java.lang.reflect.Method.invoke(Method.java:521)
12-26 23:40:00.649: W/System.err(30879): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-26 23:40:00.649: W/System.err(30879): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-26 23:40:00.649: W/System.err(30879): at dalvik.system.NativeStart.main(Native Method)
С кошкой-журналом я могу сделать что-то для новичка, новичка, лол ... но я просмотрел его пару раз бок о бок с оригиналом и не уверен, что я мог испортить. Надеясь, что кто-то может пролить немного света на это для меня, если потребуется дополнительная информация, пожалуйста, дайте мне знать. Спасибо