App crashes when I try to insert data into database

YGouddi

So, I'm trying to build an app where the user creates an event and the event gets stored into a data base. But every time I click the save button the app crashes. I've tried many things to try and decipher the problem but I'm failing constantly. Here's the code for the SQLiteOpenHelper

  public class AccessDatabase extends SQLiteOpenHelper {


// Declaring the variables
private static final String DB_NAME = "unilog";
private static final int DB_VERSION = 2;
private static final String TB_NOTES = "Notes";
private static final String NOTE_NAME = "name";
private static final String NOTE_DATE = "date";
private static final String NOTE_LOCATION = "location";
private static final String NOTE_DESCRIPTION = "description";
private static final String NOTE_STATUS = "status";
private static final String NOTE_CREATION = "createdby";


private static final String CREATE_NOTES_TABLE = "CREATE TABLE " + TB_NOTES + " ("
        + " num INTEGER PRIMARY KEY AUTOINCREMENT, " + NOTE_NAME + " TEXT,"
        + NOTE_DATE + " TEXT," + NOTE_LOCATION + " TEXT," + NOTE_DESCRIPTION + " TEXT," + NOTE_CREATION + " TEXT," + NOTE_STATUS + " INTEGER)";

private static final String CREATE_USER_TABLE = "CREATE TABLE USERS ("
        + "id INTEGER PRIMARY KEY AUTOINCREMENT, "
        + "NAME TEXT NOT NULL, "
        + "PASSWORD TEXT NOT NULL, "
        + "EMAIL TEXT NOT NULL) ";
//Done Declaring the variables

AccessDatabase(Context context) {

    super(context, DB_NAME, null, DB_VERSION);
}

private static void insertUser(SQLiteDatabase db, String name, String password, String email) {
    ContentValues user = new ContentValues();
    user.put("NAME", name);
    user.put("PASSWORD", password);
    user.put("EMAIL", email);
    db.insert("USERS", null, user);


}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_NOTES_TABLE);
    db.execSQL(CREATE_USER_TABLE);

    insertUser(db, "Yosr", "123456789", "[email protected]");
    insertUser(db, "Yesmine", "nadalind", "[email protected]");

    ContentValues io = new ContentValues();
    io.put(NOTE_NAME, "Yosr");
    io.put(NOTE_DATE, "121212");
    io.put(NOTE_LOCATION, "Unilog");
    io.put(NOTE_DESCRIPTION, "Android");
    io.put(NOTE_CREATION, "By me");
    io.put(NOTE_STATUS, 0);
    db.insert(TB_NOTES, null, io);


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TB_NOTES);
    db.execSQL("DROP TABLE IF EXISTS USERS");

    onCreate(db);
}


//TOdo add note
public void addNote(Notes note) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(NOTE_NAME, note.getName());
    values.put(NOTE_DATE, note.getEventDate());
    values.put(NOTE_LOCATION, note.getEventLocation());
    values.put(NOTE_DESCRIPTION, note.getEventDescription());
    values.put(NOTE_CREATION, note.getCreatedBy());
    values.put(NOTE_STATUS, note.getStatus());
    //todo insert row
    db.insert(TB_NOTES, null, values);
    db.close();

}
//TODO : GETTING A SINGLE NOTE

public Notes getNote(String name, String date) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TB_NOTES, new String[]{NOTE_NAME, NOTE_DATE, NOTE_LOCATION, NOTE_DESCRIPTION, NOTE_CREATION, NOTE_STATUS},
            NOTE_NAME + " =? AND " + NOTE_DATE + " =?", new String[]{name, date}, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();
    Notes note = new Notes(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getInt(5));
    cursor.close();
    return note;
}


//TODO : GETTING ALL NOTES

public List<Notes> getallnotes() {
    List<Notes> notesList = new ArrayList<Notes>();
    String SelectQuery = "SELECT * FROM " + TB_NOTES;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(SelectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            Notes note = new Notes();
            note.setName(cursor.getString(1));
            note.setEventDate(cursor.getString(2));
            note.setDescription(cursor.getString(4));
            note.setEventLocation(cursor.getString(3));
            note.setCreatedBy(cursor.getString(5));
            notesList.add(note);
        } while (cursor.moveToNext());
    }
    cursor.close();
    return notesList;
}

//TODO delete note

public void DeleteNote(Notes notes)

{
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TB_NOTES, "(" + NOTE_NAME + " = ? AND " + NOTE_DATE + "= ?)",
            new String[]{notes.getName(), notes.getEventDate()});
    db.close();
}

//Get number of notes
public int getNotesCount() {
    String countQuery = "SELECT  * FROM " + TB_NOTES;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("select * from Notes", null);

    cursor.close();

    // return count
    return cursor.getCount();
}

} And the here's the code for the note.java

 public class Notes {
 private int status;
 private String Name, EventDate,EventLocation,EventDescription ,    createdBy;
public Notes()
{}

public Notes (String name, int status)
{
    this.Name = name;
    this.status = status;

}
public Notes(String name,String EventDate, String EventLocation, String Description, String createdby, int status) {

    this.createdBy = createdby;
    this.EventDescription= Description;
    this.EventLocation= EventLocation;
    this.EventDate=EventDate;
    this.Name = name;
    this.status = status;
}

// setters

//TODO NAME
public void setName(String name) {
    this.Name = name;
}
//TODO DESCRIPTION
public void setDescription (String description) {
    this.EventDescription = description;
}

//TODO LOCATION
public void setEventLocation (String location)
{
    this.EventLocation = location;
}

//TODO STATUS
public void setStatus(int status) {
    this.status = status;
}
//TODO EVENTDATE
public void setEventDate(String date)
{this.EventDate = date;}

//TODO CREATEDBY
public void setCreatedBy(String createdby){
    this.createdBy = createdby;
}

// getters

//TODO NAME
public String getName() {
    return this.Name;
}
//TODO STATUS
public int getStatus() {
    return this.status;
}
//TODO CREATEDBY

public String getCreatedBy() {
    return createdBy;
}

//TODO EVENTDATE
public java.lang.String getEventDate() {
    return EventDate;
}
//TODO EVENTLOCATION
public java.lang.String getEventLocation() {
    return EventLocation;
}

public String getEventDescription() {
    return EventDescription;
}

}

and finally the createnote.java

  public class CreateNote extends Activity {

//TODO Declaring Variables
 String name;

TextView enddate, startdate, datetext;
Button display, SaveEvent, CancelEvent;
ImageButton StartDate, EndDate, datebutton;
EditText eventlocation, eventdescription, newnote;
Calendar mycalendar1 = Calendar.getInstance();
Calendar mycalendar2 = Calendar.getInstance();
Calendar mytime = Calendar.getInstance();
AccessDatabase db = new AccessDatabase(this);
//TODO  Done declaring variables

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



    //TODO:EditText : location & description
    eventlocation = (EditText) findViewById(R.id.location);
    eventdescription = (EditText) findViewById(R.id.description);
    String location = eventlocation.getText().toString();
    String description = eventdescription.getText().toString();
    eventlocation.setText(location, TextView.BufferType.EDITABLE);
    eventdescription.setText(description, TextView.BufferType.EDITABLE);
    newnote  = (EditText)findViewById(R.id.newnote);
    name = newnote.getText().toString();

    //TODO save and cancel buttons

     SaveEvent = (Button)findViewById(R.id.savenote);
     CancelEvent = (Button)findViewById(R.id.cancelnote);
    SaveEvent.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
         //   String msg = db.getNote("Yosr", "121212").getCreatedBy();

                  int non  = db.getNotesCount();
                      StringBuilder stro = new StringBuilder();
                  stro.append(non);
                    String nin = stro.toString();


                Toast.makeText(getApplicationContext(), nin,  Toast.LENGTH_LONG).show();

            }
        });




            //TODO :Buttons : start & end & date


    datebutton = (ImageButton) findViewById(R.id.datebutton);
    StartDate = (ImageButton) findViewById(R.id.dpresultday);
    EndDate = (ImageButton) findViewById(R.id.dpendtime);


    //TODO TextView : startdate and enddate
    datetext = (TextView) findViewById(R.id.date);
    startdate = (TextView) findViewById(R.id.startdate);
    enddate = (TextView) findViewById(R.id.enddate);


    //TODO Calendar and datepicker stuff for start

    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int day) {
            mytime.set(Calendar.YEAR, year);
            mytime.set(Calendar.MONTH, month);
            mytime.set(Calendar.DAY_OF_MONTH, day);
            updatelabel2();
        }
    };

    //TODO Startdate button listener
    StartDate.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View view) {
            int hour = mycalendar1.get(Calendar.HOUR_OF_DAY);
            int minute = mycalendar2.get(Calendar.MINUTE);
            TimePickerDialog mtimepicker;
            mtimepicker = new TimePickerDialog(CreateNote.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedhour, int selectedminute) {

                  startdate.setText(selectedhour + ":" + selectedminute);

                }
            }, hour, minute, true);
            mtimepicker.setTitle("selecttime");
            mtimepicker.show();
        }

    });


  //TODO TimePicker listener for startButton

    datebutton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new DatePickerDialog(CreateNote.this, date, mycalendar1
                    .get(Calendar.YEAR), mytime.get(Calendar.MONTH),
                    mytime.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

    //TODO Enddate button listener
    EndDate.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View view) {
            int hour = mycalendar2.get(Calendar.HOUR_OF_DAY);
            int minute = mycalendar2.get(Calendar.MINUTE);
            TimePickerDialog mtimepicker;
            mtimepicker = new TimePickerDialog(CreateNote.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedhour, int selectedminute) {
                    enddate.setText(selectedhour + ":" + selectedminute);
                }
            }, hour, minute, true);
            mtimepicker.setTitle("selecttime");
            mtimepicker.show();

        }
    });




}




private void updatelabel2(){

    String myFormat = "MM/dd/yy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

    datetext.setText(sdf.format(mytime.getTime()));

} }

Divers

You can't use closed cursor:

public int getNotesCount() { 
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("select * from Notes", null);
    int count = cursor.getCount()
    cursor.close();

    return count;
} 

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

When I try to set a clickListener, app crashes

From Dev

App crashes when i try to run this page

From Dev

App crashes when i try to set onClickListener

From Dev

When I try to set a clickListener, app crashes

From Dev

App crashes when i try to run this page

From Dev

Android app crashes when i try to reLogin

From Dev

error when try to insert data into database

From Dev

My app crashes when I try to add Image Button to it

From Dev

MapFragment make app crashes at runtime when I try to setMapType

From Dev

my app crashes when I try to download an image

From Dev

When I Try to Change the Color of SnackBar TextView App Crashes

From Dev

"org.hibernate.PersistentObjectException: detached entity passed to persist" when I try insert data in the database

From Dev

Facing exception "org.hibernate.PersistentObjectException: detached entity passed to persist" when I try insert data in the database

From Dev

I have trouble when I try to insert datas into database in MySQL

From Dev

My SQLite database is not created when i open the app and it crashes

From Dev

Data inserts to database and then app crashes

From Dev

error occured when I try to insert data into sqlte

From Dev

App crashes when I delete from table view and core data

From Dev

Roslyn crashes when I try to run a script

From Dev

When I try to add more than 4 images to the layout, the app crashes

From Dev

App crashes when I try to launch in Android Kitkat 4.4.4 but works fine in Android 5 & 6 versions

From Dev

Database - Query failed when we try to insert

From Dev

App crashes when trying to save to SQLite database

From Dev

App crashes when changes are made in Realm database

From Dev

When I insert data, it shows '1' in database - php,sql

From Dev

Multiple instances of IEntityChangeTracker error get when try to insert data into database in c#

From Dev

It says Incorrect syntax near ',' when I try to insert an item into my database?

From Java

SSMS crashes when try to modify database diagram (v18.2)

From Dev

Unfortunately app has stopped ! when i try to insert some codings into the mainActivity class

Related Related

  1. 1

    When I try to set a clickListener, app crashes

  2. 2

    App crashes when i try to run this page

  3. 3

    App crashes when i try to set onClickListener

  4. 4

    When I try to set a clickListener, app crashes

  5. 5

    App crashes when i try to run this page

  6. 6

    Android app crashes when i try to reLogin

  7. 7

    error when try to insert data into database

  8. 8

    My app crashes when I try to add Image Button to it

  9. 9

    MapFragment make app crashes at runtime when I try to setMapType

  10. 10

    my app crashes when I try to download an image

  11. 11

    When I Try to Change the Color of SnackBar TextView App Crashes

  12. 12

    "org.hibernate.PersistentObjectException: detached entity passed to persist" when I try insert data in the database

  13. 13

    Facing exception "org.hibernate.PersistentObjectException: detached entity passed to persist" when I try insert data in the database

  14. 14

    I have trouble when I try to insert datas into database in MySQL

  15. 15

    My SQLite database is not created when i open the app and it crashes

  16. 16

    Data inserts to database and then app crashes

  17. 17

    error occured when I try to insert data into sqlte

  18. 18

    App crashes when I delete from table view and core data

  19. 19

    Roslyn crashes when I try to run a script

  20. 20

    When I try to add more than 4 images to the layout, the app crashes

  21. 21

    App crashes when I try to launch in Android Kitkat 4.4.4 but works fine in Android 5 & 6 versions

  22. 22

    Database - Query failed when we try to insert

  23. 23

    App crashes when trying to save to SQLite database

  24. 24

    App crashes when changes are made in Realm database

  25. 25

    When I insert data, it shows '1' in database - php,sql

  26. 26

    Multiple instances of IEntityChangeTracker error get when try to insert data into database in c#

  27. 27

    It says Incorrect syntax near ',' when I try to insert an item into my database?

  28. 28

    SSMS crashes when try to modify database diagram (v18.2)

  29. 29

    Unfortunately app has stopped ! when i try to insert some codings into the mainActivity class

HotTag

Archive