我是Android开发的新手,最近也从eclipse转移到了android studio。我正在尝试制作提醒应用。出现问题的是,在提醒中输入注释时,数据库被创建但不显示在屏幕上,即列表视图。此外,我已检查数据库是否已创建,所有其他工作正常,但我的数据库未显示。
以下是包含XML文件的DBhelper类和ListView:
P.S。如果需要其他java类...请告诉我......
DBHelper类:
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DataBase_NAME = "Reminder.db";
public static final int DataBase_VERSION = 1;
public static final SimpleDateFormat sdf = new
SimpleDateFormat(RemindMe.DEFAULT_DATE_FORMAT);
public DataBaseHelper(Context context) {
super(context, DataBase_NAME, null, DataBase_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(Alarm.getSql());
db.execSQL(AlarmTime.getSql());
db.execSQL(AlarmMsg.getSql());
Log.i(" this works","and this");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Alarm.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + AlarmTime.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + AlarmMsg.TABLE_NAME);
Log.i("at least this works","and this too");
onCreate(db);
}
public void shred(SQLiteDatabase db) {
db.delete(AlarmMsg.TABLE_NAME, AlarmMsg.COL_STATUS+" = ?", new String[]
{AlarmMsg.CANCELLED});
}
private final String populateSQL = Util.concat("SELECT ",
"a."+Alarm.COL_FROMDATE+", ",
"a."+Alarm.COL_TODATE+", ",
"a."+Alarm.COL_RULE+", ",
"a."+Alarm.COL_INTERVAL+", ",
"at."+AlarmTime.COL_AT,
" FROM "+Alarm.TABLE_NAME+" AS a",
" JOIN "+AlarmTime.TABLE_NAME+" AS at",
" ON a."+Alarm.COL_ID+" = at."+AlarmTime.COL_ALARMID,
" WHERE a."+Alarm.COL_ID+" = ?");
public void populate(long alarmId, SQLiteDatabase db) {
String[] selectionArgs = {String.valueOf(alarmId)};
Cursor c = db.rawQuery(populateSQL, selectionArgs);
if (c.moveToFirst()) {
Calendar cal = Calendar.getInstance();
AlarmMsg alarmMsg = new AlarmMsg();
long now = System.currentTimeMillis();
db.beginTransaction();
try {
do {
Date fromDate = sdf.parse(c.getString(0)); //yyyy-M-d
cal.setTime(fromDate);
//at
String[] tokens = c.getString(4).split(":"); //hh:mm
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(tokens[0]));
cal.set(Calendar.MINUTE, Integer.parseInt(tokens[1]));
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
String rule = c.getString(2); //every day month
String interval = c.getString(3); //mm hh dd MM yy
if (rule == null && interval == null) {//one time
alarmMsg.reset();
alarmMsg.setAlarmId(alarmId);
alarmMsg.setDateTime(cal.getTimeInMillis());
if (alarmMsg.getDateTime() < now-Util.MIN)
alarmMsg.setStatus(AlarmMsg.EXPIRED);
alarmMsg.save(db);
} else {//repeating
if (rule != null) {
tokens = rule.split(" ");
interval = "0 0 1 0 0"; //date++;
//Day
if (!"0".equals(tokens[1])) {
cal.set(Calendar.DAY_OF_WEEK,
Integer.parseInt(tokens[1]));
interval = "0 0 7 0 0"; //week++;
}
//Every
if (!"0".equals(tokens[0]) && "0".equals(tokens[1]))
{
cal.set(Calendar.DATE,
Integer.parseInt(tokens[0]));
interval = "0 0 0 1 0"; //month++;
}
//Month
if (!"0".equals(tokens[2])) {
cal.set(Calendar.MONTH,
Integer.parseInt(tokens[2])-1);
interval = "0 0 0 0 1"; //year++;
}
while(cal.getTime().before(fromDate)) {
nextDate(cal, interval);
}
}
Date toDate = sdf.parse(c.getString(1));
toDate.setHours(0);
toDate.setMinutes(0);
toDate.setSeconds(0);
toDate.setDate(toDate.getDate()+1);
while(cal.getTime().before(toDate)) {
alarmMsg.reset();
alarmMsg.setAlarmId(alarmId);
alarmMsg.setDateTime(cal.getTimeInMillis());
if (alarmMsg.getDateTime() < now-Util.MIN)
alarmMsg.setStatus(AlarmMsg.EXPIRED);
alarmMsg.save(db);
nextDate(cal, interval);
}
}
} while(c.moveToNext());
db.setTransactionSuccessful();
} catch (Exception e) {
// Log.e(TAG, e.getMessage(), e);
} finally {
db.endTransaction();
}
}
c.close();
}
private void nextDate(Calendar cal, String interval) {
String[] tokens = interval.split(" ");
cal.add(Calendar.MINUTE, Integer.parseInt(tokens[0]));
cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(tokens[1]));
cal.add(Calendar.DATE, Integer.parseInt(tokens[2]));
cal.add(Calendar.MONTH, Integer.parseInt(tokens[3]));
cal.add(Calendar.YEAR, Integer.parseInt(tokens[4]));
}
private final String listSQL = Util.concat("SELECT ",
"a."+Alarm.COL_NAME+", ",
"am."+AlarmMsg.COL_ID+", ",
"am."+AlarmMsg.COL_DATETIME+", ",
"am."+AlarmMsg.COL_STATUS,
" FROM "+Alarm.TABLE_NAME+" AS a",
" JOIN "+AlarmMsg.TABLE_NAME+" AS am",
" ON a."+Alarm.COL_ID+" = am."+AlarmMsg.COL_ALARMID);
/**
* @param db
* @param args {startTime, endTime}
* @return cursor
*/
public Cursor listNotifications(SQLiteDatabase db, String... args) {
String selection = "am."+AlarmMsg.COL_STATUS+" !=
'"+AlarmMsg.CANCELLED+"'";
selection += (args!=null && args.length>0 && args[0]!=null) ? " AND
am."+AlarmMsg.COL_DATETIME+" >= "+args[0] : "";
selection += (args!=null && args.length>1 && args[1]!=null) ? " AND
am."+AlarmMsg.COL_DATETIME+" <= "+args[1] : "";
String sql = Util.concat(listSQL,
" WHERE "+selection,
" ORDER BY am."+AlarmMsg.COL_DATETIME+" ASC");
return db.rawQuery(sql, null);
}
public int cancelNotification(SQLiteDatabase db, long id, boolean isAlarmId)
{
ContentValues cv = new ContentValues();
cv.put(AlarmMsg.COL_STATUS, AlarmMsg.CANCELLED);
return db.update(AlarmMsg.TABLE_NAME,
cv,
(isAlarmId ? AlarmMsg.COL_ALARMID : AlarmMsg.COL_ID)+" = ?",
new String[]{String.valueOf(id)});
}
public int cancelNotification(SQLiteDatabase db, String startTime, String
endTime) {
ContentValues cv = new ContentValues();
cv.put(AlarmMsg.COL_STATUS, AlarmMsg.CANCELLED);
return db.update(AlarmMsg.TABLE_NAME,
cv,
AlarmMsg.COL_DATETIME+" >= ? AND "+AlarmMsg.COL_DATETIME+" <=
?",
new String[]{startTime, endTime});
}
public static final String getDateStr(int year, int month, int date) {
return Util.concat(year, "-", month, "-", date);
}
public static final String getTimeStr(int hour, int minute) {
return Util.concat(hour, ":", minute>9 ? "":"0", minute);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/bg_repeat" >
<RelativeLayout
android:id="@+id/menu_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#f804fc" >
<TextView
android:id="@+id/heading_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:padding="5dip"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="1"
android:shadowColor="#333333"
android:textColor="#d3e397"
android:textSize="18sp"
android:text="Remind Me" />
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:paddingTop="5dip"
android:paddingBottom="5dip"
android:paddingLeft="5dip"
android:paddingRight="10dip"
android:onClick="onClick"
android:background="@null"
android:src="@drawable/preferences" />
<ImageButton
android:id="@+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@id/imageButton1"
android:paddingTop="5dip"
android:paddingBottom="5dip"
android:paddingLeft="10dip"
android:paddingRight="5dip"
android:onClick="onClick"
android:background="@null"
android:src="@drawable/add" />
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@drawable/range"
android:gravity="center_vertical" >
<ImageButton
android:id="@+id/imageButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dip"
android:paddingBottom="5dip"
android:paddingLeft="5dip"
android:paddingRight="10dip"
android:onClick="onClick"
android:background="@null"
android:src="@drawable/left" />
<TextView
android:id="@+id/range_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textColor="#ffffff" />
<ImageButton
android:id="@+id/imageButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dip"
android:paddingBottom="5dip"
android:paddingLeft="10dip"
android:paddingRight="5dip"
android:onClick="onClick"
android:background="@null"
android:src="@drawable/right" />
</LinearLayout>
<LinearLayout
android:id="@+id/list_view"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:padding="5dip"
android:orientation="vertical" >
<ListView android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="@drawable/line"
android:dividerHeight="3dip"
android:listSelector="@android:color/transparent"
android:cacheColorHint="#00000000"
android:drawSelectorOnTop="false" />
<TextView android:id="@android:id/empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:textColor="#777777"
android:text="No data" />
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="3dip"
android:background="#5c755e"
android:gravity="right"
android:textColor="#3d4935"
android:textSize="10sp"
android:textStyle="italic"
android:text="(c) appsrox.com" />
</LinearLayout>
提醒类:
public class reminder extends ListActivity {
private static final String TAG = "MainActivity";
private TextView headingText;
private Cursor c;
private TextView rangeText;
private ViewSwitcher vs;
private SQLiteDatabase db;
private Typeface font;
private AlertDialog disclaimer;
public final Calendar cal = Calendar.getInstance();
public final Date dt = new Date();
private String[] monthArr;
private Alarm alarm = new Alarm();
private AlarmMsg alarmMsg = new AlarmMsg();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_reminder);
findViews();
db = RemindMe.db;
font = Typeface.createFromAsset(getAssets(), "fonts/OpenSans-
Semibold.ttf");
headingText.setTypeface(font);
monthArr = getResources().getStringArray(R.array.spinner3_arr);
int r = RemindMe.getDateRange();
switch(r) {
case 3: // Yearly
cal.set(Calendar.MONTH, 0);
case 2: // Monthly
cal.set(Calendar.DATE, 1);
case 1: // Weekly
if (r==1) cal.set(Calendar.DATE, cal.getFirstDayOfWeek());
case 0: // Daily
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
}
registerForContextMenu(getListView());
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong("cal", cal.getTimeInMillis());
}
@Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
cal.setTimeInMillis(state.getLong("cal"));
}
private void findViews() {
headingText = (TextView) findViewById(R.id.heading_tv);
rangeText = (TextView) findViewById(R.id.range_tv);
vs = (ViewSwitcher) findViewById(R.id.view_switcher);
}
private String getRangeStr() {
int date = cal.get(Calendar.DATE);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
dt.setTime(System.currentTimeMillis());
switch(RemindMe.getDateRange()) {
case 0: // Daily
if (date==dt.getDate() && month==dt.getMonth() &&
year==dt.getYear()+1900) return "Today";
else return date+" "+monthArr[month+1];
case 1: // Weekly
return date+" "+monthArr[month+1] + move(+1) + " - " +
cal.get(Calendar.DATE)+" "+monthArr[cal.get(Calendar.MONTH)+1] + move(-1);
case 2: // Monthly
return monthArr[month+1]+" "+year;
case 3: // Yearly
return year+"";
}
return null;
}
private Cursor createCursor() {
if(c!=null){
c = RemindMe.dbHelper.listNotifications(db,
cal.getTimeInMillis()+move(+1), cal.getTimeInMillis()+move(-1));
startManagingCursor(c);
return c;}
else return null;
}
@Override
protected void onResume() {
super.onResume();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.reminder_row,
createCursor(),
new String[]{Alarm.COL_NAME, AlarmMsg.COL_DATETIME,
AlarmMsg.COL_DATETIME, AlarmMsg.COL_DATETIME, AlarmMsg.COL_DATETIME},
new int[]{R.id.msg_tv, R.id.year_tv, R.id.month_tv,
R.id.date_tv, R.id.time_tv});
adapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int
columnIndex) {
if (view.getId() == R.id.msg_tv) return false;
TextView tv = (TextView)view;
long time = cursor.getLong(columnIndex);
dt.setTime(time);
switch(view.getId()) {
case R.id.year_tv:
tv.setText(String.valueOf(dt.getYear()+1900));
break;
case R.id.month_tv:
tv.setText(monthArr[dt.getMonth()+1]);
break;
case R.id.date_tv:
tv.setText(String.valueOf(dt.getDate()));
break;
case R.id.time_tv:
long now = System.currentTimeMillis();
String txt = RemindMe.showRemainingTime() ?
Util.getRemainingTime(time, now) : Util.getActualTime(dt.getHours(),
dt.getMinutes());
if (TextUtils.isEmpty(txt)) txt =
Util.getActualTime(dt.getHours(), dt.getMinutes());
tv.setText(txt);
RelativeLayout parent = (RelativeLayout)tv.getParent();
TextView tv2 = (TextView)
parent.findViewById(R.id.msg_tv);
if (time < now)
tv2.setTextColor(Color.parseColor("#555555"));
else tv2.setTextColor(Color.parseColor("#587498"));
break;
}
return true;
}
});
setListAdapter(adapter);
rangeText.setText(getRangeStr());
}
private String move(int step) {
switch(RemindMe.getDateRange()) {
case 0:
cal.add(Calendar.DATE, 1*step);
break;
case 1:
cal.add(Calendar.DATE, 7*step);
break;
case 2:
cal.add(Calendar.MONTH, 1*step);
break;
case 3:
cal.add(Calendar.YEAR, 1*step);
break;
}
return "";
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton1:
startActivity(new Intent(this, Settings_Activity.class));
break;
case R.id.imageButton2:
startActivity(new Intent(this, AddAlarmActivity.class));
break;
case R.id.imageButton3:
move(-1);
rangeText.setText(getRangeStr());
((SimpleCursorAdapter)getListAdapter()).changeCursor(createCursor());
break;
case R.id.imageButton4:
move(+1);
rangeText.setText(getRangeStr());
((SimpleCursorAdapter)getListAdapter()).changeCursor(createCursor());
break;
case R.id.toggleButton1:
vs.showNext();
break;*/
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menuInfo) {
if (v.getId() == android.R.id.list) {
getMenuInflater().inflate(R.menu.reminder_context_menu, menu);
menu.setHeaderTitle("Choose an Option");
menu.setHeaderIcon(R.drawable.ic_dialog_menu_generic);
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) menuInfo;
alarmMsg.setId(info.id);
alarmMsg.load(db);
if (alarmMsg.getDateTime() < System.currentTimeMillis())
menu.removeItem(R.id.menu_edit);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
boolean refresh = false;
switch (item.getItemId()) {
case R.id.menu_edit:
alarmMsg.setId(info.id);
alarmMsg.load(db);
alarm.reset();
alarm.setId(alarmMsg.getAlarmId());
alarm.load(db);
showDialog(R.id.menu_edit);
break;
case R.id.menu_delete:
RemindMe.dbHelper.cancelNotification(db, info.id, false);
refresh = true;
Intent cancelThis = new Intent(this,
reminder_alarm_service.class);
cancelThis.putExtra(AlarmMsg.COL_ID, String.valueOf(info.id));
cancelThis.setAction(reminder_alarm_service.CANCEL);
startService(cancelThis);
break;
case R.id.menu_delete_repeating:
alarmMsg.setId(info.id);
alarmMsg.load(db);
RemindMe.dbHelper.cancelNotification(db, alarmMsg.getAlarmId(),
true);
refresh = true;
Intent cancelRepeating = new Intent(this,
reminder_alarm_service.class);
cancelRepeating.putExtra(AlarmMsg.COL_ALARMID,
String.valueOf(alarmMsg.getAlarmId()));
cancelRepeating.setAction(reminder_alarm_service.CANCEL);
startService(cancelRepeating);
break;
}
if (refresh) {
SimpleCursorAdapter adapter = (SimpleCursorAdapter)
getListAdapter();
adapter.getCursor().requery();
adapter.notifyDataSetChanged();
}
return true;
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
openContextMenu(v);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case R.id.menu_edit:
return new AlertDialog.Builder(this)
.setTitle("Edit")
.setView(getLayoutInflater().inflate(R.layout.edit,
null))
.setCancelable(false)
.setPositiveButton("Ok", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
Dialog d = (Dialog) dialog;
EditText msgEdit = (EditText)
d.findViewById(R.id.msg_et);
CheckBox soundCb = (CheckBox)
d.findViewById(R.id.sound_cb);
alarm.setSound(soundCb.isChecked());
if (!TextUtils.isEmpty(msgEdit.getText())) {
alarm.setName(msgEdit.getText().toString());
alarm.persist(db);
SimpleCursorAdapter adapter =
(SimpleCursorAdapter) getListAdapter();
adapter.getCursor().requery();
adapter.notifyDataSetChanged();
} else {
Toast.makeText(reminder.this, "Enter a
message", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
})
.create();
}
return super.onCreateDialog(id);
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case R.id.menu_edit:
EditText msgEdit = (EditText) dialog.findViewById(R.id.msg_et);
CheckBox soundCb = (CheckBox)
dialog.findViewById(R.id.sound_cb);
msgEdit.setText(alarm.getName());
soundCb.setChecked(alarm.getSound());
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.reminder_options_menu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (getListAdapter().isEmpty()) {
menu.findItem(R.id.menu_delete_all).setEnabled(false);
} else {
menu.findItem(R.id.menu_delete_all).setEnabled(true);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete_all:
String startTime = cal.getTimeInMillis()+move(+1);
String endTime = cal.getTimeInMillis()+move(-1);
RemindMe.dbHelper.cancelNotification(db, startTime, endTime);
Intent cancelAll = new Intent(this,
reminder_alarm_service.class);
cancelAll.putExtra(Alarm.COL_FROMDATE, startTime);
cancelAll.putExtra(Alarm.COL_TODATE, endTime);
cancelAll.setAction(reminder_alarm_service.CANCEL);
startService(cancelAll);
SimpleCursorAdapter adapter = (SimpleCursorAdapter)
getListAdapter();
adapter.getCursor().requery();
adapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
if (disclaimer != null)
disclaimer.dismiss();
super.onDestroy();
}
}