package com.example.asynctask;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
ProgressBar progressbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressbar = (ProgressBar) findViewById(R.id.progressBar);
}
class ProgressTask extends AsyncTask<Integer, Integer, Void> {
private boolean flag = true;
#Override
protected void onPreExecute() {
progressbar.setMax(100);
}
#Override
protected void onCancelled() {
//progressbar.setMax(0);
flag = false;
Log.v("onCancelled:flag", String.valueOf(flag));
}
#Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
int start = params[0];
for (int i = start; i <= 100; i=i+10) {
if (!flag) {
break;
} else {
publishProgress(i);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("ThreadError", e.toString());
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
progressbar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
Log.v("Progress", "Finish");
}
}
public void onClick(View v) {
ProgressTask task = new ProgressTask();
switch (v.getId()) {
case R.id.start:
task.execute(10);
break;
case R.id.stop:
task.cancel(true);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here is a symple AsyncTask app which starts to update the progress bar when you hit Start. But when you will hit stop, it wont stop. Thing is when you call task.cancel(true), onCancelled() methods does gets invoked and changes the value of flag to false but in onCancelled() value of flag remains true. I have also tried isCancelled() in place of flag varaible with no success. For a moment my problem is similar to Ollie C, but no exceptions are thrown in my case.
As Wenhui pointed out in the comment, I made a silly mistake in which I declared and instantiated task inside onClick(View v).
Related
I am facing a problem, I have implemented a code, it is showing me message in Logs correctly but it doesn't update the TextView's text. Here i have tried this version. How i can update it? I tried it using threads as well but in vain.
I have seen many solution over this StackOverflow platform but i could not find my any solution for my problem.
package com.example.yousafmoh.seizuredetection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class ledControl extends AppCompatActivity {
// Button btnOn, btnOff, btnDis;
ImageButton On, Off, Discnt, Abt;
TextView txtMessage;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
//call the widgets
On = (ImageButton)findViewById(R.id.on);
Off = (ImageButton)findViewById(R.id.off);
Discnt = (ImageButton)findViewById(R.id.discnt);
Abt = (ImageButton)findViewById(R.id.abt);
txtMessage = (TextView) findViewById(R.id.txtMessage);
new ConnectBT().execute(); //Call the class to connect
//myBluetoothThread();
//commands to be sent to bluetooth
On.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
Off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
Discnt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void myBluetoothThread() {
while(true)
{
if (btSocket!=null)
{
try
{
if(isBtConnected) {
InputStream inputStream = btSocket.getInputStream();
for (int i = 0; i <= inputStream.available(); i++) {
//Log.d("data", inputStream.read() + " "+"ok");
int val = inputStream.read();
if (val == 49) // seizure detected
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
Log.d("Message", " Detected");
}
});
Log.d("Message", " Detected");
} else if (val == 48) // no detection
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
Log.d("Message", "not Detected");
}
});
Log.d("Message", "not Detected");
//, Toast.LENGTH_SHORT).show();
}
}
}
}
catch (IOException e)
{
msg("Error");
}
}
}
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
for(int i = 0 ; i <= inputStream.available();i++)
{
Log.d("data",inputStream.read()+" ");
}
Log.d("Bytes available off",String.valueOf(inputStream.available()));
Log.d("Message off",String.valueOf(inputStream.read()));
//btSocket.getOutputStream().write("0".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
Log.d("Bytes available on",String.valueOf(inputStream.available()));
Log.d("Message on",String.valueOf(inputStream.read()));
Log.d("Message on",inputStream.toString());
btSocket.getOutputStream().write("1".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
public void about(View v)
{
if(v.getId() == R.id.abt)
{
Intent i = new Intent(this, AboutActivity.class);
startActivity(i);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_led_control, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
progress.dismiss();
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
if(progress!=null)
progress.dismiss();
if(isBtConnected)
{
myBluetoothThread();
}
}
}
}
Try using this if its a fragment class
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
and this is its an activity
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
Another solution u can try is.
You can use handler
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
}
});
I have read some article somewhere that you should not update your textview directly inside the Runnable Thread. So what I did is i created a function that updates the textview then the Runnable run method calls that function. So It look like this.
public class SampleActivity extends AppCompatActivity {
TextView sample;
int counter = 0;
Handler handler;
Runnable runnable;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
sample = findViewById(R.id.sample);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
counter++;
updateTextView("Counter: " + counter);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
public void updateTextView(String message) {
sample.setText(message);
}
But I tried it calling the sample.setText("Counter: "+counter) inside the Runnable Thread, it still works though.
Btw here is my sample.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/sample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="SAWSAW"
android:textColor="#000"
android:textSize="32dp" />
</LinearLayout>
I am trying to implement 360 Video Viewer in my project but I am getting an error for the line:
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
This is the error
Method loadVideoFromAsset must be called from the UI thread, currently inferred
thread is worker
Following is my code:
package com.example.jal.jp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import com.google.vr.sdk.widgets.video.VrVideoEventListener;
import com.google.vr.sdk.widgets.video.VrVideoView;
import java.io.IOException;
public abstract class VR_Video extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private VrVideoView mVrVideoView;
private SeekBar mSeekBar;
private Button mVolumeButton;
private boolean mIsPaused;
private boolean mIsMuted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vr__video);
initViews();
}
public void onPlayPausePressed() {
}
public void onVolumeToggleClicked() {
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
private void initViews() {
mVrVideoView = (VrVideoView) findViewById(R.id.video_view);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mVolumeButton = (Button) findViewById(R.id.btn_volume);
mVrVideoView.setEventListener(new ActivityEventListener());
mSeekBar.setOnSeekBarChangeListener(this);
mVolumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVolumeToggleClicked();
}
});
}
class VideoLoaderTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
try {
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_MONO;
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
} catch( IOException e ) {
//Handle exception
}
return true;
}
}
public void playPause() {
}
#Override
protected void onPause() {
super.onPause();
mVrVideoView.pauseRendering();
mIsPaused = true;
}
#Override
protected void onResume() {
super.onResume();
mVrVideoView.resumeRendering();
mIsPaused = false;
}
#Override
protected void onDestroy() {
mVrVideoView.shutdown();
super.onDestroy();
}
private class ActivityEventListener extends VrVideoEventListener {
#Override
public void onLoadSuccess() {
super.onLoadSuccess();
}
#Override
public void onLoadError(String errorMessage) {
super.onLoadError(errorMessage);
}
#Override
public void onClick() {
super.onClick();
}
#Override
public void onNewFrame() {
super.onNewFrame();
}
#Override
public void onCompletion() {
super.onCompletion();
}
}
}
Please help. I tried my best but couldn't fix.
Remove AsyncTask Implementation And Call Required Methods From UI Thread
Use Below Code :
private void initViews() {
mVrVideoView = (VrVideoView) findViewById(R.id.video_view);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mVolumeButton = (Button) findViewById(R.id.btn_volume);
mVrVideoView.setEventListener(new ActivityEventListener());
try {
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_MONO;
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
} catch( IOException e ) {
//Handle exception
}
mSeekBar.setOnSeekBarChangeListener(this);
mVolumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVolumeToggleClicked();
}
});
}
I dont know much about videoview but I show in your code that you are trying to access some the features in doInbackground method. The doINbackground method runs on a separate thread from the UI thread so that complex ant time consuming tasks do not block the UI thread. You can implement the features you are implementing in doINbackground method in the onCreate method or if you still need to use doInbackground you can access the UI thread inside doInbackground using runOnUiThread as follows
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code here
}
});
Hi All I am new to Android and I was building an English to German translator app and I am getting the above error for following the line of code:
Can please assist me how to resolve this issue.
package com.exmaple.android.lang_trans;
import java.util.Locale;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.exmaple.android.lang_trans.R;
import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;
public class MainActivity extends Activity implements OnInitListener {
private TextToSpeech tts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
((Button) findViewById(R.id.bSpeak)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
speakOut(((TextView) findViewById(R.id.tvTranslatedText)).getText().toString());
}
});
((Button) findViewById(R.id.bTranslate)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
class bgStuff extends AsyncTask<Void, Void, Void> {
String translatedText = "";
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
//below line is throwing the error
String text = ((EditText) findViewById(R.id.etUserText)).getText().toString();
translatedText = translate(text);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
translatedText = e.toString();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
((TextView) findViewById(R.id.tvTranslatedText)).setText(translatedText);
super.onPostExecute(result);
}
}
new bgStuff().execute();
}
});
}
public String translate(String text) throws Exception {
// Set the Client ID / Client Secret once per JVM. It is set statically and applies to all services
Translate.setClientId("CLIENT ID"); //Change this
Translate.setClientSecret("CLIENT SECRET"); //change
String translatedText = "";
translatedText = Translate.execute(text, Language.GERMAN);
return translatedText;
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.GERMAN);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
//speakOut("Ich");
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
Your problem is that you are accessing your UI element in a thread other than the UI thread which android system does not allow
you cannot update the UI from any thread other than the UI thread or the "main" thread.
https://developer.android.com/guide/components/processes-and-threads.html#WorkerThreads
So you could change your onClick function to the following :
((Button) findViewById(R.id.bTranslate)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
class bgStuff extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
if (params.length > 0) {
return translate(params[0]);
}
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
return null;
}
#Override
protected void onPostExecute(String result) {
((TextView) findViewById(R.id.tvTranslatedText)).setText(result);
}
}
new bgStuff().execute(((EditText) findViewById(R.id.etUserText)).getText().toString());
}
});
This is my MainActivity... i put one button, in button onclick i call asyncTask
package com.example.asnytaskpro;
import java.util.concurrent.ExecutionException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AsyncMainActivity extends Activity implements OnClickListener {
Button button ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_async, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.err.println("1");
try {
new AllPrinterClass(AsyncMainActivity.this, "123456789123456789", "123").execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
}
This is My AsyncTaskClass
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.widget.Toast;
public class AllPrinterClass extends AsyncTask<Integer, Integer, Integer>{
public static String ServerData = "";
private ProgressDialog prgDialog;
private Context context;
String TransNo = "" ,IMEINo = "";
int iRetValue = 0;
String CurrentDate = null, CurrentTime= null;
SimpleDateFormat df,tf;
public AllPrinterClass(Context context1, String imeiNo,String transno2)
{
this.context = context1;
this.IMEINo = imeiNo;
this.TransNo = transno2;
Calendar c = Calendar.getInstance();
df = new SimpleDateFormat("dd/M/yyyy");
CurrentDate = df.format(c.getTime());
tf = new SimpleDateFormat("hh:mm:ss");
CurrentTime = tf.format(c.getTime());
System.err.println(CurrentDate);
System.err.println(CurrentTime);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.prgDialog = new ProgressDialog(context);
this.prgDialog.setMessage("Place your finger on FPS ...");
this.prgDialog.setIndeterminate(true);
this.prgDialog.setCancelable(false);
this.prgDialog.show();
}
#Override
protected Integer doInBackground(Integer... params) {
//////////////////Doing my Code///////////////////
for (int i = 0; i < 10; i++) {
System.err.println("i :-" + i);
SystemClock.sleep(500);
}
/////////////////////////////////////////////////////
return iRetValue;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prgDialog.dismiss();
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
}
}
This code working for me but my ProgressDialog not showing(May be run background).
In i remove prgDialog.dismiss(); in onPostExecute() Method then my dialog showing after doInBackground() Method.
I want dialog show in onPreExecute() Method and dismiss in onPostExecute() method.
Here:
...execute().get();
Calling get method will block main ui Thread until doInBackground execution not completed. that's why ProgressDialog is not showing.
Use only execute() method to start AsyncTask which show Progress Dialog during doInBackground method execution:
new AllPrinterClass(AsyncMainActivity.this,
"123456789123456789", "123").execute();
I'm simply loading an image on button click via url , i want progress bar to show downloadin done,0-100 now i had changed the code not showing the progress updation but only progress bar
kindly help. XML has a button [downloadbtn], and a progressbar, imageview and a quit button
mainfest.xml has acsess permission internet
code:
*
package com.example.t4;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ProgressBar prgs;
ProgressTask task = new ProgressTask();
Button showProgressBtn;
Button stopProgressBtn;
ImageView img;
Bitmap bmp ;
TextView tv1;
int filesize,filedyn;
public void startdownload(){
try { URL url;
url = new URL("http://whywedoit.files.wordpress.com/2009/04/smile.jpg");
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
filesize = urlConnection.getContentLength();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.tv1);
img = (ImageView) findViewById(R.id.imageView1) ;
stopProgressBtn = (Button) findViewById(R.id.btnCancel);
prgs = (ProgressBar) findViewById(R.id.progress);
showProgressBtn = (Button) findViewById(R.id.btn);
prgs.setVisibility(View.INVISIBLE);
img.setVisibility(View.INVISIBLE);
tv1.setVisibility(View.INVISIBLE);
final ProgressTask pgt = new ProgressTask();
showProgressBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(pgt.getStatus()==Status.RUNNING){Toast.makeText(getApplicationContext(), "Status"+pgt.getStatus(), Toast.LENGTH_SHORT).show();}
if(pgt.getStatus()==Status.FINISHED||pgt.getStatus()==Status.PENDING){
Toast.makeText(getApplicationContext(), "Status"+pgt.getStatus(), Toast.LENGTH_SHORT).show();
prgs.setVisibility(View.VISIBLE);
task.execute(10);
tv1.setVisibility(View.VISIBLE);
}}
});
stopProgressBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
stopProgress();
}
});
}
private class ProgressTask extends AsyncTask<Integer,Integer,Void>{
protected void onPreExecute() {
super.onPreExecute();
prgs.setMax(100); // set maximum progress to 100.
}
protected void onCancelled() {
prgs.setMax(0); // stop the progress
Log.v("Progress","Cancelled");
finish();
}
protected Void doInBackground(Integer... params) {
startdownload();
//for(int j=0;j<=filesize;j++){
publishProgress((int) ((filedyn / (float) filesize) * 100));
//}
Log.v("Progress","Downloading");
return null;
}
protected void onProgressUpdate(Integer... values) {
prgs.setProgress(0);
Log.v("Progress","Updating");
}
protected void onPostExecute(Void result) {
img.setVisibility(View.VISIBLE);
tv1.setVisibility(View.INVISIBLE);
img.setImageBitmap(bmp);
prgs.setVisibility(View.INVISIBLE);
Log.v("Progress", "Finished");
}
}
public void stopProgress() {
task.cancel(true);
}
}
*
Sorry, I don't think you only have progress bar update problems. There are too many points needs to be repaired.
1st inside your OnClickListener, you are doing task.execute(10);showProgress(); AsnycTask is asynchronous task, you cannot put your showProgress() there. Do something with your code.
private boolean init = true;
private Void doInBackground(Integer... params) {
init = true;
startdownload();
Log.v("Progress", "Downloading");
return null;
}
protected void onProgressUpdate(Integer... values) {
if (init){
showProgress();
init = false;
}else{
prgs.setProgress(5);
Log.v("Progress", "Once");
}
}
2nd startdownload method, are you sure your startdownload method doing downloading? or just getting the length of filesize. Make it clear else you will get yourself confuse.
3nd To invoke onProgressUpdate, you need to call publishProgress(progressValue); Here's the sample.
private Void doInBackground(Integer... params) {
init = true;
startdownload();
publishProgress(5); // onProgressUpdate invoked
//
// doing download
//
Log.v("Progress", "Downloading");
return null;
}
use this code and use progressdialog instead of progressbar
#Override
protected void onProgressUpdate(Integer... progress) {
//Set the pertange done in the progress dialog
pd.setProgress((int) (progress[0]));
}
You need set the ProgressBar max value and you need to update the progress in onProgressUpdate
protected void onProgressUpdate(Integer... values) {
prgs.setProgress(values[0]);
Log.v("Progress","Once");
}
and call
publishProgress(progress)
in the doInBackground of ProgressTask to update the progress
Check for more ref