0

Note: I searched google and here for few hours, but didn't get the answer.

I want to show the value what will for loop return. Here is my code:

mProgressBar = findViewById(R.id.progressBar);
        percentText = findViewById(R.id.percent);

        mProgressBar.setMax(100);
        mProgressBar.setProgress(0);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    for (int progress = 0; progress<100; progress++){
                        mProgressBar.setProgress(progress);
                        percentText.setText(progress);
                        sleep(30);
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    Intent intent = new Intent(SplashScreenActivity.this, SignUpLoginActivity.class);
                    startActivity(intent);
                }

App crashing while I'm adding this line percentText.setText(progress);. Without this line, code is working well. What should I do to show the progress value to the TextView?

  • Please post the error message you are getting when the app crashes, along with some additional context (is the code you posted inside your `onCreate` method?) – Tyler V Jul 07 '18 at 14:22
  • https://pastebin.com/LEmEZX3T here I pasted the error. – Md. Sakib Khandaker Jul 07 '18 at 19:11
  • See @Kelvin's answer for how to fix that particular error. However the other points raised here are also valid, and you'll have to address them too (can't update a UI element off the UI thread) – Tyler V Jul 07 '18 at 19:18
  • Also, see this answer for another reference on how to make a UI that updates at some frequency https://stackoverflow.com/questions/51219393/android-app-crashes-with-while-loop/51219468#51219468 – Tyler V Jul 07 '18 at 19:41

7 Answers7

1

Ok, so adding my input to all the issues raised in the various answers, this is a complete working example Activity. The main issues identified were 1) calling setText(int) rather than setText(String) and 2) updating UI elements off the UI thread.

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private final Handler handler = new Handler();
    private TextView percentText;
    private ProgressBar mProgressBar;
    private int progress = 0;
    private final int updateFreqMs = 100; // call update every 100 ms

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // reset the counter every time the activity resumes, whether 
        // you do this depends how you want it to behave
        progress = 0; 
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                updateProgress();
                if( progress < 100 ) {
                    handler.postDelayed(this, updateFreqMs);
                }
                else {
                    // Didn't test this part, but this is where you'd launch
                    // the next activity after the progress is complete
                    Intent intent = new Intent(MainActivity.this, SignUpLoginActivity.class);
                    startActivity(intent);

                    // probably also want to finish this so the user can't
                    // press back and come back here
                    finish();
                }
            }
        }, updateFreqMs);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_your_layout); // Put your layout id here
        percentText = findViewById(R.id.percent);
        mProgressBar = findViewById(R.id.progressBar);

        mProgressBar.setMax(100);
        mProgressBar.setProgress(0);
    }

    private void updateProgress() {
        // this will be called until progress == 100
        ++progress;
        mProgressBar.setProgress(progress);
        percentText.setText(String.valueOf(progress));
    }
}
Tyler V
  • 9,694
  • 3
  • 26
  • 52
0

It doesn't look like you've started your thread...

try

new Thread(new Runnable() {...all your code...})).start()

Reuben Tanner
  • 5,229
  • 3
  • 31
  • 46
0

You should use handler to set progress to textview inside your for loop

// Update the progress bar and display the
                //current value in the text view
                handler.post(new Runnable() {
                    public void run() {
                        progressBar.setProgress(progress);
                        textView.setText(progress);
                    }
                });
prashant17
  • 1,520
  • 3
  • 14
  • 23
0

You have to update the UI on the UI thread, not on other thread. Use code something like this

Handler mainHandler = new Handler(Looper.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {
         percentText.setText(progress);
    } 
};
mainHandler.post(myRunnable);
hjchin
  • 864
  • 2
  • 8
  • 25
0

You should run UI modifying codes in UI Thread.

U can access UI thread inside your thread like this:

new Thread(new Runnable() {
            @Override
            public void run() {
                yourActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       percentText.setText(progress);
                    }
                });
            }
Shynline
  • 1,497
  • 1
  • 13
  • 18
  • too many errors, not understanding where to add this code. :( – Md. Sakib Khandaker Jul 07 '18 at 13:59
  • 1
    I didn't give you complete code. it's just an example for giving you an idea. main point is you should run that line in UI thread and there are several ways. one of them is to somehow get your activity instance and then use runOnUiThread method. I can't give you complete code because you didn't say where are these codes taking placed. – Shynline Jul 07 '18 at 16:24
0

App crashing while I'm adding this line percentText.setText(progress);

Only UI Thread can access Views. You can't access any View from Background Thread. Use Handler to send task to UI Thread.

Handler mHandler = new Handler(Looper.getMainLooper());

 .............................

for (int progress = 0; progress<100; progress++){
   // mProgressBar.setProgress(progress);
   // percentText.setText(progress);
    mHandler.post(new Runnable() {
     @Override
     public void run() {
       // this will run in the main thread
       percentText.setText(progress);
       mProgressBar.setProgress(progress);
     }
     });
    sleep(30);

}
Abu Yousuf
  • 5,729
  • 3
  • 31
  • 50
0

This is because the progress is of integer type. instead of

progressText.setText(progress);

which may result in resources not found exception.

use

progressText.setText(String.valueOf(progress));
  • 1
    Based on the error you posted, this is the current issue. However the other issues raised in other answers are also relevant. You likely have multiple issues to fix. When you say something "doesn't work" please elaborate or we have no way of helping you (e.g. do you get the same error message, or a new one?) – Tyler V Jul 07 '18 at 19:17
  • So your error message is still `ResourceNotFoundException` on the same line (48)? Have you tried something like `progressText.setText("test");`? You should not be getting the same error if you made @Kelvin's change. – Tyler V Jul 07 '18 at 19:34
  • yea thats true @Tyler. which error message are you getting exactly @Sakib? – Kelvin K Makau Jul 07 '18 at 19:39