Reputation: 507
In my app I use Room library for read/write values. In one activity I am reading a value from my SQLite db and I need to pass that value to next activity. Just because we cannot read values in main thread I am using a different thread. When I tried to put those values to intent.putExtra
outside the thread it gives me Nullpointerexception
. But if I put my intent
within the thread everything seem to be ok. I wanna know whether is it ok to put my intent within the thread? Is this the correct method? Do I need to use AsyncTask?
Runnable r = new Runnable(){
@Override
public void run() {
List<Vehicle> list = dDb.vehicleDao().getAll();
for (Vehicle s : list) {
vehicleNumber = s.getVehicleNo();
vehicleDescrp = s.getDescription();
}
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// Launch main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("VEHICLEID", vehicleNumber);
intent.putExtra("VEHICLEDS", vehicleDescrp);
startActivity(intent);
finish();
}
}
};
Thread newThread= new Thread(r);
newThread.start();
Upvotes: 0
Views: 881
Reputation: 6602
That will not work because you cannot do things like opening Actvity
outside of the Main Thread
.
If you really need it you have to wrap it with
runOnUiThread(new Runnable() {
void run() {
// Do stuff…
}
});
So in ur case it will look like
Runnable r = new Runnable(){
@Override
public void run() {
List<Vehicle> list = dDb.vehicleDao().getAll();
for (Vehicle s : list) {
vehicleNumber = s.getVehicleNo();
vehicleDescrp = s.getDescription();
}
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
LoginActivity.this.runOnUiThread(new Runnable() {
void run() {
// Launch main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("VEHICLEID", vehicleNumber);
intent.putExtra("VEHICLEDS", vehicleDescrp);
startActivity(intent);
finish();
}
};
Thread newThread= new Thread(r);
newThread.start();
Upvotes: 2