Hello! I decided to do one resource-intensive operation (the method is in a different class) in another thread:


//MainActivity public void open_generator(int s) { //тут был код, который не имеет отношения к вопросу time_start = System.currentTimeMillis(); Generator.generate(s); } 

 //Generator public static void generate(final int r) { new Thread(new Runnable() { @Override public void run() { //очень много кода handler.post(new Runnbale() { //вот тут как бы идёт возвращение в основной поток @Override public void run() { MainActivity ma = new MainActivity(); ma.finished(System.currentTimeMillis()); } }); } }).start(); } 

 //и снова MainActivity public void finished(long at) { time_finish = at; int time = (int)(time_finish - time_start) / 1000; Toast.makeText(MainActivity.this, "Генерация завершена за " + time + " секунд", Toast.LENGTH_LONG).show(); } 

After running this code, the application crashes, in the logs a complete nonsense (swears at ContextWrapper , called from Toast.makeText(...).show(); ). I understand that I incorrectly "returned" to the main thread. Even runOnUIThread() didn't help. What to do?

On the pros do not skimpy.

  • 2
    read about asyntask, in your version you need to do a handler - Gorets
  • @Gorets, if done under asynctask, you will have to redo a lot. Is there no way easier? - Helisia

1 answer 1

You have a problem not in the streams, but in the fact that you are creating a new instance of MainActivity.class , which has no context. And when creating Toast get not a "complete nonsense")), but a NullPointerException , I suppose. Pass a copy of your Activity to the generate() method:

 Generator.generate(s, this); 

and use it:


 //Generator public static void generate(final int r, final MainActivity ma){ new Thread(new Runnable() { @Override public void run() { //очень много кода handler.post(new Runnbale() { //вот тут как бы идёт возвращение в основной поток @Override public void run() { /* MainActivity ma = new MainActivity(); // - ошибка здесь*/ ma.finished(System.currentTimeMillis()); } }); } }).start(); } 
  • So did! Thank! - Helisia