每次我打开一个新活动时,Android SQLite数据库似乎都会清除

时间:2011-10-22 05:29:58

标签: java android eclipse sqlite

我一直试图修复这两个错误一段时间,我觉得这与我开启一项新活动时会发生的根本误解有关。基本上该程序是一个任务管理程序。当我在不修改类别的情况下添加新任务时,它工作正常,数据库更新正常,应用程序的主页面在我添加新任务时更新以显示这些新任务。

但是,我最近添加了“添加类别”按钮的功能。此按钮的目的是打开一个新的listactivity,允许用户添加新的任务类别。每次我从任务编辑活动打开它,然后按后退按钮返回主页面,数据库中的所有任务都将被清除。想知道是否有人能告诉我发生了什么以及为什么数据会被消灭。

这是首页的相关代码段(显示所有任务的列表视图:

private RemindersDbAdapter mDbHelper;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.reminder_list);
    mDbHelper = new RemindersDbAdapter(this);
    mDbHelper.open();
    fillData();
    registerForContextMenu(getListView());

}


private void fillData() {
    Cursor remindersCursor = mDbHelper.fetchAllReminders();
    startManagingCursor(remindersCursor);

    // Create an array to specify the fields we want to display in the list (only TITLE)
    String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};

    // and an array of the fields we want to bind those fields to (in this case just text1)
    int[] to = new int[]{R.id.text1};

    // Now create a simple cursor adapter and set it to display
    SimpleCursorAdapter reminders = 
            new SimpleCursorAdapter(this, R.layout.reminder_row, remindersCursor, from, to);
    setListAdapter(reminders);
}

以下是我的任务编辑视图的一些代码(调用类别列表的活动的代码):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mDbHelper = new RemindersDbAdapter(this);
    //mCatDbHelper = new CategoriesDbAdapter(this);

    setContentView(R.layout.reminder_edit);

    mCalendar = Calendar.getInstance(); 
    mTitleText = (EditText) findViewById(R.id.title);
    //mBodyText = (EditText) findViewById(R.id.body);
    mDateButton = (Button) findViewById(R.id.reminder_date);
    mTimeButton = (Button) findViewById(R.id.reminder_time);
    mLowPriorityButton = (Button) findViewById(R.id.low_priority);
    mMedPriorityButton = (Button) findViewById(R.id.med_priority);
    mHighPriorityButton = (Button) findViewById(R.id.high_priority);
    mManageCategories = (Button) findViewById(R.id.manage_categories);
    mSchoolRadio = (RadioButton)findViewById(R.id.radio_schoolwork);
    mFamilyRadio = (RadioButton)findViewById(R.id.radio_family);
    mOtherRadio = (RadioButton)findViewById(R.id.radio_other);
    mContext = this;

    priority = "Low";
    category = "Other";


    mConfirmButton = (Button) findViewById(R.id.confirm);

    mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID) 
                                    : -1L;


    registerButtonListenersAndSetDefaultText();
}

private void setRowIdFromIntent() {
    if (mRowId == -1L) {
        Bundle extras = getIntent().getExtras();            
        mRowId = extras != null ? extras.getLong(RemindersDbAdapter.KEY_ROWID) 
                                : -1L;

    }
}

@Override
protected void onPause() {
    super.onPause();
    mDbHelper.close(); 
}

@Override
protected void onResume() {
    super.onResume();
    mDbHelper.open(); 
    setRowIdFromIntent();

    //if(mRowId != -1L)
    populateFields();
}

@Override
protected Dialog onCreateDialog(int id) {
    switch(id) {
        case DATE_PICKER_DIALOG: 
            return showDatePicker();
        case TIME_PICKER_DIALOG: 
            return showTimePicker(); 
    }
    return super.onCreateDialog(id);
}

private void populateFields()  {



    // Only populate the text boxes and change the calendar date
    // if the row is not null from the database. 
    if (mRowId != -1L) {
        Cursor reminder = mDbHelper.fetchReminder(mRowId);
        startManagingCursor(reminder);
        mTitleText.setText(reminder.getString(
                reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_TITLE)));
       category = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_CATEGORY));
       if(category.equals("School"))
           mSchoolRadio.setChecked(true);
       else if(category.equals("Family"))
           mFamilyRadio.setChecked(true);
       else
           mOtherRadio.setChecked(true);



        // Get the date from the database and format it for our use. 
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
        Date date = null;
        try {
            String dateString = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_DATE_TIME)); 
            date = dateTimeFormat.parse(dateString);
            mCalendar.setTime(date); 
        } catch (ParseException e) {
            Log.e("ReminderEditActivity", e.getMessage(), e); 
        } 
    } else {
        // This is a new task - add defaults from preferences if set. 
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 
        String defaultTitleKey = getString(R.string.pref_task_title_key); 
        String defaultTimeKey = getString(R.string.pref_default_time_from_now_key); 

        String defaultTitle = prefs.getString(defaultTitleKey, null);
        String defaultTime = prefs.getString(defaultTimeKey, null); 

        if(defaultTitle != null)
            mTitleText.setText(defaultTitle); 

        if(defaultTime != null)
            mCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime));

    }

    updateDateButtonText(); 
    updateTimeButtonText(); 

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if(mRowId == -1L)
        mRowId = -1L;
    outState.putLong(RemindersDbAdapter.KEY_ROWID, mRowId);
}

/*
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID) 
                : -1L;
}
*/

private void saveState() {
    String title = mTitleText.getText().toString();
    //String body = mBodyText.getText().toString();

    SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT); 
    String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());

    if (mRowId == -1L) {

        long id = mDbHelper.createReminder(title, priority, category, reminderDateTime);
        if (id > 0) {
            mRowId = id;
        }
    } else {
       mDbHelper.updateReminder(mRowId, title, priority, category, reminderDateTime);
    }

    new ReminderManager(this).setReminder(mRowId, mCalendar); 
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
}

这是对导致问题的新CategoryListActivity活动的调用(与上面的代码在同一个类中):

mManageCategories.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(mContext, CategoryListActivity.class);
            startActivity(i);
            //populateFields();
        }
    });

我遗漏了许多不那么相关的代码。无论如何,就像我上面说的那样......主要的问题是,一旦我开始这个新的CategoryListActivity活动,数据库和所有任务就会被消灭。奇怪的是,即使我重新启动模拟器,只要我不启动CategoryListActivity,任务就不会被擦除。如果有人知道发生了什么,请帮助。

1 个答案:

答案 0 :(得分:0)

安德鲁检查这两个链接,它将向您解释有关数据库集成的所有信息。 http://www.devx.com/wireless/Article/40842/1954
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/