-4

I've created a nested class within my Activity

public class MissionsActivity extends Activity {

class UpdateMissions implements Runnable {

    @Override
    public void run() {
      android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
        [...]
}

   [...]
}

In the thread I have to read a file and update some TextFields in the layout. I've tried implementing the run() method with a while(true) that reads and updates the fields, but the app just crashes when I start that Activity.

UPDATE: I've called the execute() method inside the onCreate() method of the UI Activity. The Task is only working the first time I enter the Activity, if i change and go back it won't do anything.

ayyylmao
  • 71
  • 1
  • 13

2 Answers2

0

Hey a solution could be trying to use Java's Executor Framework. Put the following code in your Activity.

With executors, you can use a cachedThreadPool() singleThreadExecutor() fixedThreadPoolExecutor(int numOfThreads) etc.

Executors.newSingleThreadExecutor().submit(new Runnable() {
        @Override
        public void run() {
            //Your task here.
        }
    });

Please note there are numerous Threading Models and techniques in Android, some Android Specific, some based in Android.

AsyncTask

HandlerThread

martinomburajr
  • 1,235
  • 14
  • 29
0

You can use an AsyncTask. It allows you to load the file and show the progress on ui thread until the load it's finished.

Here you have a good example Download a file with Android, and showing the progress in a ProgressDialog

I would recommend using RxJava or Live Data if you are more advance in developing but also the first solution is fine enough for beginning https://developer.android.com/topic/libraries/architecture/livedata.html

Clapa Lucian
  • 590
  • 2
  • 7
  • 14