mercredi 22 avril 2015

Data wipes out automatically in SQLlite

I'm new to android development and i'm pretty confused about this issue. I have an activity which gets some inputs from the user and inserts them into a SQLLite database. Here's my code where i insert the data into the table.

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

}

Now, above code is working fine (at first i didn't know about beginTransaction(), setTransactionSuccessful() & endTransaction(). I added them trying to resolve the problem i had). I after inserting i even did some calculations with data without any problem.

But then at one point i tried moving to a different activity right after a database insertion and there was no problem. No errors, no exceptions, nothing. But that's when i realized all of the inserted data had been wiped clean from the database. I was pretty confused about this.

At first i was thinking that database commit was automatically done when we issue a SQL statement using execSQL() method. I searched in the internet and i did not find any commit; keyword like we have in Oracle. But i found some stackoverflow threads on beginTransaction(), setTransactionSuccessful() & endTransaction() which implied that they commit the transaction to the database. So i tried this also, but still the issue is there.

I tried killing the application and restating to check whether there is a data loss when the app life cycle is destroyed, after inserting some data into the database which was successfully inserted. And it did lose the data. I don't know what's happening here. Appreciate if anyone could help me on this.

Here's my Main class which creates the tables,

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

}

}

Aucun commentaire:

Enregistrer un commentaire