I'm new to working with threads
on Android and I'm having a hard time implementing them.
The thread
will be used to make a calculation and finally send an email depending on the result of the calculation, however I am not able to implement it nor to call a simple toast
due to the exception:
java.lang.RuntimeException: Can not create handler inside thread that has not called Looper.prepare ();
I do not know if it's because I'm using it in the user's activity and I do not know how to solve it, could you 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 that extends 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 the calculation and sending by email, if there is an easier way or better in question to the performance I will be happy to know it.