Running threads on android

Asked

Viewed 536 times

0

I’m new at work with threads on Android and I’m having difficulties to implement them.

To thread will be used to make a calculation and finally send an email depending on the result of the calculation, but I am not able to implement it nor to call a simple toast due to exception:

java.lang.Runtimeexception: Can’t create Handler Inside thread that has not called Looper.prepare();

I don’t know if it’s because I’m using it in the user’s Activity and I don’t know how to solve it, could they help me ? Follow the related codes

Mainactivity:

public class MainActivity extends AppCompatActivity {
//ATRIBUTOS
private ArrayAdapter adapter;
private ListView listView;
private ArrayList<Coins> arrayList;
private Toolbar toolbar;

private final long intervalo = 10000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //CONFIGURANDO A TOOLBAR
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("CoinmarketCap");
    setSupportActionBar(toolbar); //indispensavel para o funcionamento da toolbar

    //********* CONFIGURANDO A LISTAGEM DAS MOEDAS **********/
    listView = (ListView) findViewById(R.id.lv_coins);

    arrayList = new ArrayList<>();
    adapter = new CoinsAdapter(MainActivity.this, arrayList);
    listView.setAdapter(adapter);

    //********* FIM CONFIGURANDO A LISTAGEM DAS MOEDAS **********/
    recarregar();

    //EXECUTANDO A TAREFA DE CALCULO
    Timer timer = new Timer();
    TimerTask tarefa = new TimerTask() {
        @Override
        public void run() {
            try{
                Inbackground inbackground = new Inbackground(MainActivity.this);
                inbackground.run();
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    };
    timer.scheduleAtFixedRate(tarefa, intervalo, intervalo);
}

Class extending Timertask:

public class Inbackground extends TimerTask {
private Context context;

public Inbackground(Context c){
    this.context = c;
}

@Override
public void run() {
    Toast.makeText(context, "Rodando a thread", Toast.LENGTH_SHORT).show();
}
}

I do not know if this is the best way to accomplish the task of calculating and sending by email, if there is an easier way or better way in question to the performance I will be happy to meet you.

2 answers

1

The best way to implement this is by using Asynctask, it looks like this:

  class Tarefa extends AsyncTask<String, String, String> {

        ProgressDialog dialog = new ProgressDialog(this);
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog.setMessage("Acessando...");
            dialog.setCancelable(false);
            dialog.show();
        }
        @Override
        protected String doInBackground(String... strings) {
            int a = 4+5;

            return String.valueOf(a);               
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

           Toast.makeText(Main.this,s, Toast.LENGTH_SHORT).show();
        }
    }

And then you call wherever you want, like this: new Tarefa().execute();

  • The way you’re doing it won’t be able to send a message during the thread, if you don’t implement Handler, like this: Handler h = new Handler(Looper.getMainLooper()); h.post(new Runnable() { public void run() { Toast.makeText( Suaactivity.this.getBaseContext(), "Text", Toast.LENGTH_SHORT). show(); } });

  • If possible click [Edit] and add the comment code in your reply.

0

Você pode usar esse dois passo que montei.

1 - Primeiro crie uma classe chamada AsyncControl

public class AsyncControl {

private ProgressDialog mProgressDialog;

    public static void runAsync(final AsyncListiner listiner, final Context context, final String title) {
        run(listiner, context, title, true);
    }

    public static void runAsync(final AsyncListiner listiner, final Context context, final String title, boolean showDialog) {
        run(listiner, context, title, showDialog);
    }

    public static void runAsync(final AsyncListiner listiner, final Context context,boolean showDialog) {
        run(listiner, context, "", showDialog);
    }

    public static void run(final AsyncListiner listiner, final Context context, final String title, final boolean showDialog) {
        new AsyncTask() {
            Dialog dialog;

            @Override
            protected void onPreExecute() {
               mProgressDialog = new ProgressDialog(activity);
               mProgressDialog.setIndeterminate(false);
               mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                if (showDialog)
                    dialog.show();
            }

            @Override
            protected Object doInBackground(Object[] objects) {
                listiner.run();
                return null;
            }

            @Override
            protected void onPostExecute(Object o) {
                dialog.dismiss();
                listiner.onComplete();
            }
        }.execute();
    }

    public interface AsyncListiner {
        void run();
        void onComplete();
    }
}

2 - Para chamar o metodo em modo async

 AsyncControl.runAsync(new AsyncControl.AsyncListiner() {
            @Override
            public void run() {
                /// o que deve ser feito em background
            }

            @Override
            public void onComplete() {
              /// Quando termina de executar em background
            }
        },mContext,"Esse é um titulo");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.