friends,
i am using following code to display progress on andorid activity when i call web service method to getposts it show progress. but when call of serivce is complete my application gets crashed.
please guide what mistake am i doing or any other alternative way to achieve this goal?
mProgressStatus = 0;
Thread th=new Thread(new Runnable() {
public void run() {
if (mProgressStatus < 100) {
myProgressBar.setVisibility(View.VISIBLE);
} else {
myProgressBar.setVisibility(View.GONE);
}
}
});
th.start();
results = p.GetPosts(p, PageSize, adap.getCount());
mProgressStatus=100;
th.stop();
So, if your application crashes, maybe you should look at the error message first? Or at least provide it for us.
(A tip: I read three posts of you today and you always have trouble with the first/last lines of your code pasting, please check you code pasting before you submit a question...)
You can try using runOnUiThread, if you are in an activity class
mProgressStatus = 0;
MyActivity.this.runOnUiThread(new Runnable() {});
public void run() {
if (mProgressStatus < 100) {
myProgressBar.setVisibility(View.VISIBLE);
} else {
myProgressBar.setVisibility(View.GONE);
}
}
});
Everything about the UI have to be executed in the UI Thread
Related
I am trying to create an auto image slider using a view pager following some tutorials. I got everything working, but then I see
Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread. and googled the error.`
You see, in my code, I have a timer and a handler that just delay the code for 3 seconds and then slides the view pager to the next image. I confirmed with a friend and after hours of searching, there was nothing else that was doing too much work on the main thread.
So searching on stack overflow about the problem, I see that a lot of developers suggested using AsyncTask to do some stuff in background and then update, which might actually be a perfect solution here. But then I realised that I know nothing about AsyncTask. I went to the android developers reference and saw some tutorials, but I was unable to find something that'll fit into my solution.
I saw a lot of tutorials about image downloading, but they are by far, not what I'm concerned with. I am only concerned with controlling the view pager to move to the next slide.
Here is the part where I control my view pager to slide:
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);
How do I incorporate this code into an AsyncTask?
For reference, I used this tutorial.
Runnable is a seprate worker thread, it has no interaction with main thread. When you are handling ui elements, use runOnUiThread. example.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
});
or
runOnUiThread(){
mPager.setCurrentItem(currentPage++, true);
}
Below you can find two methods on how can one run a code on the main/UI thread on android:
runOnUIThread Activity’s method
runOnUiThread(new Runnable(){
public void run() {
// UI code goes here
}
});
Handler
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
// UI code goes here
}
});
source
I am developing an Android application and I want to call a function every 40ms. To do so, I implemented a Handler and a Runnable. I chose this two objects thanks to the post How to run a method every X seconds. But I am not sure this is the right way to perform what I am doing :
In my application, I am playing a video, I want to "launch" the Handler when starting the video, "put it on hold" when pausing the video, starting it again when resuming the video and so on.
So far, I am using mHandler.removeCallbacks(mRunnable); to detain it. But to start it or resume it, I don't know if I should use mHandler.post(mRunnable); mHandler.postDelay(mRunnable, DELAY) or mRunnable.run();. I succeed making them all work but the behaviour is never as expected...
Here is the code I use to set up the Handler...
public void setUpdatePositionHandler() {
mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
if (mVideoView.getCurrentPosition() > mVideoView.getDuration()) {
if (mVideoView.getCurrentPosition() > 1000) {
mVideoView.seekTo(1); // go back to beginning
mVideoView.pause();
mPlayButton.setVisibility(View.VISIBLE);
mStampIndex = 0;
mLastPosition = 0;
Log.i(TAG, "removeCallbacks() from runnable");
mHandler.removeCallbacks(this);
} else {
//mHandler.postDelayed(this, DELAY);
}
} else {
if (!mStamps.isEmpty()) {
onPositionUpdate(mStamps);
}
mHandler.postDelayed(this, DELAY);
}
}
};
Note that I don't feel really sure of what I implemented so far, and that any ressources that would help me understand better would be welcome :) (I already read the documentations of the 2 classes and read several documents or posts on the subjects, but I think I am missing something.)
Thank you for your help
Is it the correct way ?
if it will not produce any problem and it meets your requirements then yes
but your question should be is it the best practice?
i prefer to write it like the following
public void setUpdatePositionHandler() {
mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
if (mVideoView.getCurrentPosition() > mVideoView.getDuration()) {
if (mVideoView.getCurrentPosition() > 1000) {
mVideoView.seekTo(1); // go back to beginning
mVideoView.pause();
mPlayButton.setVisibility(View.VISIBLE);
mStampIndex = 0;
mLastPosition = 0;
Log.i(TAG, "removeCallbacks() from runnable");
mHandler.removeCallbacks(this);
} else {
//mHandler.postDelayed(this, DELAY);
}
} else {
if (!mStamps.isEmpty()) {
onPositionUpdate(mStamps);
}
}
}
mHandler.postDelayed(mRunnable, DELAY);
};
be noted the above code will work only once expect if you make CountDownTimer or you can use Thread.sleep() with a normal loop and AsyncTask in order to not block your code because if so the application will not be responding and then your app will be crached
In an effort to learn Android I am writing a small app. The first thing I am trying to do is login via a remote API.
I would like to show a "loading" dialog when the call is being made (in case he user in using mobile internet). Researching this has shown two possible methods.
One is to use a ProgressDialog and a private class that extends Thread, the other is using a private class that extends AsyncTask.
Which is best/more appropriate for this task?
I have tried using the ProgressDialog version but am struggling. I have put the function making the http request in the extended Thread run() method, but am unsure on how to pass the response data (JSON) back into my activity.
Any and all help gratefully received.
The best way possible is to use an AsyncTask with a ProgressDialog. You should extend AsyncTask and implement all the methods you need:
onPreExecute() - here you initialize your ProgressDialog and show() it
doInBackground() - here you do your work
onPostExecute() - here you call dismiss() on ProgressDialog to hide it
(optional) onProgressUpdate() - here you can change the progress of your ProgressDialog if it's determinate
There is a get() method in AsyncTask class that lets you retrieve the result of the work. Also you can implement an interface between the AsyncTask and calling Activity to return the result. Hope this helps.
Efforts come with rewards :) Egor is right, AsyncTask is the best way to do it. But
You have to know that Activity is working on the UI thread and threads not. So the only way to share things is via handler. Here an example:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = (ProgressBar) findViewById(R.id.progressBar1);
handler= new Handler();
}
public void startProgress(View view) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
progress.setProgress(value);
}
});
}
}
};
new Thread(runnable).start();
}
I am developing on Android but the question might be just as valid on any other Java platform.
I have developed a multi-threaded app. Lets say I have a first class that needs to do a time-intensive task, thus this work is done in another Thread.
When it's done that same Thread will return the time-intensive task result to another (3rd) class.
This last class will do something and return it's result to the first-starting class.
I have noticed though that the first class will be waiting the whole time, maybe because this is some kind of loop ?
Also I'd like the Thread-class to stop itself, as in when it has passed it's result to the third class it should simply stop. The third class has to do it's work without being "encapsulated" in the second class (the Thread one).
Anyone knows how to accomplish this ?
right now the experience is that the first one seems to be waiting (hanging) till the second and the third one are done :(
If you want to use threads rather than an AsyncTask you could do something like this:
private static final int STEP_ONE_COMPLETE = 0;
private static final int STEP_TWO_COMPLETE = 1;
...
private doBackgroundUpdate1(){
Thread backgroundThread = new Thread() {
#Override
public void run() {
// do first step
// finished first step
Message msg = Message.obtain();
msg.what = STEP_ONE_COMPLETE;
handler.sendMessage(msg);
}
}
backgroundThread.start();
}
private doBackgroundUpdate2(){
Thread backgroundThread = new Thread() {
#Override
public void run() {
// do second step
// finished second step
Message msg = Message.obtain();
msg.what = STEP_TWO_COMPLETE;
handler.sendMessage(msg);
}
}
backgroundThread.start();
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch(msg.what){
case STEP_ONE_COMPLETE:
doBackgroundUpdate2();
break;
case STEP_TWO_COMPLETE:
// do final steps;
break;
}
}
}
You would kick it off by calling doBackgroundUpdate1(), when this is complete it sends a message to the handler which kicks off doBackgroundUpdate2() etc.
Tiger ,
TiGer wrote:
When it's done that same Thread will
return the time-intensive task result
to another (3rd) class
Since thread runs asynchronously so your non-thread class can't be synced with your thread
Though to perform some action on an Activity you need an AsyncTask not A Thread
TiGer wrote:
maybe because this is some kind of
loop ?
Tiger do read more about Threads and concurrency
So the only answer I have for you now is ASYNCTASK
EDIT:
Also I'd like the Thread-class to stop
itself
Read this post's how-do-you-kill-a-thread-in-java
In ordinary Java, you would do this:
class MyTask implements Runnable {
void run() {
for (int i = 0; i < Integer.MAX; i++) {
if (i = Integer.MAX -1) {
System.out.println("done");
}
}
}
}
class MyMain {
public static void main(String[] argv) {
for (int i = 0; i < 10; i++) {
Thread t = new Thread(new MyTask());
t.start();
}
System.out.println("bye");
}
}
... that kicks off 10 threads. Notice that if you accidentally invoke t.run() instead of t.start(), your runnable executes in the main thread. Probably you'll see 'bye' printed before 10 'done'. Notice that the threads 'stop' when the the run() method of the Runnable you gave to them finishes.
I hope that helps you get your head around what it is you've got to co-ordinate.
The tricky part with concurrency is getting threads to communicate with each other or share access to objects.
I believe Android provides some mechanism for this in the form of the Handler which is described in the developer guide under designing for responsiveness.
An excellent book on the subject of concurrency in Java is Java Concurency in Practice.
if you want use AsyncTask rather then thread in android
I have resolve it using ASyncTask and Handler in Android the aim is that one task is execute after compilation of one task hear is code that show First load animation on view after compilation of that process it will goes on another page
class gotoparent extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Animation animation= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotete);
lin2.startAnimation(animation);
}
});
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(getApplicationContext(),ParentsCornor.class);
startActivity(i);
}
}, 1200);
}
}
Hej, I'm trying to create an app that runs on a main thread, but also has a background loop running (to check for a connection).
I just want to call a certain function onCreate, and that function should run in the background...I've tried with the code below, but doesn't seem to work...any suggestions?
void doStuffBackground()
{
Thread testingForBluetooth = new Thread()
{
public void run()
{
try
{
for(int i = 0; i < 100; i++)
{
writeTerminal('x');
sleep(100);
}
}
catch(Exception e)
{
Log.e("Threading", e.toString());
}
finally
{
finish();
}
}
};
}
}
But again...not working?
Thanx in advance
You never started the thread.
Anyway if you need a background task, you could also try a service.