java - 每次我打开新 Activity 时,Android SQLite 数据库似乎都会被清除

标签 java android eclipse sqlite

我已经尝试修复这两个错误有一段时间了,我觉得这与我对打开新 Activity 时发生的情况存在根本性误解有关。基本上该程序是一个任务管理程序。当我添加新任务而不修改类别时,它工作得很好,并且当我添加新任务以显示这些新任务时,数据库更新正常,应用程序的主页更新。

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

这是首页的相关代码 fragment (显示所有任务的 ListView :

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);
}

以下是我的任务编辑 View 的一些代码(调用类别列表 Activity 的代码):

@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 Activity 的调用(与上述代码在同一类中):

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 Activity ,数据库和所有任务都会被清除。奇怪的是,即使我重新启动模拟器,只要我不启动 CategoryListActivity,任务就不会被删除。如果有人知道发生了什么事,请帮忙。

最佳答案

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

关于java - 每次我打开新 Activity 时,Android SQLite 数据库似乎都会被清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7857624/

相关文章:

java - SQLite 数据库中没有存储任何信息

java - 需要合适的数据结构的建议

java - 无法从已编译的 github 库导入类

来自数据库的 Android 填充 Spinner 需要旧条目

javascript - 如何创建eclipse项目来调试网页上的Javascript

java - 为什么 ForkJoinPool::shutdownNow 返回一个空列表?

Android高分辨率图像处理

android - C++ 生成器 : Include JAR files

java - 如何将 "send"变量从应用程序转移到不同的模块?

java - 在 Eclipse/RCP 中定位工具栏