0

Now I have successfully retrieved as well as inserting data into a database, but when I am inserting data to the database second time it will throw an error.Because it will triggered create table query every time when the application arrives on main page. But I don't know how to rectify this problem.

Below is my code:-

public class Calender {

    private Form current;
    private Resources theme;
    Form calendar, saveEvent, DataEvent;
    Label dateLabel;
    TextField eventArea, descriptionArea;
    Customised cal;
    Database db = null;
    Cursor cur = null;

    public void init(Object context) {
        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature, uncomment if you have a pro subscription
        // Log.bindCrashProtection(true);
        String path = Display.getInstance().getDatabasePath("Events.db");
        FileSystemStorage fs = FileSystemStorage.getInstance();
        if (!fs.exists(path)) {
            try (InputStream is = Display.getInstance().getResourceAsStream(getClass(), "/Events.db");
                    OutputStream os = fs.openOutputStream(path)) {
                Util.copy(is, os);
            } catch (IOException err) {
                Log.e(err);
            }
        }
        try {
            db = Display.getInstance().openOrCreate("Events.db");
            db.execute("CREATE TABLE Personsse (Date date NOT NULL,Event varchar(255) NOT NULL, Description varchar(255) NOT NULL)");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        if (current != null) {
            current.show();
            return;
        }
        try {
            SplashScreen spl = new SplashScreen();
            spl.show();

            new java.util.Timer().schedule(
                    new java.util.TimerTask() {
                @Override
                public void run() {
                    calendar.show();
                }
            }, 4000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        DataEvent = new Form("Data Explorer", new BorderLayout());
        Command back1 = new Command("Back") {
            public void actionPerformed(ActionEvent ev) {
                calendar.show();
            }
        };
        DataEvent.setBackCommand(back1);
        calendar = new Form("Events", new BoxLayout(BoxLayout.Y_AXIS));
        cal = new Customised();

        calendar.add(cal);

        Label date = new Label("Event Date:- ");
        dateLabel = new Label();
        Label event = new Label("Event:- ");
        eventArea = new TextField();
        Label description = new Label("Event Description:- ");
        descriptionArea = new TextField();

        Container container = TableLayout.encloseIn(2, date, dateLabel, event, eventArea, description, descriptionArea);
        container.setUIID("container");
        calendar.add(container);
        cal.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy");
                    String selectedDate = new Date(cal.getSelectedDay()).toString();
                    Date date1 = sdf.parse(selectedDate);
                    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                    dateLabel.setText(df.format(date1));
                } catch (ParseException ex) {
                    ex.printStackTrace();
                }

                cal.createDay();
            }

        });

        Toolbar tb = new Toolbar();
        calendar.setToolBar(tb);

        tb.addCommandToRightBar("", FontImage.createMaterial(FontImage.MATERIAL_SAVE, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
            saveEvent.show();
        });
        tb.addCommandToLeftBar("", FontImage.createMaterial(FontImage.MATERIAL_EVENT, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
            DataEvent.show();
        });

        Button add = new Button("Add Event");
        Button clear = new Button("Clear Event");
        calendar.add(add);
        calendar.add(clear);

        //Saved Events Form Starts  ====================================================================================
        saveEvent = new Form("Saved Event", new BoxLayout(BoxLayout.Y_AXIS));
        Command back = new Command("Back") {
            public void actionPerformed(ActionEvent ev) {
                calendar.show();
            }
        };
        saveEvent.setBackCommand(back);
        Toolbar tb1 = new Toolbar();
        saveEvent.setToolBar(tb1);
        tb1.addCommandToLeftBar("", FontImage.createMaterial(FontImage.MATERIAL_ARROW_BACK, UIManager.getInstance().getComponentStyle("TitleCommand")), back);
        //Save Events Form Ends =======================================================================================

        add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                Log.p(dateLabel.getText().toString());
                //if((dateLabel.getText() == null) && (eventArea.getText() == null) && (descriptionArea.getText() == null)){
                if ((dateLabel.getText() == "") || (eventArea.getText() == "") || (descriptionArea.getText() == "")) {
                    Dialog.show("Required field", "Please fill all the fields", "OK", "");
                } //}
                else {

                    Label date1 = new Label("Event Date:- ");
                    Label dateLabel1 = new Label(dateLabel.getText());
                    Label event1 = new Label("Event:- ");
                    Label eventArea1 = new Label(eventArea.getText());
                    Label description1 = new Label("Event Description:- ");
                    Label descriptionArea1 = new Label(descriptionArea.getText());

                    Container container1 = TableLayout.encloseIn(2, date1, dateLabel1, event1, eventArea1, description1, descriptionArea1);
                    container1.setUIID("container");

                    saveEvent.add(container1);

                    ToastBar.showMessage("Event successfull saved", FontImage.MATERIAL_SAVE, 4000);

                    //Databse Working
                    try {

                        String[] values = new String[]{dateLabel.getText(), eventArea.getText(), descriptionArea.getText()};

                        db.execute("INSERT INTO Personsse (Date,Event,Description) VALUES(?,?,?)", values);

                        Button database = new Button("Database");
                        calendar.add(database);
                        database.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent evt) {
                                try {
                                    cur = db.executeQuery("SELECT * FROM Personsse");
                                    int columns = cur.getColumnCount();
                                    DataEvent.removeAll();

                                    if (columns > 0) {
                                        boolean next = cur.next();
                                        if (next) {
                                            ArrayList<String[]> data = new ArrayList<>();
                                            String[] columnNames = new String[columns];
                                            for (int iter = 0; iter < columns; iter++) {
                                                columnNames[iter] = cur.getColumnName(iter);
                                            }
                                            while (next) {
                                                Row currentRow = cur.getRow();
                                                String[] currentRowArray = new String[columns];
                                                for (int iter = 0; iter < columns; iter++) {
                                                    currentRowArray[iter] = currentRow.getString(iter);
                                                }
                                                data.add(currentRowArray);
                                                next = cur.next();
                                            }
                                            Object[][] arr = new Object[data.size()][];
                                            data.toArray(arr);
                                            DataEvent.add(BorderLayout.CENTER, new Table(new DefaultTableModel(columnNames, arr)));
                                        } else {
                                            DataEvent.add(BorderLayout.CENTER, "Query returned no results");
                                        }
                                    } else {
                                        DataEvent.add(BorderLayout.CENTER, "Query returned no results");
                                    }
                                    DataEvent.revalidate();
                                    Util.cleanup(db);
                                    Util.cleanup(cur);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                DataEvent.show();
                            }
                        });

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        });

}

And the error is given below:-

Getting following error when application starts:-

java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (table Personsse already exists)
    at org.sqlite.DB.newSQLException(DB.java:886)
    at org.sqlite.DB.newSQLException(DB.java:897)
    at org.sqlite.DB.throwex(DB.java:864)
    at org.sqlite.NativeDB.prepare(Native Method)
    at org.sqlite.DB.prepare(DB.java:207)
    at org.sqlite.PrepStmt.<init>(PrepStmt.java:50)
    at org.sqlite.SQLiteConnection.prepareStatement(SQLiteConnection.java:616)
    at org.sqlite.SQLiteConnection.prepareStatement(SQLiteConnection.java:606)
    at org.sqlite.SQLiteConnection.prepareStatement(SQLiteConnection.java:578)
    at com.codename1.impl.javase.SEDatabase.execute(SEDatabase.java:92)
    at com.pivotal.calendar.Calender.init(Calender.java:76)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.codename1.impl.javase.Executor$1$1.run(Executor.java:117)
    at com.codename1.ui.Display.processSerialCalls(Display.java:1154)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:971)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.io.IOException: [SQLITE_ERROR] SQL error or missing database (table Personsse already exists)
    at com.codename1.impl.javase.SEDatabase.execute(SEDatabase.java:96)
    at com.pivotal.calendar.Calender.init(Calender.java:76)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.codename1.impl.javase.Executor$1$1.run(Executor.java:117)
    at com.codename1.ui.Display.processSerialCalls(Display.java:1154)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:971)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
[EDT] 0:0:0,1 - Codename One revisions: 16f9f308f6ef10ac0e25a8afbd37b8066f5a391d
2348

And when adding second record to the database following error thrown by application:-

[EDT] 0:0:0,46 - 26/04/2017
**** WARNING! DB Cursor was released by the GC without being closed first! This might cause crashes on iOS *****
[EDT] 0:0:15,345 - 26/04/2017
java.lang.NullPointerException
[EDT] 0:0:16,278 - Exception: java.lang.NullPointerException - null
    at com.codename1.impl.javase.SEDatabase.execute(SEDatabase.java:103)
    at com.pivotal.calendar.Calender$5.actionPerformed(Calender.java:212)
    at com.codename1.ui.util.EventDispatcher.fireActionEvent(EventDispatcher.java:349)
    at com.codename1.ui.Button.fireActionEvent(Button.java:435)
    at com.codename1.ui.Button.released(Button.java:467)
    at com.codename1.ui.Button.pointerReleased(Button.java:566)
    at com.codename1.ui.Form.pointerReleased(Form.java:2642)
    at com.codename1.ui.Form.pointerReleased(Form.java:2578)
    at com.codename1.ui.Component.pointerReleased(Component.java:3266)
    at com.codename1.ui.Display.handleEvent(Display.java:2025)
    at com.codename1.ui.Display.edtLoopImpl(Display.java:1070)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:999)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

And I am also having some query related to Codename one SQLite like:-How to print table data to the Label in ascending order, how to print one row at a time in SpanLabel.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Gaurav Takte
  • 607
  • 5
  • 22

1 Answers1

0

Your table already exist so for that you get this error, to avoid this case you can use IF NOT EXISTS :

CREATE TABLE IF NOT EXISTS Personsse ...

So, this happen, when you execute your program more then one time, so the first time it will create the table, when you execute it again, the table already exit, so boom, this error happen, table already exist.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • I will fix that problem with the help of your solution so thank you, But when I am adding a second record to the database, it will throw an error :- EDT] 0:0:23,685 - Exception: java.lang.NullPointerException - null – Gaurav Takte Apr 06 '17 at 09:16
  • mmm good, this mean that something is not initialized or null, can you show me exactly were this happen in your code @GRV_Droid – Youcef LAIDANI Apr 06 '17 at 09:29
  • It will throw an error when an Insert query calls second time.When the application is on main page for first time then we can add multiple records into the database but when application navigate to another page where application display table and again navigate to main page for adding records it will throw an error saying JavaNullPointerException. @YCF_L 24 – Gaurav Takte Apr 06 '17 at 09:54
  • @GRV_Droid is a famous error you can take a look here, http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it try to debug your program step by step, and check which line it throw this error, ok and tell me so maybe i can help you – Youcef LAIDANI Apr 06 '17 at 09:57