Java – Android runs the functions in the class in a new thread

Android runs the functions in the class in a new thread… here is a solution to the problem.

Android runs the functions in the class in a new thread

I have this code :

MyClass tmp = new MyClass();
tmp.setParam1(1);
.tmp. SetParam2("Test");
tmp.setParam3("Test");
...

And then I have

tmp.heavyCalc();

In this heavy calculation operation, I have to update the progress bar in the UI and show the user that it is processing the progress bar update and some text to display.
Now it doesn’t work because I’m not using threads, the app gets stuck and hangs, then suddenly returns a progress bar to 100% and all the text pops up together.

So I decided to let my function run as a new thread.
In my class definition, I added implements Runnable
So

public class MyClass implements Runnable{

Then I call that heavyCalc() function the new Run() function I created:

@Override
public void Run()
{
heavyCalc();
}

Now I do this:

Thread thread = new Thread(tmp);
tmp.run();

It works, but the UI still doesn’t change anything, the app gets stuck, and then the progress bar suddenly 100% and the app returns.
What am I missing?

Solution

Your answer:
As other answers suggest, you should use thread.start() instead of tmp.run().

The following description is not directly related to your problem, but it can help you write better code and protect you from errors you will encounter in the future.

But to write better code, my advice is to use handlers.
By using handlers, you can perform your actions in the main thread.

For example: To update the value of a textView from a class that you created for another purpose, you must publish this action (Update textView) to the main thread because your custom thread does not have permission to manipulate the View.

Use handlers in your project:

1. You should create an instance from the Handler class in the main thread:

public static Handler handler = new Handler();

2. Start with the second thread and use the handler like this:

YourMainThreadClass.handler.post(new Runnable() {
    @Override
    public void run() {
         Do Whatever
    }
});

exception: You do not have to use a handler for progressBar, but you should use a handler to handle other Views in the same problem. The ProgressBar is just an exception, but I recommend that you use a handler in this case as well.

Related Problems and Solutions