有人知道为什么我的数据库没有按预期保存吗?当我在我的Activity中时,我可以很容易地从数据库中保存和加载数据。一旦我离开并租用数据库活动,它就不会保留数据库的任何信息。
我正在使用数据库助手
public class DatabaseHandler extends SQLiteOpenHelper{
为了生成初始表,我在前言中执行此操作,创建可写数据库请求以启动onCreate()。当我把它拿出来时,系统会因为没有数据库而出错。
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.myContext = context;
// TODO Auto-generated constructor stub
myDataBase = this.getWritableDatabase();
myDataBase.close();
}
我在onCreate
上生成表格@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE DAILYWORK (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"day INTEGER," +
"time TEXT," +
"work INTEGER DEFAULT 0)");
db.execSQL("CREATE TABLE DAILYPREACHLOG (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"day INTEGER," +
"time TEXT," +
"contacts INTEGER DEFAULT 0," +
"m20 INTEGER DEFAULT 0," +
"m30 INTEGER DEFAULT 0," +
"m40 INTEGER DEFAULT 0," +
"f20 INTEGER DEFAULT 0," +
"f30 INTEGER DEFAULT 0," +
"f40 INTEGER DEFAULT 0)");
db.execSQL("CREATE TABLE CONTACTLOG (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"firstname TEXT," +
"lastname TEXT," +
"phone TEXT," +
"email TEXT," +
"address TEXT)");
}
从我读到的生成onCreate()与实现的sqlhelper只会创建表,如果它们不存在。然而,似乎每次我进入它都会删除旧表并重新创建它们。
每个请求的完整数据库活动
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_PATH = "/data/data/com.example.johnbravado.zionwork/databases/";
private static final String DATABASE_NAME = "zionWorkDB.db";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase myDataBase = null;
private final Context myContext;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.myContext = context;
// TODO Auto-generated constructor stub
myDataBase = this.getWritableDatabase();
myDataBase.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE DAILYWORK (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"day INTEGER," +
"time TEXT," +
"work INTEGER DEFAULT 0)");
db.execSQL("CREATE TABLE DAILYPREACHLOG (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"day INTEGER," +
"time TEXT," +
"contacts INTEGER DEFAULT 0," +
"m20 INTEGER DEFAULT 0," +
"m30 INTEGER DEFAULT 0," +
"m40 INTEGER DEFAULT 0," +
"f20 INTEGER DEFAULT 0," +
"f30 INTEGER DEFAULT 0," +
"f40 INTEGER DEFAULT 0)");
db.execSQL("CREATE TABLE CONTACTLOG (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"firstname TEXT," +
"lastname TEXT," +
"phone TEXT," +
"email TEXT," +
"address TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
// Drop older table if existed
//arg0.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWSONGS);
// Create tables again
onCreate(arg0);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
public void openDataBase() throws SQLException {
//Open the database
String myPath = DATABASE_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
public boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DATABASE_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
//database does not exist yet
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
public void reset() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
myContext.deleteDatabase(DATABASE_NAME);
}
}
public void addDailyWork(long day, String time, int work) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("day", day);
values.put("time", time);
values.put("work", work);
db.insert("DAILYWORK", null, values);
db.close();
}
public void addDailyPreachLog(long day, String time, int[] counts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("day", day);
values.put("time", time);
values.put("contacts", counts[6]);
values.put("m20", counts[0]);
values.put("m30", counts[1]);
values.put("m40", counts[2]);
values.put("f20", counts[3]);
values.put("f30", counts[4]);
values.put("f40", counts[5]);
db.insert("DAILYPREACHLOG", null, values);
db.close();
}
public void updateDailyPreachLog(long day, String time, int[] counts) {
SQLiteDatabase db = this.getWritableDatabase();
String whereClause = "day=" + String.format(String.format("%1$d", day)) + " AND time=\"" + time + "\"";
ContentValues values = new ContentValues();
//values.put("day", day);
//values.put("time", time);
values.put("contacts", counts[6]);
values.put("m20", counts[0]);
values.put("m30", counts[1]);
values.put("m40", counts[2]);
values.put("f20", counts[3]);
values.put("f30", counts[4]);
values.put("f40", counts[5]);
db.update("DAILYPREACHLOG", values, whereClause, null);
db.close();
}
public String getPreachLogString(long day, String time) {
String selectQuery;
SQLiteDatabase db;
Cursor cursor;
String tmp;
String result = null;
String myPath = DATABASE_PATH + DATABASE_NAME;
SimpleDateFormat formatDate = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
selectQuery = "SELECT * FROM DAILYPREACHLOG WHERE day = " + day + " AND time = \"" + time + "\"";
cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
tmp = String.format("M20:%1$d : M30:%2$d : M40:%3$d : F20:%4$d : F30:%5$d : F40:%6$d",
cursor.getInt(cursor.getColumnIndex("m20")),
cursor.getInt(cursor.getColumnIndex("m30")),
cursor.getInt(cursor.getColumnIndex("m40")),
cursor.getInt(cursor.getColumnIndex("f20")),
cursor.getInt(cursor.getColumnIndex("f30")),
cursor.getInt(cursor.getColumnIndex("f40")));
result = tmp;
}
cursor.close();
db.close();
return result;
}
public HashMap<String, Integer> getPreachLogData(long day, String time) {
String selectQuery;
SQLiteDatabase db;
Cursor cursor;
String tmp;
HashMap<String, Integer> result = new HashMap<String, Integer>();
String myPath = DATABASE_PATH + DATABASE_NAME;
SimpleDateFormat formatDate = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
selectQuery = "SELECT * FROM DAILYPREACHLOG WHERE day = " + day + " AND time = \"" + time + "\"";
cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
result.put(MyConstants.DB_M20_HASH_KEY, cursor.getInt(cursor.getColumnIndex("m20")));
result.put(MyConstants.DB_M30_HASH_KEY, cursor.getInt(cursor.getColumnIndex("m30")));
result.put(MyConstants.DB_M40_HASH_KEY, cursor.getInt(cursor.getColumnIndex("m40")));
result.put(MyConstants.DB_F20_HASH_KEY, cursor.getInt(cursor.getColumnIndex("f20")));
result.put(MyConstants.DB_F30_HASH_KEY, cursor.getInt(cursor.getColumnIndex("f30")));
result.put(MyConstants.DB_F40_HASH_KEY, cursor.getInt(cursor.getColumnIndex("f40")));
result.put(MyConstants.DB_CONTACTS_HASH_KEY, cursor.getInt(cursor.getColumnIndex("contacts")));
}
cursor.close();
db.close();
return result;
}
public ArrayList<String> getMonthlyWork(int year, int month) {
long thismonth = 0;
long nextmonth = 0;
String selectQuery;
SQLiteDatabase db;
ArrayList<String> result = new ArrayList<>();
SimpleDateFormat formatDate = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
String myPath = DATABASE_PATH + DATABASE_NAME;
Calendar c = Calendar.getInstance();
c.set(year, month, 1);
thismonth = c.getTimeInMillis();
if (month < 11) {
c.set(Calendar.MONTH, month + 1);
} else {
c.set(Calendar.MONTH, 0);
c.set(Calendar.YEAR, year + 1);
}
nextmonth = c.getTimeInMillis();
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
selectQuery = "SELECT * FROM DAILYWORK WHERE day BETWEEN " + thismonth + " AND " + nextmonth;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
c.setTimeInMillis(cursor.getLong(cursor.getColumnIndex("day")));
formatDate.format(c.getTime());
result.add(formatDate.format(c.getTime()) + ", "
+ cursor.getString(cursor.getColumnIndex("time")) + ", "
+ cursor.getInt(cursor.getColumnIndex("work")));
while (cursor.moveToNext()) {
c.setTimeInMillis(cursor.getLong(cursor.getColumnIndex("day")));
formatDate.format(c.getTime());
result.add(formatDate.format(c.getTime()) + ", "
+ cursor.getString(cursor.getColumnIndex("time")) + ", "
+ cursor.getInt(cursor.getColumnIndex("work")));
}
}
cursor.close();
db.close();
return result;
}
}
部分活动,因为太长了
public class CounterActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
//stuff removed for space
initgui();
}
tod_spin = (Spinner)findViewById(R.id.counter_tod_spinner);
ArrayAdapter tofdAdapter = ArrayAdapter.createFromResource (this, R.array.tofd, android.R.layout.simple_spinner_item);
tofdAdapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item);
tod_spin.setAdapter(tofdAdapter);
tod_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
DatabaseHandler db;
HashMap<String, Integer> preachData;
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
db = new DatabaseHandler(CounterActivity.this);
preachData = db.getPreachLogData(dateInMillis, tod_spin.getSelectedItem().toString());
db.close();
if(pos == 0){
save_preachlog_btn.setEnabled(false);
view_preachlog_btn.setEnabled(false);
}else{
save_preachlog_btn.setEnabled(true);
if(preachData.isEmpty()){
view_preachlog_btn.setEnabled(false);
}else{
view_preachlog_btn.setEnabled(true);
}
db.close();
}
updateCounterInterfaceCounts(preachData);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
dateInMillis = c.getTimeInMillis();
tv_counter_date =(TextView)findViewById(R.id.counter_date_tv);
tv_counter_date.setText(new StringBuilder()
.append(month + 1).append("-")
.append(day).append("-").append(year)
.append(" "));
tv_counter_date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog(MyConstants.DATE_DIALOG_ID);
}
});
save_preachlog_btn = (Button)findViewById(R.id.btn_save_count);
save_preachlog_btn.setEnabled(false);
save_preachlog_btn.setText(MyConstants.START_SERVICE_BTN_LBL);
save_preachlog_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int[] counters = new int[7];
String currentState = save_preachlog_btn.getText().toString();
DatabaseHandler db;
if(currentState.compareTo(MyConstants.START_SERVICE_BTN_LBL) == 0){
tod_spin.setEnabled(false);
tv_counter_date.setEnabled(false);
view_preachlog_btn.setEnabled(false);
if(!MyWearableListenerService.isRunning()){
startService(wearListenerIntent);
}
db = new DatabaseHandler(CounterActivity.this);
if(db.getPreachLogString(dateInMillis, tod_spin.getSelectedItem().toString()) == null){
save_preachlog_btn.setText(MyConstants.SAVE_SERVICE_BTN_LBL);
}else{
save_preachlog_btn.setText(MyConstants.UPDATE_SERVICE_BTN_LBL);
}
db.close();
enableCountButtons();
}else if(currentState.compareTo(MyConstants.SAVE_SERVICE_BTN_LBL) == 0){
save_preachlog_btn.setText(MyConstants.START_SERVICE_BTN_LBL);
disableCountButtons();
stopService(wearListenerIntent);
counters[0] = m20CountTotal;
counters[1] = m30CountTotal;
counters[2] = m40CountTotal;
counters[3] = f20CountTotal;
counters[4] = f30CountTotal;
counters[5] = f40CountTotal;
counters[6] = contactCountTotal;
db = new DatabaseHandler(CounterActivity.this);
db.addDailyPreachLog(dateInMillis, tod_spin.getSelectedItem().toString(), counters);
db.close();
tod_spin.setEnabled(true);
tv_counter_date.setEnabled(true);
view_preachlog_btn.setEnabled(true);
}else if(currentState.compareTo(MyConstants.UPDATE_SERVICE_BTN_LBL) == 0){
save_preachlog_btn.setText(MyConstants.START_SERVICE_BTN_LBL);
disableCountButtons();
stopService(wearListenerIntent);
counters[0] = m20CountTotal;
counters[1] = m30CountTotal;
counters[2] = m40CountTotal;
counters[3] = f20CountTotal;
counters[4] = f30CountTotal;
counters[5] = f40CountTotal;
counters[6] = contactCountTotal;
db = new DatabaseHandler(CounterActivity.this);
db.updateDailyPreachLog(dateInMillis, tod_spin.getSelectedItem().toString(), counters);
db.close();
tod_spin.setEnabled(true);
tv_counter_date.setEnabled(true);
view_preachlog_btn.setEnabled(true);
}
}
});
view_preachlog_btn = (Button)findViewById(R.id.btn_view_count);
view_preachlog_btn.setEnabled(false);
view_preachlog_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String log;
DatabaseHandler db = new DatabaseHandler(CounterActivity.this);
log = db.getPreachLogString(dateInMillis, tod_spin.getSelectedItem().toString());
db.close();
Toast.makeText(CounterActivity.this, log, Toast.LENGTH_LONG).show();
sendNotification("Preach Log", log);
}
});
disableCountButtons();
}
private void updateCounterInterfaceCounts(HashMap<String, Integer> data) {
if(data.isEmpty()){
m20CountTotal = 0;
m30CountTotal = 0;
m40CountTotal = 0;
f20CountTotal = 0;
f30CountTotal = 0;
f40CountTotal = 0;
contactCountTotal = 0;
}else {
m20CountTotal = data.get(MyConstants.DB_M20_HASH_KEY);
m30CountTotal = data.get(MyConstants.DB_M30_HASH_KEY);
m40CountTotal = data.get(MyConstants.DB_M40_HASH_KEY);
f20CountTotal = data.get(MyConstants.DB_F20_HASH_KEY);
f30CountTotal = data.get(MyConstants.DB_F30_HASH_KEY);
f40CountTotal = data.get(MyConstants.DB_F40_HASH_KEY);
contactCountTotal = data.get(MyConstants.DB_CONTACTS_HASH_KEY);
}
preachCountTotal = m20CountTotal + m30CountTotal + m40CountTotal +
f20CountTotal + f30CountTotal + f40CountTotal;
preachCountTotalTv.setText(String.format("%1$d", preachCountTotal));
contactCountTotalTv.setText(String.format("%1$d", contactCountTotal));
m20_vcb.setCount(m20CountTotal);
m30_vcb.setCount(m30CountTotal);
m40_vcb.setCount(m40CountTotal);
f20_vcb.setCount(f20CountTotal);
f30_vcb.setCount(f30CountTotal);
f40_vcb.setCount(f40CountTotal);
}
private void disableCountButtons(){
contactSubCountBtn.setEnabled(false);
m20_vcb.disable();
m30_vcb.disable();
m40_vcb.disable();
f20_vcb.disable();
f30_vcb.disable();
f40_vcb.disable();
}
private void enableCountButtons(){
contactSubCountBtn.setEnabled(true);
m20_vcb.enable();
m30_vcb.enable();
m40_vcb.enable();
f20_vcb.enable();
f30_vcb.enable();
f40_vcb.enable();
contactAddCountBtn.setEnabled(true);
}
private void sendMessageToWearable(final String path, final String text) {
new Thread( new Runnable() {
@Override
public void run() {
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await();
for(Node node : nodes.getNodes()) {
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(
mGoogleApiClient, node.getId(), path, text.getBytes() ).await();
}
runOnUiThread( new Runnable() {
@Override
public void run() {
//mEditText.setText( "" );
}
});
}
}).start();
}
private DatePickerDialog.OnDateSetListener datePickerListener
= new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into textview
tv_counter_date.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
Calendar c = Calendar.getInstance(Locale.US);
c.set(year, month, day);
dateInMillis = c.getTimeInMillis();
}
};
private void SendIntDataToWear(String path, String key, int data) {
PutDataMapRequest putDataMapReq = PutDataMapRequest.create(path);
putDataMapReq.getDataMap().putInt(key, data);
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
PendingResult<DataApi.DataItemResult> pendingResult =
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
}
private boolean showToast(String message){
Toast.makeText(CounterActivity.this, message, Toast.LENGTH_LONG).show();
return true;
}
private void sendNotification(String title, String content){
int notificationId = 001;
//Building notification layout
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(content)
.setVibrate(new long[]{1000,1000})
.setDefaults(Notification.DEFAULT_ALL);
// instance of the NotificationManager service
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
// Build the notification and notify it using notification manager.
notificationManager.notify(notificationId, notificationBuilder.build());
}
private int increasePreachCountTotal(){
preachCountTotal++;
preachCountTotalTv.setText(String.format("%1$d", preachCountTotal));
return preachCountTotal;
}
private int decreasePreachCountTotal(){
if(preachCountTotal > 0){
preachCountTotal--;
}
preachCountTotalTv.setText(String.format("%1$d", preachCountTotal));
return preachCountTotal;
}
private void increaseCountTotal(int count){
switch(count){
case MyConstants.M20:
m20CountTotal++;
break;
case MyConstants.M30:
m30CountTotal++;
break;
case MyConstants.M40:
m40CountTotal++;
break;
case MyConstants.F20:
f20CountTotal++;
break;
case MyConstants.F30:
f30CountTotal++;
break;
case MyConstants.F40:
f40CountTotal++;
break;
}
increasePreachCountTotal();
}
private void decreaseCountTotal(int count){
switch(count){
case MyConstants.M20:
if(m20CountTotal > 0){
m20CountTotal--;
decreasePreachCountTotal();
}
//m20CountTotalTv.setText(String.format("%1$d", m20CountTotal));
break;
case MyConstants.M30:
if(m30CountTotal > 0){
m30CountTotal--;
decreasePreachCountTotal();
}
//m30CountTotalTv.setText(String.format("%1$d", m30CountTotal));
break;
case MyConstants.M40:
if(m40CountTotal > 0){
m40CountTotal--;
decreasePreachCountTotal();
}
//m40CountTotalTv.setText(String.format("%1$d", m40CountTotal));
break;
case MyConstants.F20:
if(f20CountTotal > 0){
f20CountTotal--;
decreasePreachCountTotal();
}
//f20CountTotalTv.setText(String.format("%1$d", f20CountTotal));
break;
case MyConstants.F30:
if(f30CountTotal > 0){
f30CountTotal--;
decreasePreachCountTotal();
}
//f30CountTotalTv.setText(String.format("%1$d", f30CountTotal));
break;
case MyConstants.F40:
if(f40CountTotal > 0){
f40CountTotal--;
decreasePreachCountTotal();
}
//f40CountTotalTv.setText(String.format("%1$d", f40CountTotal));
break;
}
}
public class WearableReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Intent service = new Intent(context, WearableReceiverService.class);
//startWakefulService(context, service);
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"com.example.johnbravado.zionwork");
wakeLock.acquire();
// Do Work
msgReqAction(intent.getIntExtra(MyConstants.BROADCAST_DATA_REQ, 0));
wakeLock.release();
}
}
}
答案 0 :(得分:0)
这是一个无关的错误,是由于没有向数据库提供正确的信息。因为我没有设置我用作验证字段的时间变量的小时,分钟和毫秒,所以没有找到该值。
<RequestOptionsArgs> {headers: headers, withCredentials: true}