Get counter value from server and update in Textview - android

I have a server giving me live data in JSON format which updates every second. I have to display that in my android app.
I am a beginner and I tried Async Task updating every second via a thread and setting a delay on it.
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// Perform the HTTP request for data and process the response.
counterAsyncTask task=new counterAsyncTask();
task.execute(REQUEST_URL);
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
It runs out of memory and crashes after some time
Are there any alternates?

Try putting your code into handler thread
Runnable runnable = new Runnable() {
#Override
public void run() {
mHandler.postDelayed(this, 1000);
counterAsyncTask task=new counterAsyncTask();
task.execute(REQUEST_URL);
}
};
// start it with:
mHandler.post(runnable);

Related

how to start first thread complete to after second thread start

Am using some method i need to some method complete to start to another method so that am using thread function, How to start one thread follow by to second thread start?
Thread thread1 = new Thread(new Runnable() {
#Override
public void run() {
try {
loadIrrigationSourceMaster();
loadIrrigationMaster();
loadSeasonMaster();
loadFactoryMaseter();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
#Override
public void run() {
try {
loadTransport();
plantTypeMaster();
plotOwnerTypeMaster();
ExitRatoonMaster();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread2.start();
(new Thread(new Runnable() {
#Override
public void run() {
//TODO: fist thread code here
Log.w("tag","1");
(new Thread(new Runnable() {
#Override
public void run() {
//TODO: second thread code here
Log.w("tag","2");
}
})).start();
}
})).start();
out put of above:
tag:1
tag:2
but i dont think it's a good idea . just put rest of your job in first Thread
To wait for a thread to complete its execution before moving on, you can use the join() method: docs
Specifically for your problem, you can put thread1.join(), right after the thread1.start() call. The join call will block the calling thread until thread1 is finished with its execution, so that thread2 will be initialized and executed after thread1 is finished.
Alternatively, you can also call thread1.join() in the beginning of the run() method of thread2, so that the main thread won't need to be blocked by the join() call.

Android: ProgressDialog not progressing inside a Thread

I'm calling several AsyncTasks to do a job. In order to know when they are done. I have an object (synchronized) with a numerator that holds the number of current running AsyncTasks.
After deploying all of them I do the following:
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage(getString(R.string.please_wait));
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setProgress(0);
pd.setMax(Utils.getAsyncs());
pd.show();
new Thread(new Runnable() {
#Override
public void run() {
while (Utils.getAsyncs() > 0)
pd.setProgress(pd.getMax() - Utils.getAsyncs());
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
}
});
}
}).start();
When the dialog shows, it starts progressing but at some point it gets stuck til the end of everything and then dismisses (as expected).
I tried to put
pd.setProgress(pd.getMax() - Utils.getAsyncs());
also inside a runOnUiThread but that made things worse and I'm sure I'm missing something else. hence my question. Thanks
edited by request:
public static int getAsyncs() {
return asyncs;
}
edit 2: I did the following based on a comment
while (Utils.getAsyncs() > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
runOnUiThread(new Runnable() {
public void run() {
pd.setProgress(pd.getMax() - Utils.getAsyncs());
}
});
}
and it seems to be better
In your class fields
private Handler progressHandler = new Handler();
private Runnable progressRunnable = new Runnable() {
#Override
public void run() {
progressDialog.setProgress(progressValue);
progressHandler.postDelayed(this, 1000);
}
};
When the time consuming thread is started
// Here start time consuming thread
// Here show the ProgressDialog
progressHandler.postDelayed(progressRunnable, 1000);
When the time consuming thread ends
progressHandler.removeCallbacks(progressRunnable);
/// Here dismiss the ProgressDialog.
ADDED:
Instead new Thread(new Runnable) that you probably use for your time consuming code I propose to do this:
To initialize the task :
MyTask task = new MyTask();
task.execute();
// Here show the PorgressDialog
progressHandler.postDelayed(progressRunnable, 1000);
Add this private class inside your main class:
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
//Here do your time consuming work
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
// This will be called on the UI thread after doInBackground returns
progressHandler.removeCallbacks(progressRunnable);
progressDialog.dismiss();
}
}
do something lik this
new Thread(new Runnable() {
public void run() {
while (prStatus < 100) {
prStatus += 1;
handler.post(new Runnable() {
public void run() {
pb_2.setProgress(prStatus);
}
});
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(prStatus == 100)
prStatus = 0;
}
}
}).start();

Android present streamed images

I want to present bitmap images from a internetstream. Every 500 millisec i get a new image and i want to present this image to the user. What is the best way to do this? Can i use an image view and chenge the image every 500 millisec?
I tried to do this in an timer task like this:
timer.schedule(new TimerTask() {
public void run() {
if(flag){
Bitmap bmp = null;
Log.i(APPID, "New frame");
try {
bmp = session.getImage();
setImage(bmp);
} catch (Exception e) {
e.printStackTrace();
}
} else {
timer.cancel();
}
}
}, 500, 500);
But this does not work.
Updating the UI from a thread other than the UI/main thread will fail as Android does not allow it. Try using a Handler to post messages back to the UI thread. You could do something like this.
final Handler h = new Handler();
timer.schedule(new TimerTask() {
public void run() {
if(flag){
h.post(new Runnable() {
public void run() {
Bitmap bmp = null;
Log.i(APPID, "New frame");
try {
bmp = session.getImage();
setImage(bmp);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
timer.cancel();
}
}
}, 500, 500);
Timer task runs on a different thread. you need to update ui on the ui thread. You should use runOnUiThread or Handler
runOnUiThread(new Runnable() //run on ui threa
{
public void run()
{
// update ui here
}
});
Handler
Handler m_handler;
Runnable m_handlerTask ;
m_handler= new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
// do soemthing
m_handler.postDelayed(m_handlerTask, 1000);
// change 1000 to whatever you want
}
};
m_handlerTask.run();
When you wan to cancel call this m_handler.removeCallbacks(m_handlerTask).

How to notify worker thread that UI is modified using Handler.Post()?

I have a worker thread and occasionally i send updates to the UI Thread using Handler.Post(). In some cases i need worker thread to wait until Handler.Post() executed on UI Thread and the view is modified and after UI thread is modified, notify the worker Thread to go on...
here is my simple worker thread:
workerThread = new Thread() {
#Override
public void run() {
progressBarHandler.post(new Runnable() {
public void run() {
//Step1: which works ok
ActionModeButton.performClick();
}
}
//Step2: returns null pointer exception because ActionMode
//is not yet created and R.id.select_recording is an
//ActionMode button if I put Thread.sleep(1000); here it
//will work fine.
final View selectRecording = getActivity()
.findViewById(R.id.select_recording);
selectRecording.post(new Runnable() {
public void run() {
selectRecording.performClick();
}
});
}
}
workerThread.start();
using synchronized block with wait and notify
final Handler handler = new Handler();
final Object lock = new Object();
new Thread(new Runnable() {
boolean completed = false;
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
synchronized (lock) {
//Do some stuff on ui thread
completed = true;
lock.notifyAll();
}
}
});
synchronized (lock) {
try {
if(!completed)
lock.wait();
}
catch (InterruptedException e) {
}
}
}
}).start();
What about using a Semaphore for that?
Semaphore semaphore = new Semaphore(0);
uiHandler.post(new Runnable() {
// ... do something here
semaphore.release();
});
semaphore.acquire();
The Semaphore start with 0 permit. The thread will block on semaphore.acquire() until semaphore.release() (which will add a permit) is called.

how to create a thread to refresh data in 3 second interval

I need a thread (it does httppost ,and parse the answer xml and refresh listview to set the changes from parsed xml) in 3 sec interval
I have already tried this code
Timer timer = new Timer();
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
try {
httpPostList(url);
saxParseList();
list.invalidateViews();
Thread.sleep(1000);
} catch (Exception ie) {
}
}
}, 1000, 1000 * 30);
I would appreciate you to create a Service with an AsyncTask in it.
Async Tasks are the Android Synonym to normal Java Tasks, Documentation finding here: http://developer.android.com/reference/android/os/AsyncTask.html
Services are Background Processes, seeing this Doc:
http://developer.android.com/reference/android/app/Service.html
Try using handlers:
Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
// ...
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
updateUI();
}
};
Thread thread = new Thread() {
#Override
public void run() {
while(true) {
Message msg = new Message();
handler.sendMessage(msg);
try {
sleep(3*1000); // 3 seconds
} catch (InterruptedException e) {
}
}
}
};
thread.start();
}
private synchronized void updateUI() {
// ...
}
Finally I made it using "Async task".

Categories

Resources