showing imported data on progress bar - android

I am working on Address book app in android.In my application i import contacts from phonebook in my app.while importing i am showing progress bar.I want to show the contacts being imported on the progressbar while importing.how to do this?
following is my code:-
public class Task extends AsyncTask<String, Integer, Void> {
private ProgressDialog dialog;
protected Context applicationContext;
#Override
protected void onPreExecute()
{
System.out.println("IN PreExecute");
this.dialog = ProgressDialog.show(applicationContext, "Importing Contacts", "Please Wait...", true);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println("IN BACKGROUND");
addcontacts();//return flag1;
//dialog.setMessage(name);
return null ;
}
protected void onProgressUpdate(String... progress)
{
System.out.println("IN update");
}
#Override
protected void onPostExecute(Void unused) {
this.dialog.cancel();
System.out.println("IN PostExecute");
final AlertDialog.Builder alertbox1=new AlertDialog.Builder(Import.this);
Cursor c=data.getData();
int num=c.getCount();
alertbox1.setMessage(+num+" contacts imported");
c.close();
// set a positive/yes button and create a listener
alertbox1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1)
{
call();
}
});
alertbox1.show();
}

onProgressUpdate gets called every time we call publishProgress and the arguments from publishProgress go to onProgressUpdate
So in doInBackground() you can do
protected Void doInBackground(String... params) {
for(int i=1; i<=totalContacts; ++i) {
importNextContact();
publishProgress(i/(float)totalContacts)*100);
}
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}

Using dialog.setMessage("msg") is correct but remember that you can not change the ui in the
doInBackground(...) method, so either you post a msg using an handler or you use runOnUiThread.

Related

WindowManager$BadTokenException near dialog.show in AsyncTask android

How to show a dialog box in AsyncTask. Getting BadToketException in dialog.show();
I tried many ways but I could not solve it.
Also tried to pass context to the dialog box in different ways, but it is giving me the same result.
public class RetriveStock extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
message = client.clientReceive(1); // I get data here.
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
if (message.contains("AlertExecuted:")) {
final Dialog dialog = new Dialog(CreateAlert.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.display_dialog);// Dialog layout
TextView dialogText = (TextView) dialog.findViewById(R.id.digMsg);
dialogText.setText("Alert Executed!");
Button ok = (Button) dialog.findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
try {
dialog.show(); //WindowManager$BadTokenException
} catch (Exception e) {
e.printStackTrace();
}
}
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Please help.
protected void onPreExecute() {
// TODO Auto-generated method stub
// progressDialog = ProgressDialog.show(this, "", "loading news content");
progressDialog = new ProgressDialog(context , AlertDialog.THEME_HOLO_LIGHT);
progressDialog.setMessage(""+getString(R.string.laodnews));
progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.animate));
progressDialog.setCancelable(false);
progressDialog.show();
}
start dailoge in pre execute and stop in onpostexecute..
is CreateAlert registered activity in manifest..if not then you have to pass registered activity context

Android - Loader for 1 record

Which is the best way to load the data for a single item (read only) detail activity?
Should i use LoaderManager or directly AsyncTask?
Use an Asyntask for best result:
Public class example extends AsyncTask<Void,Void,Void>
{
private ProgressDialog dialog;
public example(Context context){
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
dialog.setTitle("Demo");
dialog.setMessage("Please Wait..");
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
}
}

Android: Is not showing ProgressDialog

I have AsynTask and show progress dialoge while it is running. Phone receive incoming call. After call stopped the progress dialoge is not showing but the activity layout is dim in such way if the dialoge is showing. Has you any ideas?
I have somethin like this:
Recovery recovery=new Recovery();
recovery.execute();
And asynktask:
public class Recovery extends AsyncTask<String, Void, Integer>{
#Override
protected Integer doInBackground(String... uri) {
publishProgress();
//some code
return Ret;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
showDialog(RECOVERY);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
dismissDialog(RECOVERY);
}
}
use this way it works
ProgressDialog dialog = new ProgressDialog(YourActivity.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Loading Please Wait...");
this.dialog.show()
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}

Progress bar doesn't update

I created a Progress bar but I can't see the loading animation. It's frozen. I want to display a progress bar when I click on the item and then see the bar working and not frozen. Here is my code:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (((TextView) view).getText().equals("Zman-New (rus)")){
progDailog = ProgressDialog.show(testLoading.this, "Getting data", "Loading...",true,true);
new GetDataTask("stringurl.xml").execute();
}
Here is the getdata
private class GetDataTask extends AsyncTask<Void, Void, Integer> {
String url;
GetDataTask(String url){
this.url=url;
}
#Override
protected Integer doInBackground(Void... params) {
//do all your backgroundtasks
intent = new Intent(rusNewsP.testLoading.this, rusNewsTest.rusNewsActivite.class);
intent.putExtra("url",url);
startActivity(intent);
finish();
return 1;
}
#Override
protected void onPostExecute(Integer result) {
//finish up ( or close the progressbar )
//do something with the result
progDailog.dismiss();
super.onPostExecute(result);
}
}
If you just want to test Progress try this:
private class Initialize extends AsyncTask<Short, Short, Short> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(yourlass.this);
pd.setMessage("test");
pd.show();
super.onPreExecute();
}
#Override
protected Short doInBackground(Short... params) {
try {
synchronized (this) {
wait(2000);
}
} catch (InterruptedException ex) {
}
return null;
}
#Override
protected void onPostExecute(Short result) {
pd.dismiss();
super.onPostExecute(result);
}
}
And don't call startActivity in the doInBackground-Method. Call it in OnPostExecute instead. GUI Operations should not be done in doInBackground.
Try to start the Activity Direct from the UI thread as that will be fast.
Still,if you want this way then try to start it from the onPostExecute Method.
Not from the doInBackground.
protected void onPostExecute(Integer result)
{
//do something with the result
progDailog.dismiss();
intent=new Intent(rusNewsP.testLoading.this,rusNewsTest.rusNewsActivite.class);
intent.putExtra("url",url);
startActivity(intent);
finish();
}
And...don't call super.onPostExecute(result); after dismissing the progressDialog..after completing the doInBackground(Short... params),It will return directly to onPostExecute Method where it will dismiss the ProgressDialog first time and then execute the Constructor which will try again to dismiss the ProgressDialog which is already dismissed resulting into uncaught exception.

Dismiss a dialog when a thread is done

I'm creating a thread in android for a time consuming operation. I want the main screen to show a progress dialog with a message informing that the operation is in progress, but I want that dialog to dismiss once the thread is done. I've tried with join but it locks the thread and doesn't show the dialog. I tried using:
dialog.show();
mythread.start();
dialog.dismiss();
but then the dialog doesn't show. How can I make that sequence but wait for the thread to end without locking the main thread?
This is as far as I got:
public class syncDataElcanPos extends AsyncTask<String, Integer, Void> {
ProgressDialog pDialog;
Context cont;
public syncDataElcanPos(Context ctx) {
cont=ctx;
}
protected void onPreExecute() {
pDialog = ProgressDialog.show(cont,cont.getString(R.string.sync), cont.getString(R.string.sync_complete), true);
}
protected Void doInBackground(String... parts) {
// blablabla...
return null;
}
protected void onProgressUpdate(Integer... item) {
pDialog.setProgress(item[0]); // just for possible bar in a future.
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
But when I try to execute it, it gives me an exception: "Unable to add window".
When your thread is done, use the runOnUIThread method to dismiss the dialog.
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
To do that there is two ways to do it , ( and i prefer the first second one : AsyncTask ) :
First : you display your alertDialog , and then on the method run() you should do like this
#override
public void run(){
//the code of your method run
//....
.
.
.
//at the end of your method run() , dismiss the dialog
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
Second : Using an AsyncTask like this :
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
//create and display your alert here
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Downloading data ...", true);
}
protected Void doInBackground(Void... unused) {
// here is the thread's work ( what is on your method run()
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
//dismiss the alert here where the thread has finished his work
pDialog.dismiss();
}
}
well in AsyncTask in the on postexecute you can call dismiss
here is an example from other thread
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Retrieving data ...", true);
}
protected Void doInBackground(Void... unused) {
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}

Categories

Resources