SQLlite

时间:2015-04-22 17:17:21

标签: android database sqlite

我是Android开发的新手,我对此问题非常困惑。我有一个活动,它从用户那里获得一些输入并将它们插入到SQLLite数据库中。这是我的代码,我将数据插入表中。

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.saveBtn:

        MainCalander.DB =  this.openOrCreateDatabase(MainCalander.dbName, MODE_PRIVATE, null);
        System.out.println("DB Opened!!");

        //Set duplicate flag back to normal
        duplicateFlag=false;

        //Retrieve the text from Edit Text boxes
        String t1 = title.getText().toString();
        String t2 = desc.getText().toString();

        //Make the date string
        String dateString = MainCalander.selectedYear + '-' + MainCalander.selectedMonth + '-' + MainCalander.selectedDay;
        System.out.println(dateString);
        //Time String
        String timeString = time.getText().toString();

        Cursor c1 = MainCalander.DB.rawQuery("SELECT * FROM " + MainCalander.tableName, null);

        if (c1 != null) {
            System.out.println("not null");
            if (c1.moveToFirst()){
                System.out.println("moved to first");
                do {
                    System.out.println("Doing");
                    String tempTitle = c1.getString(c1.getColumnIndex("EVENT"));
                    String tempDate = c1.getString(c1.getColumnIndex("DATE"));

                    System.out.println(dateString + " = " + tempDate);

                    //Check for duplicate titles
                    if (t1.equals(tempTitle) && dateString.equals(tempDate)) {
                        System.out.println(dateString + " = " + tempDate);
                        Toast.makeText(getApplicationContext(), "Event name already exist!", Toast.LENGTH_LONG).show();
                        duplicateFlag=true;
                        break;
                    }
                } while (c1.moveToNext());

            }
        }

        //Insert to the DB
        if(!duplicateFlag){

            MainCalander.DB.beginTransaction();
            try {                   
                MainCalander.DB.execSQL("INSERT INTO "+ MainCalander.tableName + " VALUES ('"+ t1 + "','" + t2 + "','" + dateString + "','" + timeString + "');");
                MainCalander.DB.setTransactionSuccessful();     

            } catch (SQLiteException e) {
                e.printStackTrace();
                MainCalander.DB.endTransaction();
            } finally {
                MainCalander.DB.endTransaction();
            }

            System.out.println("One row inserted Successfully!");
            Toast.makeText(getApplicationContext(), "Event Saved!", Toast.LENGTH_LONG).show();
        }

        MainCalander.DB.close();
        this.finish();

        break;

    default:
        break;
    }

}

现在,上面的代码工作正常(起初我不知道beginTransaction(),setTransactionSuccessful()& endTransaction()。我添加它们试图解决我的问题 。插入后我甚至做了一些数据计算没有任何问题。

但是有一次我尝试在数据库插入后立即转移到另一个活动并且没有问题。没有错误,没有例外,没有。但是那时我意识到所有插入的数据都已从数据库中清除干净。我对此非常困惑。

起初我认为当我们使用execSQL()方法发出SQL语句时,数据库提交会自动完成。我在网上搜索,我没有发现任何提交;我们在Oracle中的关键字。但是我在beginTransaction(),setTransactionSuccessful()&上找到了一些stackoverflow线程。 endTransaction()暗示他们将事务提交到数据库。所以我也试过这个,但问题仍然存在。

在尝试将数据插入成功插入数据库之后,我尝试终止应用程序并重新启动以检查应用程序生命周期被销毁时是否存在数据丢失。它确实丢失了数据。我不知道这里发生了什么。感谢是否有人可以帮助我。

这是我创建表格的Main类,

public class MainCalander extends Activity implements View.OnClickListener{

final Context context = this;
public static CalendarView calendar;

public static SQLiteDatabase DB;
public static final String dbName = "AppointmentMan";
public static final String tableName = "Events";

//Calendar
public static String selectedYear;
public static String selectedMonth;
public static String selectedDay;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_calander);

    View createBtn = findViewById(R.id.createBtn);
    createBtn.setOnClickListener(this);

    View deleteBtn = findViewById(R.id.deleteBtn);
    deleteBtn.setOnClickListener(this);

    View editBtn = findViewById(R.id.editBtn);
    editBtn.setOnClickListener(this);

    View moveBtn = findViewById(R.id.moveBtn);
    moveBtn.setOnClickListener(this);

    initializeCalendar();

    try {
        //Instantiate DB object
        DB =  this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);

        //Creates table main events table
        DB.execSQL("CREATE TABLE IF NOT EXISTS " + tableName +" (EVENT VARCHAR NOT NULL,"
                + "DESCRIPTION TEXT NOT NULL,"
                + "DATE DATE NOT NULL,"
                + "TIME TEXT);");

    } catch (SQLiteException se ) {
        Toast.makeText(getApplicationContext(), "Couldn't create or open the database", Toast.LENGTH_LONG).show();
    } finally {
        if (DB != null) {
            DB.execSQL("DELETE FROM " + tableName);
            DB.close();
        }
    }
}



public void initializeCalendar() {
    calendar = (CalendarView) findViewById(R.id.calenderView);

    calendar.setShowWeekNumber(false);

    calendar.setOnDateChangeListener(new OnDateChangeListener() {
        @Override
        public void onSelectedDayChange(CalendarView view, int year, int month, int day) {
                Toast.makeText(getApplicationContext(), day + "/" + month + "/" + year, Toast.LENGTH_SHORT).show();
                selectedDay = Integer.toString(day);
                selectedMonth = Integer.toString(month);
                selectedYear = Integer.toString(year);
            }
        }
    );

}


@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.createBtn:
        Intent intentNewAp = new Intent(this, NewAppointment.class);
        startActivity(intentNewAp);
        break;

    case R.id.deleteBtn:
        Intent intentDel = new Intent(this, DeleteActivity.class);
        startActivity(intentDel);
        break;

    case R.id.editBtn:
        Intent intentEdit = new Intent(this, ShowListViewing.class);
        startActivity(intentEdit);
        break;

    case R.id.moveBtn:
        Intent intentMove = new Intent(this, ShowListMoving.class);
        startActivity(intentMove);
        break;

    default:
        break;
    }

}

}

1 个答案:

答案 0 :(得分:1)

看起来您已经扩展了SQLiteDatabase。你不应该这样做。你应该扩展SQLiteOpenHelper。

有关详细信息,请参阅storage options上的文档。

这是在那里显示的基本示例:

public class DictionaryOpenHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 2;
    private static final String DICTIONARY_TABLE_NAME = "dictionary";
    private static final String DICTIONARY_TABLE_CREATE =
                "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
                KEY_WORD + " TEXT, " +
                KEY_DEFINITION + " TEXT);";

    DictionaryOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DICTIONARY_TABLE_CREATE);
    }
}