Problem with thread implementation - android

I have a Start button to start my function for downloading data(startdownload()).
When the start button click i have placed a text view that shows data is dowmload started and when download completed the same text view show download completed .
Download function is placed under a thread.
start_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Status.setText("Download Started");
Thread t = new Thread(){
public void run() {
startdownload();
runOnUiThread(new Runnable() {
public void run() {
Status.setText("Download Completed");
}
});
}};
t.start();
}
});
Also i have a stop button to stop downloading data,which stop the thread and shows download stopped using the same text view as above mentioned.the stop button code is as below
stop_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onStop();
Status.setText("Download Stopped");
}
public void onStop() {
super.onStop();
isRunning = false;
}
The problem is that when i click start button the text view shows download started but when clicked stop button before completely dowloading the data it shows download stopped
in the text view first and after some time it shows download completed.....
Please any one verify that is there any problem with my thread implementation procedure...
I think thats why it shows download completed even when i stoped the thread using stop button....Please help me......

I think you can update UI from thread so please try to use the handler.
Thank you.

Do you actually stop thread? Or it continues to run after you press stop button?
You can use flag isStopped and in thread:
if (!isStopped) {
runOnUiThread(new Runnable() {
public void run() {
Status.setText("Download Completed");
}
});
}
and set isStopped to true in stop_button.

If onStop() is the Activity.onStop() callback method, then you should not call it. It has nothing to do with your downloading thread, and anyway it's just a system callback that is called by system. Actually, stopping a thread by yourself is not recommended, the Thread.stop() method is deprecated, as you may know. It's easy to "stop" a thread that is performing some operations in a loop: you just drop the flag controlling the loop, result is that the thread keeps on running, but it's doing nothing. Your application architecture doesn't let you stop your thread, cause you're just running a task. Post your downloading code and it will be more clear what you're doing and what you're trying to achieve.

Related

Android app in background: Thread stopped after short time

I'm starting a thread like this in my app.
private void AppThreadWorker()
{
AppThread = new Thread(new Runnable() {
#Override
public void run() {
while (canRun)
{
//do async get from server
}
});
AppThread.start();
}
I want to be able to move this app in background and I want this thread continues working. This works fine. The problem is that after 1 hour the Thread stops. Do you know some tricks to let him run for more time?
Use Service for This.
Create a Thread inside Service because by default Service run in UI (Main) Thread.

ProgressBar running faster after each onclick in android

I am Stuck here with this application in android. In my application i am trying to implement a progressbar which shows timer for certain seconds. When the Button is clicked the timer should refresh and again start from 0 in progressBar. For this I am using Thread.
The Problem is, When I Click the button the Thread calls the timer function and each time the thread is getting faster and faster. I couldn't resolve it and not having any idea what is going in background.
This is my code for Timerfunction
public void setTimer()
{
prog=0;
progress.setProgress(prog);
if(flag){
t= new Thread(new Runnable(){
public void run()
{
while(prog<100)
{
prog+=1;
handle.post(new Runnable(){
public void run()
{
progress.setProgress(prog);
if(prog==progress.getMax()&& flag){
call_fun();
}
}
});
try
{
Thread.sleep(time);
}
catch(InterruptedException e)
{
Log.i("Error", null);
}
}
}
});
t.start();
}
}
I called this function in another function called RandomGeneration. If the button is clicked the randomgeneration is called and the set timer is activated everytime. But the progressbar is running faster after every click. It is constantly running in the same specific time. For example if it runs for 3 seconds in the first click, its running 2 seconds in the second click and getting faster considerably.
Can anyone please try to find what is happening in this code.
Thanks in advance..!!
From what I see a new Thread is being created everytime you click the button.
Maybe try to check if t is already running and if so update it's logic to set progress to 0?
Also, what does if(flag) do?

onClickListener not work will thread is in run mode?

i am trying to make kind of player, so, I setup play button and pause button and make them clickListener . when i press play button the thread start (and it work fine) but the pause button dont work until the thread is finished. what can i do to fix it?
constructor:
play = false;
playButton=(ImageButton)findViewById(R.id.imageButton1);
playButton.setOnClickListener(playButtonClick);
the runnable:
private Runnable runnable=new Runnable() {
#Override
public void run() {
int count=0;
long time=System.currentTimeMillis();
while(count<24*3 && play)
{
if (System.currentTimeMillis()-time>41.67){
count++;
time=System.currentTimeMillis();
scene.play();
draw(sf.getHolder());
}
}
play=false;
}
clickListener:
private OnClickListener playButtonClick=new OnClickListener() {
#Override
public void onClick(View v) {
if (!play){
play = true
scene=new TestScene(3,t);
thread=new Thread(runnable);
thread.run();
}else
play = false;
}
};
the problem: when the thread is run i cant stop it the function clicklistner is working just when the thread is stop.
Try using Thread.start() instead of Thread.run()
See Thread Docs:
If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
Edit:
You can also read this answer for more information about start vs. run
Based on your question, A Thread is running in it's own space. The only way to halt a Thread is to tell it to Halt. You could set some static variable that the Thread is listening on. The Thread can take necessary action depending on the state of the variable. In the simplest scenario Pressing the pause button could change a static variable in the Thread class file

Android Button Response Problem

hi all
since i am using a button and on the click of that button it connects to a Web Service.
But the problem is that when i press the button it does not showed me that it has been clicked and goes to connect to the internet and web service. after connecting it shows me the response that it has been clicked. in short the response of button is very slow. if that buton has some INternet connectvity in its Listener.
i know it has something to do with UI thread. but please friends guide me through this.
Thanks a bunch,
Put the following code in your class:
// Need handler for callbacks to UI Threads
// For background operations
final Handler mHandler = new Handler();
// Create Runnable for posting results
final Runnable mUpdateResults = new Runnable() {
public void run() {
// Do your task which needs to get done after webservice call is complete.
}
};
And for calling the webservice use the following code in button event:
new Thread() {
public void run() {
// Place the webservice call here.
mHandler.post(mUpdateResults);
}
}.start();
Actually what are you looking for is multithreading, all the webservice calls and network activities should go in separate thread.
After the thread start() call you can do what ever you want and would be done instantly without any delay (in your case showing that button pressed).
You have to use Handler for this background operation already ask on OS follow this link
progress dialog not showing in android?
You should write a class say MyWebService and extend it from AsyncTask. Perform the connect operation in its overridden doInBackground() method and update any UI changes in its onPostExecute() method.
Create a new Thread in the onClickListener that does the heavy work in the background. That way the UI thread will be able to update the state of the button:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
// Code that connects to web service goes here...
}
}).start();
});

Task not finishing and forbidding TextView to be updated

I am now working on an android app in which I need to display a text after some processing is done.
I'm using a Thread to run a process in the back while my progress dialog is being displayed to the user. The Thread works properly and I've followed it step by step and, apparently, it also ends fine; however, the method in which I call it does not seem to come to an end (at least, during a normal cycle) because the text I am setting afterward does display immediately, I have to wait and do some other action (like in order for it to display
Below is the piece of code I'm having trouble with:
private OnClickListener saldoDisp = new OnClickListener(){
public void onClick(View v){
int x = s2.getSelectedItemPosition();
branchSel = arrSucsId[x];
mainProc();
saldoAdminTex.setText(strSaldo); //The late one
}
};
public void mainProc(){
chekP = new Thread (null,doProc,"Background");
chekP.start();
mProgress =ProgressDialog.show(SivetaAsaldo.this, "","Obteniendo saldo...",true, false);
}
private Runnable doProc = new Runnable(){
public void run(){
if(getSaldoAdmin(levelSel,branchSel))
{
mProgress.dismis();
Log.i(TAG,"Task completed properly");
}else
handler.post(tosti);
}
};
So I do get the "Task completed properly" but seems like it still waits for something else, any clues guys?
Thanks for taking a bit of your time to check it out =).
saldoAdminTex.setText(strSaldo); //The late one
is going to get called immediately. It doesn't wait until after the Thread started in mainProc ends. You also cannot dismiss the Progress Dialog in your runnable. You can only do UI related things on the main UI thread.
It would help you to read the article on Painless Threading on the Android Dev site.
About your ProgressDialog, please see this answer about how to use a AsyncTask with a ProgressDialog.
Looking at your code, this:
saldoAdminTex.setText(strSaldo);
would potentially be executed before your thread finishes as the thread will be running in parallel to that line.
An alternative way would be to do this:
public void mainProc(){
mProgress =ProgressDialog.show(SivetaAsaldo.this, "","Obteniendo saldo...",true,false);
handler.post(new Runable(){
public void run(){
if(getSaldoAdmin(levelSel,branchSel))
{
mProgress.dismis();
saldoAdminTex.setText(strSaldo);
Log.i(TAG,"Task completed properly");
}else
handler.post(tosti);
}
});
}

Categories

Resources