Thread Not Working Properly - Android
My thread is not working properly. It is executing all the code in RepeatingThread() method but not in the run() method every 3 seconds. What am I doing wrong? Here is the the cod
Solution 1:
You need to extend the Thread instead of implement the Runnable interface:
publicclassRepeatingThreadextendsThread{
//.....
}
Solution 2:
You should probably use a Timer
for this kind of short recurrent tasks:
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TimerTasktask=newRepeatingTask();
Timertimer=newTimer();
timer.scheduleAtFixedRate(task, 0, 3000);
}
publicclassRepeatingTaskextendsTimerTask {
privateintlen=0;
privatebyte[] input = newbyte[len];
publicRepeatingTask() {
//try {
Log.e(LOG_TAG, "Before inputJSON String");
//inputJSON = dataInputStream.readUTF();//URL url = new URL("tcp://23.23.175.213:1337");//inputJSON = dataInputStream.readUTF();//inputstrrd = new InputStreamReader(socket.getInputStream());Stringhello="hello world";
//String inputJSON = getStringFromBuffer(new InputStreamReader(socket.getInputStream()));//Convert
Log.e(LOG_TAG, "After inputJSON String:" + inputJSON);
/*}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*///LOOK HERE FIRST //inputJSON is what is received back from the server - Take the inputJSON //String and use regular expressions HERE to remove all the other characters in the //string except the payload JSON.//refreshViewModels(inputJSON);
}
@Overridepublicvoidrun() {
try {
Log.e(LOG_TAG, "IN REPEATINGTHREAD-INPUTJSON");
//outputstrwr.write(outputJSONserv); //UNCOMMENT IF NEED TO SEND DATA TO GET JSON BACK//inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
inputJSON = ConvertByteArrayToString(getFileBytes(inputStr));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "IN REPEATINGTHREAD-INPUTJSON2:" + inputJSON);
refreshViewModels(inputJSON);
}
}
In your code, you mix the Thread pattern (started with the start() method) and handlers, which is a bit confusing.
Post a Comment for "Thread Not Working Properly - Android"