Updating the Progress Bar in the list view - android

I have a scenario, In my chat application I want to send photos, photos sending takes time. I have attached a progress bar( horizontal) to show the progress of sending the photo in my application. But I am unable to update the progress bar as it is the item of the custom list view.
Here is my asynchtask to set the progress for Progress Bar but I am not able to get it.
class SendPhotoToFriend extends AsyncTask<String, String, String>{
String receiver,path = "";
public SendPhotoToFriend(String path,String receiver) {
// TODO Auto-generated constructor stub
this.path = path;
this.receiver = receiver;
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(connection);
if (sdm == null)
sdm = new ServiceDiscoveryManager(connection);
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
// Create the file transfer manager
FileTransferManager manager = new FileTransferManager(
connection);
FileTransferNegotiator.setServiceEnabled(connection, true);
// Create the outgoing file transfer
OutgoingFileTransfer transfer = manager
.createOutgoingFileTransfer(receiver + "/Smack");
System.out.println("Receiver of the file is "+receiver+"/smack");
Log.i("transfere file", "outgoingfiletransfer is created");
try {
long total = 0;
OutgoingFileTransfer.setResponseTimeout(30000);
transfer.sendFile(new File(path), "Description");
Log.i("transfere file", "sending file");
while (!transfer.isDone()) {
//Thread.sleep(1000);
total+=transfer.getProgress();
publishProgress(""+(int)((total*100)/transfer.getFileSize()));
Log.i("transfere file", "sending file status "
+ transfer.getStatus() + "progress: "
+ transfer.getProgress());
if (transfer.getStatus() == org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error) {
Log.i("transfere file", "Errorrr isss: "
+ transfer.getError()+transfer.getPeer());
transfer.cancel();
break;
}
}
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("transfere file", "sending file done");
return null;
}
#Override
protected void onProgressUpdate(final String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view =inflater.inflate(R.layout.user_chat_send_chat, null);
ProgressBar p_Bar = (ProgressBar)view.findViewById(R.id.progress_bar_image);
p_Bar.setProgress(Integer.parseInt(values[0]));
customAdapter1.notifyDataSetChanged();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
The progress Bar is the view of the custom list view, I want to update it at the run time.
Thanks

You're inflating the ProgressBar within the onProgress callback. This is absolutely wrong. The ProgressBar should to be added to the view before your AsyncTask starts (inflate and add) and then turn it to be visibile in your AsyncTask constructor. You should also store a reference to the ProgressBar in the AsyncTask (or somehow else in scope by non-static inner class).
In the end your AsyncTask should be looking like this (assuming the ProgressBar is already attached to the view):
class SendPhotoToFriend extends AsyncTask<String, String, String> {
String receiver,path = "";
ProgressBar progress;
public SendPhotoToFriend(String path, String receiver, ProgressBar progress) {
this.path = path;
this.receiver = receiver;
this.progress = progress;
this.progress.setVisibility(View.Visible);
}
#Override
protected String doInBackground(String... arg0) {
// You're application logic...
// ...
publishProgress((int)((total*100)/transfer.getFileSize()));
// ...
}
#Override
protected void onProgressUpdate(final Integer... values) {
this.progress.setProgress(values[0]);
}
}
Also you don't need to (and shouldn't) call adapter.notifiyDataSetChanged() in your onProgres-Callback.

I suppose each list item view has a progress bar, if that is the case, you can use getView to get the view for that position, and then call:
View view = customAdapter1.getView(position, convertView, parent);
ProgressBar p_Bar = (ProgressBar)view.findViewById(R.id.progress_bar_image);
p_Bar.setProgress(Integer.parseInt(values[0]));
No need to call customAdapter1.notifyDataSetChanged();

Related

how to make one asynctask to start after the other one?

what i have is two asynctask each one call a function to parse some data ... and i want the asynctask starts after asynctasknew finish how can i do this??? here is my code ..
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AsyncCallWS task = new AsyncCallWS();
try{
Intent newintent = getIntent();
mixlist=newintent.getStringArrayListExtra("listmix");
Log.e("listmix",mixlist+"");
for(int i=0;i<=mixlist.size();i++){
if(i==mixlist.size()){
Log.d("states","finished");
Item_Name="0";
Item_Price="0";
Item_Quantity="0";
Total_Price="0";
Customer_Name=name.getText().toString();
Log.e("customer_name",Customer_Name);
Customer_Number=mobile.getText().toString();
Customer_Address=addressnew.getText().toString();
//Call execute
task.execute();
}
else{
Item_Name=mixlist.get(i);
i++;
Item_Price=mixlist.get(i);
i++;
Item_Quantity=mixlist.get(i);
i++;
Total_Price=mixlist.get(i);
Customer_Name="0";
Customer_Number="0";
Customer_Address="0";
// AsyncCallWSnew tasknew = new AsyncCallWSnew();
//Call execute
AsyncCallWSnew tasknew = new AsyncCallWSnew();
tasknew.execute();
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(Void result) {
//Make Progress Bar invisible
Toast.makeText(getApplicationContext(), "order has been sent + item price", Toast.LENGTH_LONG).show();
Intent intObj = new Intent(PersonalInfo.this,MainActivity.class);
startActivity(intObj);
//Error status is false
}
//Make Progress Bar visible
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
loginStatus = WebService.invokeLoginWS(Item_Name,Item_Price,Item_Quantity, Total_Price, Customer_Name,
Customer_Number, Customer_Address,"InsertData");
return null;
}
}
private class AsyncCallWSnew extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(Void result) {
//Make Progress Bar invisible
Toast.makeText(getApplicationContext(), "order has been sent", Toast.LENGTH_LONG).show();
Intent intObj = new Intent(PersonalInfo.this,MainActivity.class);
startActivity(intObj);
//Error status is false
}
//Make Progress Bar visible
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
loginStatus = WebService.invokeLoginWS(Item_Name,Item_Price,Item_Quantity, Total_Price, Customer_Name,
Customer_Number, Customer_Address,"InsertData");
return null;
}
}
}
when i make a debug my code works just fine .. but in normal run .. it doesn't can any help me?
There are basically two possibilities:
Simply start the next AsyncTask from onPostExecute() of the previous one
Use AsyncTask.executeOnExecutor() with SerialExecutor and start all of them in a row.
Hi You can use AsyncTask executeonExecutor method to start the async task. But it will require minimum API version 11. Kindly refer the following code.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new YourFirstTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params...);
new YourSecondTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params...);
}else{
new YourFirstTask().execute(params...);
new YourSecondTask().execute(params...);
}
For Lower version you can call directly. automatically system will process one by one.

ProgressDialog is not showing when .3gp file converting to a .zip

I am working on Android app.
I need to show a progress dialog box when I click on button.
In that button I am converting video file to .zip file and calculating that file size.
In this process I need to show a ProgressDialog, but it is not showing.
Screen get struck while calculating and after calculation it shows ProgressDialog and then screen navigating to the next screen.
My Code:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaCheck.this.runOnUiThread(new Runnable() {
public void run() {
pd = ProgressDialog.show(MediaCheck.this, "",
"Checking the video compatability. Please wait", true);
}
});
video_Path= makeZip(video_Path);
if (video_Path.equalsIgnoreCase("File size is too large")) {
pd.dismiss();
Toast.makeText(getApplicationContext(),
"Large video", Toast.LENGTH_LONG)
.show();
return;
}
pd.dismiss();
// Doing screen navigation here.
}
});
Code to make a zip and know the size
private static String makeZip(String videoPath) {
byte[] buffer = new byte[1024];
String[] videoFileName = videoPath.split("/");
File directory = null;
try {
ContextWrapper cw = new ContextWrapper(context_this);
// path to /data/data/yourapp/app_data/imageDir
directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
FileOutputStream fos = new FileOutputStream(directory
+ "/IRCMS_Video.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = null;
ze = new ZipEntry(videoFileName[5]);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(videoPath);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
File videoZip = new File(directory + "/IRCMS_Video.zip");
videoLength = videoZip.length() / (1024 * 1024);
if (videoLength > 3)
return "File size is too large";
in.close();
zos.closeEntry();
// remember close it
zos.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
return directory.toString() + "/IRCMS_Video.zip";
}
}
Please help...
then you should try ASYNCTASK to easily perform your operation and reduce the complexity of using threads
private class Converter extends AsyncTask<String, Void, Void> { //Converter is class name
protected String doInBackground(String... urls) {
//THIS METHOD WILL BE CALLED AFTER ONPREEXECUTE
//YOUR NETWORK OPERATION HERE
return null;
}
protected void onPreExecute() {
super.onPreExecute();
//THIS METHOD WILL BE CALLED FIRST
//DO OPERATION LIKE SHOWING PROGRESS DIALOG PRIOR TO BEGIN NETWORK OPERATION
}
protected void onPostExecute(String result) {
super.onPostExecute();
//TNIS METHOD WILL BE CALLED AT LAST AFTER DOINBACKGROUND
//DO OPERATION LIKE UPDATING UI HERE
}
}
You are doing calculation on UI thread therfore it hangs your app. Do calculation on background thread. You can resolve this by-
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pd = ProgressDialog.show(MediaCheck.this, "",
"Checking the video compatability. Please wait", true);
Thread background = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
video_Path= makeZip(video_Path);
MediaCheck.this.runOnUiThread(new Runnable()
{
public void run()
{
if (video_Path.equalsIgnoreCase("File size is too large")) {
pd.dismiss();
Toast.makeText(getApplicationContext(),
"Large video", Toast.LENGTH_LONG)
.show();
pd.dismiss();
return;
}
}
});
}
});
background.start();
// Doing screen navigation here.
}
});

AsyncTask.get() no progress bar

My app sends data to the server. It generally works fine until the user is in a bad signal area. If the user is in a good signal area the the following code works fine and the data is sent.
String[] params = new String[]{compID, tagId, tagClientId, carerID,
formattedTagScanTime, formattedNowTime, statusForWbService, getDeviceName(), tagLatitude, tagLongitude};
AsyncPostData apd = new AsyncPostData();
apd.execute(params);
.
private class AsyncPostData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String dateTimeScanned;
#Override
protected void onPreExecute()
{
// progressDialog= ProgressDialog.show(NfcscannerActivity.this,
// "Connecting to Server"," Posting data...", true);
int buildVersionSdk = Build.VERSION.SDK_INT;
int buildVersionCodes = Build.VERSION_CODES.GINGERBREAD;
Log.e(TAG, "buildVersionSdk = " + buildVersionSdk
+ "buildVersionCodes = " + buildVersionCodes);
int themeVersion;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
themeVersion = 2;
}else{
themeVersion = 1;
}
progressDialog = new ProgressDialog(NfcscannerActivity.this, themeVersion);
progressDialog.setTitle("Connecting to Server");
progressDialog.setMessage(" Sending data to server...");
progressDialog.setIndeterminate(true);
try{
progressDialog.show();
}catch(Exception e){
//ignore
}
};
#Override
protected String doInBackground(String... params) {
Log.e(TAG, "carerid in doinbackground = " + params[3] + " dateTimeScanned in AsyncPost for the duplecate TX = " + params[4]);
dateTimeScanned = params[4];
return nfcscannerapplication.loginWebservice.postData(params[0], params[1], params[2], params[3], params[4],
params[5], params[6], params[7] + getVersionName(), params[8], params[9]);
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try{
progressDialog.dismiss();
}catch(Exception e){
//ignore
}
if( result != null && result.trim().equalsIgnoreCase("OK") ){
Log.e(TAG, "about to update DB with servertime");
DateTime sentToServerAt = new DateTime();
nfcscannerapplication.loginValidate.updateTransactionWithServerTime(sentToServerAt,null);
nfcscannerapplication.loginValidate.insertIntoDuplicateTransactions(dateTimeScanned);
tagId = null;
tagType = null;
tagClientId = null;
//called to refresh the unsent transactions textview
onResume();
}else if(result != null && result.trim().equalsIgnoreCase("Error: TX duplicated")){
Log.e(TAG, "response from server is Duplicate Transaction ");
//NB. the following time may not correspond exactly with the time on the server
//because this TX has already been processed but the 'OK' never reached the phone,
//so we are just going to update the phone's DB with the DupTX time so the phone doesn't keep
//sending it.
DateTime sentToServerTimeWhenDupTX = new DateTime();
nfcscannerapplication.loginValidate.updateTransactionWithServerTime(sentToServerTimeWhenDupTX,null);
tagId = null;
tagType = null;
tagClientId = null;
}else{
Toast.makeText(NfcscannerActivity.this,
"No phone signal or server problem",
Toast.LENGTH_LONG).show();
}
}
}//end of AsyncPostData
.
The app in bad signal areas tends to show the progress bar for a few minutes before showing a black screen for a while rendering the app unusable.
I thought a way around this would be to do the following.
String[] params = new String[]{compID, tagId, tagClientId, carerID,
formattedTagScanTime, formattedNowTime, statusForWbService, getDeviceName(), tagLatitude, tagLongitude};
AsyncPostData apd = new AsyncPostData();
try {
apd.execute(params).get(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This will cause the AsyncTask to cancel after 10 seconds, but as it is executing there is a black screen until the data is sent followed by the progressbar for a few millisecs.
Is there a way to show the progressbar whilst executing an AsyncTask.get()?
thanks in advance. matt.
Also are there any ideas why the black screen comes when the user is in bad signal area and therefor no response from the server. This senario seems to cause the app alot of problems where it's behavior is unusual afterwards like sending extra transactions at a later date.
[edit1]
public class SignalService extends Service{
NfcScannerApplication nfcScannerApplication;
TelephonyManager SignalManager;
PhoneStateListener signalListener;
private static final int LISTEN_NONE = 0;
private static final String TAG = SignalService.class.getSimpleName();
#Override
public void onCreate() {
super.onCreate();
// TODO Auto-generated method stub
Log.e(TAG, "SignalService created");
nfcScannerApplication = (NfcScannerApplication) getApplication();
signalListener = new PhoneStateListener() {
public void onSignalStrengthChanged(int asu) {
//Log.e("onSignalStrengthChanged: " , "Signal strength = "+ asu);
nfcScannerApplication.setSignalStrength(asu);
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
Log.e(TAG, "SignalService destroyed");
SignalManager.listen(signalListener, LISTEN_NONE);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
// TODO Auto-generated method stub
Log.e(TAG, "SignalService in onStart");
SignalManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
SignalManager.listen(signalListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTH);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You do not need a timer at all to do what you're attempting (for some reason I thought you were trying to loop the AsyncTask based on your comments above which resulted in mine.). If I understand correctly you're issue is with the loss of service. You have an AsyncTask that you start which may or may not finish depending on certain conditions. Your approach was to use get and cancle the task after a fixed time in the event that it did not finish executing before then - the assumption being if the task didn't finish within the 10 second cut off, service was lost.
A better way to approach this problem is to use a boolean flag that indcates whether network connectivity is available and then stop the task from executing if service is lost. Here is an example I took from this post (I apologize for the formatting I'm on a crappy computer with - of all things - IE8 - so I can't see what the code looks like).
public class MyTask extends AsyncTask<Void, Void, Void> {
private volatile boolean running = true;
private final ProgressDialog progressDialog;
public MyTask(Context ctx) {
progressDialog = gimmeOne(ctx);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// actually could set running = false; right here, but I'll
// stick to contract.
cancel(true);
}
});
}
#Override
protected void onPreExecute() {
progressDialog.show();
}
#Override
protected void onCancelled() {
running = false;
}
#Override
protected Void doInBackground(Void... params) {
while (running) {
// does the hard work
}
return null;
}
// ...
}
This example uses a progress dialog that allows the user to cancle the task by pressing a button. You're not going to do that but rather you're going to check for network connectivty and set the running boolean based on whether your task is connected to the internet. If connection is lost - running will bet set to false which will trip the while loop and stop the task.
As for the work after the task complete. You should NEVER use get. Either (1) put everything that needs to be done after the doInBackgroundCompletes in onPostExecute (assuming its not too much) or (2) if you need to get the data back to the starting activity use an interface. You can add an interface by either adding as an argument to your tasks constructor or using a seperate method that sets the interface up. For example
public void setInterface(OnTaskComplete listener){
this.listener = listener;
}
Where OnTaskComplete listener is declared as an instance variable in your AsyncTask. Note the approach I am describing requires using a seperate AsyncTask class. Your's is private right now which means you need to change your project a little.
UPDATE
To check connectivity I would use something like this.
public boolean isNetworkOnline() {
boolean status=false;
try{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
status= true;
}else {
netInfo = cm.getNetworkInfo(1);
if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
status= true;
}
}catch(Exception e){
e.printStackTrace();
return false;
}
return status;
}
You can check to see if there is an actual network connection over which your app can connect to ther server. This method doesn't have to be public and can be part of you're AsyncTask class. Personally, I use something similar to this in a network manager class that I use to check various network statistics (one of which is can I connect to the internet).
You would check connectivity before you started executing the loop in your doInBackground method and then you could periodicly update throughout the course of that method. If netowkr is available the task will continue. If not it will stop.
Calling the AsyncTask built in cancle method is not sufficient becuase it only prevent onPostExecute from running. It does not actually stop the code from execting.

Android - Progress Dialog

I'm a having a problem. I want to make a progress dialog while my app download some news from a feed.
This is my code at the moment:
public class NyhedActivity extends Activity {
String streamTitle = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nyheder);
TextView result = (TextView)findViewById(R.id.result);
try {
URL rssUrl = new URL("http://rss.tv2sport.dk/rss/*/*/*/248/*/*");
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
result.setText(streamTitle);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.setText("Cannot connect RSS!");
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.setText("Cannot connect RSS!");
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.setText("Cannot connect RSS!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.setText("Cannot connect RSS!");
}
}
private class RSSHandler extends DefaultHandler
{
final int stateUnknown = 0;
final int stateTitle = 1;
int state = stateUnknown;
int numberOfTitle = 0;
String strTitle = "";
String strElement = "";
#Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
strTitle = "Nyheder fra ";
}
#Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
strTitle += "";
streamTitle = "" + strTitle;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("title"))
{
state = stateTitle;
strElement = "";
numberOfTitle++;
}
else
{
state = stateUnknown;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("title"))
{
strTitle += strElement + "\n"+"\n";
}
state = stateUnknown;
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
String strCharacters = new String(ch, start, length);
if (state == stateTitle)
{
strElement += strCharacters;
}
}
}
}
I can't figure out how to use the progress dialog. Is it possible for anyone to show my where to define the progressdialog and least but not most how to implement it.
I've looked a lot of places, but everyone seems to do it different ways, and I can't get any of them to work :(
I've even tried to make a fake one which runs on sleep, but I can't figure out what I'm doing wrong.
My preferred way:
class MyActivity extends Activity{
final static int PROGRESS_DIALOG = 1;
ProgressDialog dialog;
#Override
protected Dialog onCreateDialog(int id){
switch(id){
case PROGRESS_DIALOG:
dialog = new ProgressDialog(this);
dialog.setMessage("Whatever you want to tell them.");
dialog.setIndeterminate(true);
dialog.setCancelable(true); // if you want people to be able to cancel the download
dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog)
{
**** cleanup. Not needed if not cancelable ****
}});
return dialog;
default:
return null;
}
}
When you want it to appear, you can do showDialog(PROGRESS_DIALOG) and when you want it to go away you can do dialog.dismiss().
Don't do any long-running stuff like network IO in the UI thread (that's what calls your onCreate()), Android will force close your app. Use an AsyncTask instead, check out the linked javadoc for an example.
Create and show your progress dialog in onPreExecute() and keep a reference to it in a field
Update progress by calling publishProgress() from your doInBackground() and handle that in onProgressUpdate(), e.g. like the example linked above
Close your progress dialog and update your UI (text fields, etc.) in onPostExecute()
To create the dialog in onPreExecute(), pass a Context to your AsyncTask constructor, e.g. your activity this and store it in a field.
If you want your data to survive orientation changes or persist across activity restarts, let your AsyncTask write your parsed data into a SQLite database and then display it only the database contents in your activity.
As for the actual "showing a progress dialog" part, use one of its static factory methods show(...):
ProgressDialog dialog = ProgressDialog.show(
this, // a context, e.g. your activity
"Downloading...", // title
"Downloading RSS feed.", // message
);
This will create and show a dialog in one step.

View ProgressBar on Gallery Intent

I'm using these codes to view an image from my application:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(imgFile), "image/*");
startActivity(intent);
I have no problem viewing the picture but when the size is a little bit larger, the intent keeps blank until the image is ready to load and show.
My question is, how can I show a ProgressBar, or in more advanced way, show a temporary image, before the real image get shown?
Thanks for the answer.
Try Asynctask as shown here:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code of UI operation
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}
Also refer to this link: Fetch data from server and refresh UI when data is fetched?:)

Categories

Resources