user2410128
user2410128

Reputation:

Inserting data to database is freezing my app

I have got class with timer. This class is adding new items for my Array of points. That points are moving and from a body of timer im repainting a panel to draw them in new positions. Im connected to database sqlite. when im calling an insert function to add point to the table - apps freeze for 1s.

I want to ask is there any way to not stoping drawing/repainting? i want that operation of inserting will be doing in background.

any ideas?

Ps: i heard about swing worker but idk is it suitable to my sitaution

EDIT:

class Generator{
    ChangeListener listener;
    ArrayList<String> s;
    JPanel p;
    Timer generatorTimer;
    MyDatabase b;


    public Generator(){
    this.s = new ArrayList<String>();
    this.b = new MyDatabase();
      generatorTimer = new Timer(40, new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
              addItem();     
              p.repaint();
      }
    });
    generatorTimer.start();
    }
    private void addItem(){
        String newString = new String("sampleText");
        s.add(newString);
        b.insert(newString);  //inserting new item do database
        listener.stateChanged(new ChangeEvent(this));
    }
    public void setPanel(JPanel p){
        this.p = p;
    }

    public ArrayList<String> getArray(){
        return s;
    }   
    public void addListener(ChangeListener list){
        this.listener = list;
    }
}

Can u give me example how to replace my Timer with a SwingWorker?

Upvotes: 0

Views: 108

Answers (1)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51485

Change your addItem method to something like this:

private void addItem() {
    final String newString = new String("sampleText");
    s.add(newString);
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // inserting new item to database
            b.insert(newString);
        }
    };
    new Thread(runnable).start();
    listener.stateChanged(new ChangeEvent(this));
}

Upvotes: 1

Related Questions