-1

The buttons are not instantly dis-/reappearing and the code is very slow although i have no heavy operation running (skipping frames). I should use Threads but i do not understand how i should split my code in threads as i cant use normal thread to change the UI. For that there is the UIthread. But then i have to put the whole code into the UIthread as i have nothing else in my class and the same error would happen. Is Thread.sleep() even used on UIthread?

How the user experience is: Start button pressed. 20 sec pause. textview displays number and the start button disappears and the stop button appears.

How it should be: First should the start button disappear after pressing and the stop button appearing. After that the textview should display x and update it so that it grows 0.1 each iteration until it reaches a random int or the user presses the stop button which change gamefalse[] to true which in turn stopps the while loop.

I redid my code but it still is lagging

Skipped 5885 frames!

 final boolean[] gamefalse = {false};
        int einsatz = 50;
        final float[] x = {1};
        start.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                start.setVisibility(View.GONE);
                stop.setVisibility(View.VISIBLE);
                SecureRandom random = new SecureRandom();
                int number = random.nextInt(101);
                int j = 1;

                while (j < number && !gamefalse[0]) {
                    j++;
                    x[0] += 0.1;
                    textView.setText(String.valueOf(x[0]));
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("iteration");

                }
            }
        });


        float finalX = x[0];
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gamefalse[0] = true;
                stop.setVisibility(View.GONE);
                start.setVisibility(View.VISIBLE);
                int gewinn = (int) finalX * einsatz;


                mDatabaseReference.child("user").child(String.valueOf(encodeUserEmail(email))).child("stand").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot snapshot) {
                        Long b = snapshot.getValue(Long.class);
                        mDatabaseReference.child("user").child(String.valueOf(encodeUserEmail(email))).child("stand").setValue(b + gewinn);
                        mDatabaseReference.child("user").child(String.valueOf(encodeUserEmail(email))).child("stand").addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot snapshot) {
                                Long b = snapshot.getValue(Long.class);
                                String c = b + " ";
                                System.out.println(c);
                            }

                            @Override
                            public void onCancelled(DatabaseError error) {
                            }
                        });
                    }

                    @Override
                    public void onCancelled(DatabaseError error) {
                    }
                });
            }
        });
    }

Jonasoos
  • 1
  • 4

1 Answers1

2

This code is bad in a few ways, and shows you don't fully understand what you're doing. From your wording it seems like maybe you think the UI thread is something there can be multiple of (there can't there is only 1 and it's the same as the main thread). I'll show you a few issues:

            Crash.this.runOnUiThread(new Runnable() {

This is on an onClick listener. That's already only running on the UI thread. So all this does is delay the execution. It isn't necessary or helpful.

                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException ex) {
                            Thread.currentThread().interrupt();
                        }

This is done on the UI thread. NEVER SLEEP ON THE UI THREAD. If you need a delay on the UI thread, you post a message to the handler, or use a timer of some sort. Never sleep. Also the catch here is pointless- the current thread is already interrupted. What's the point in interrupting it again?

Unrelated to performance- you're also setting the onClick of the stop button in the onClick of the start button. That's pointless. Set it globally, and prevent the clicking of the stop button by either visibility (setting it gone or invisible) or by enablement (disabling it). You can also improve the readability and maintainability of your code by breaking up those long onClicks into named functions that do particular things.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • I removed the UIThread altogether and used 'Thread.sleep()' like shown here: https://stackoverflow.com/questions/24104313/how-do-i-make-a-delay-in-java. Now i still have the issue with the frame skipping. Should i just put all the code into a "normal" thread? I have trouble understanding what exactly causes frame skipping in my code – Jonasoos Jul 31 '23 at 19:38
  • I edited my question and redid my code – Jonasoos Jul 31 '23 at 19:48
  • Dude, you still have a massive sleep 1000 in there on the main thread (all onClickListeners run on the main thread). Unless you know what you're doing with it, forget sleep exists. Don't use it. – Gabe Sechan Aug 01 '23 at 04:18
  • If you want to update the UI every second, use a CountDownTimer or post a message to a handler to do the work of the next update. Do not try to sleep waiting for that second to finish. That is 100% the cause of your skipped frames, and it means your UI won't update until the last frame. – Gabe Sechan Aug 01 '23 at 04:20
  • ahh my bad. Thank you – Jonasoos Aug 01 '23 at 09:20