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.
If your problem is just Toast see How to display a Toast inside a Thread on Android?.
– ramaral