Android : Refreshing a fragment inside a thread

on Saturday, December 13, 2014


I have an Android Application which is receveing info from a server. I am running a Thread to read the info and after that I want to update my fragment.


Here is the Thread:



public void receiveMessage(final Activity act){
Thread t = new Thread(){
public void run(){
try{
ServerSocket ss = new ServerSocket(4444);
while(true){
Socket s = ss.accept();
ObjectInputStream dis = new ObjectInputStream(s.getInputStream());
final Mensagem m = (Mensagem) dis.readObject();
if(m != null){
((MyApplication) act.getApplication()).setRoomHelper(m.getRoomHelper());
((MyApplication) act.getApplication()).setIsNight(m.getIsNight());
}
Log.d("p", "RECEBI: " + m);

Handler handler = new Handler(Looper.getMainLooper());

handler.post(new Runnable() {

@Override
public void run() {
Log.d("b", "RUNNN");
Toast.makeText(act, "JANELA: " + m.getRoomHelper().isWindow() + " e LUZ: "
+ m.getRoomHelper().isLight(), Toast.LENGTH_LONG).show();
}
});
dis.close();
s.close();
Fragment fragment = new Room();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
}
catch(IOException e){

} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
};
t.start();
}


I want to update my fragment beucase this line here:



((MyApplication) act.getApplication()).setRoomHelper(m.getRoomHelper());


receives a lot of new info which and I need to updated it with the info I receive. The problem is I am getting:



12-13 23:24:48.133 5583-5866/com.example.rui.smarthome W/dalvikvm﹕ threadid=13: thread exiting with uncaught exception (group=0x4163ad40)
12-13 23:24:48.134 5583-5866/com.example.rui.smarthome E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-42438
Process: com.example.rui.smarthome, PID: 5583
java.lang.NullPointerException
at com.example.rui.smarthome.Room$6.run(Room.java:622)
12-13 23:24:48.188 5583-5583/com.example.rui.smarthome D/AndroidRuntime﹕ Shutting down VM
12-13 23:24:48.195 5583-5583/com.example.rui.smarthome W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4163ad40)
12-13 23:24:48.195 5583-5583/com.example.rui.smarthome I/Process﹕ Sending signal. PID: 5583 SIG: 9


The error line is this one:


FragmentManager fragmentManager = getActivity().getSupportFragmentManager();


So, since I am thinking I can't use that in here, which other options, not changing a lot of the code do I have?


I was thinking about a solution using a boolean, iniatialized outside of the thread and setting it to true inside it. The thing is it needs be declared final, so I can't change it inside the thread.


0 comments:

Post a Comment