Horizontal ProgressDialog not shown in android - android

I have the MainActivity as this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bo = new Operation(getApplicationContext());
}
public void op_perform(View v) throws Exception { //call this when a button is pressed
try {
bo.demo();
} catch (Exception e) {
// TODO: handle exception
}
The Operation class has the following lines of code:
Context con;
Operation(Context ac) {
con = ac;
barProgressDialog = new ProgressDialog(con);
updateBarHandler = new Handler();
}
public void demo() {
barProgressDialog = new ProgressDialog(con);
barProgressDialog.setTitle("Downloading Image ...");
barProgressDialog.setMessage("Download in progress ...");
barProgressDialog.setProgressStyle(barProgressDialog.STYLE_HORIZONTAL);
barProgressDialog.setProgress(0);
barProgressDialog.setMax(20);
barProgressDialog.show();
...
But, i'm not getting the progress dialog at all in my screen. I want the progress dialog to be a determinate horizontal one. This is just a piece of code and i need to put these in the Asyn task. But the processdialog is not even showing. Recommended solutions. I'm a beginner to android.

Here is a complete example of what you need: http://turboprogramacion.blogspot.cl
private ProgressDialog barraProgreso;
private Handler handler;
private void mostrarBarraProgreso(){
barraProgreso = new ProgressDialog(MainActivity.this);
barraProgreso.setTitle("Buscando...");
barraProgreso.setMessage("Progreso...");
barraProgreso.setProgressStyle(barraProgreso.STYLE_HORIZONTAL);
barraProgreso.setProgress(0);
barraProgreso.setMax(10);
barraProgreso.show();
handler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
try {
while (barraProgreso.getProgress() <= barraProgreso.getMax()) {
Thread.sleep(1000);
handler.post(new Runnable() {
#Override
public void run() {
barraProgreso.incrementProgressBy(1);
}
});
if(barraProgreso.getProgress() == barraProgreso.getMax()){
barraProgreso.dismiss();
}
}
}catch (InterruptedException er){
er.printStackTrace();
}
}
}).start();
}

Related

Android update ProgressBar with Handler

I would like to update the progressBar with Handler and for loop but without success.
Code:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(progress_k, 100);
}
}, 2000);
}
}
Question:
The progress bar increase immediately to the end value instead of progressively.
Why?
Try this:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
final int curr_progress_k = progress_k;
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(curr_progress_k, 100);
}
}, progress_k * 100); // adjust "100" value to adjust speed
}
}
Repeat a task with a time delay?
#inazaruk
private ProgressBar progressBar;
private Handler mHandler;
private int progressInt = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
progressBar = (ProgressBar) findViewById(R.id.pb);
progressBar.setProgress(0);
mHandler = new Handler();
runnable.run();
}
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
updateProgress();
} catch (Exception ignored) {
} finally {
mHandler.postDelayed(runnable, progressInt);
}
}
};
private void updateProgress() {
progressInt += 1;
if (progressInt > 100) {
mHandler.removeCallbacks(runnable);
} else {
progressBar.setProgress(progressInt);
}
}
try this code:
Solution 1
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler();
class Task implements Runnable {
int start,end;
Task(int a,int b) { start = a; end = b;}
#Override
public void run() {
for (int i =start ; i <= end; i++) {
final int value = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler1.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(value);
}
});
}
}
}
Thread t = new Thread(new Task(from, to)); //call it
t.start();
}
Solution 2: More Simple
If thread is too much to ask for this problem..
you can use the following solution to use a single Handler to update progressbar:
code
public class HandlerDemo extends Activity
{
ProgressBar bar;
Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
bar.incrementProgressBy(5);
}
};
boolean isRunning = false;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progress);
}
public void onStart()
{
super.onStart();
bar.setProgress(0);
Thread background = new Thread(new Runnable()
{
public void run()
{
try
{
for (int i = 0; i < 20 && isRunning; i++)
{
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t)
{
// just end the background thread
}
}
});
isRunning = true;
background.start();
}
public void onStop()
{
super.onStop();
isRunning = false;
}
}
Hope it helps..

Android ProgressDialog doesn't show in onCreate using Thread

I want to load some contacts when an activity is created. Because this is a long running operation I want to notify the user through a ProgressDialog. A request for this app is to not use AsyncTasks so I'm using threads but the progress is not showing. This is my onCreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
handler = new Handler();
mActionBar = getSupportActionBar();
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
progress = new ProgressDialog(this);
progress.setMessage("Loading Contacts ");
progress.setIndeterminate(true);
progress.show();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
contacts = ContactsUtils.getContacts(getContentResolver());
handler.post(new Runnable() {
public void run() {
progress.dismiss();
// UpdateDisplay();
};
});
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
Log.e("Interrupted Exception:", e.getLocalizedMessage());
}
// other methods
}
Am I missing something? Thanks
SOLVED: The rest of the code from onCreate, after the join, should be moved to a Handler, and join should be removed
You are missig
progress.show()
plus why you are using threads don't you think async tasks will do this task with beauty?
The issue you don't see your progress dialog is because
try {
t.join();
} catch (InterruptedException e) {
Log.e("Interrupted Exception:", e.getLocalizedMessage());
}
this hold main thread till your task is done, just comment it
Try This Code:-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.launching);
final ProgressDialog myPd_ring=ProgressDialog.show(Launching.this, "", "Loading please wait..", true);
myPd_ring.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try
{
Thread.sleep(2000);
}catch(Exception e){}
Intent intt=new Intent();
intt.setClass(Launching.this, MainController.class);
startActivity(intt);
finish();
myPd_ring.dismiss();
}
}).start();
}
Whenever you're trying to do something with the UI from a background thread, either use a Handler or call it within runOnUiThread(Runnable())
try something like this:
private ProgressDialog pDialog; // global
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
color_list = (ListView) this.findViewById(R.id.color_list);
imageView1 = (ImageView)findViewById(R.id.icon);
pDialog = new ProgressDialog(Launcher.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
showProgressDialog();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
contacts = ContactsUtils.getContacts(getContentResolver());
handler.post(new Runnable() {
public void run() {
hideProgressDialog();
};
});
}
});
}
private void showProgressDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideProgressDialog() {
if (pDialog.isShowing())
pDialog.hide();
}

How to refresh ListView in AsyncTask?

I am using AsyncTask and fetch twitter feed asynchronously to display in a listView. It works fine Then for refreshing the listview I put the asyncTask call into a Runnable's Run() to load it after a specific interval. The feed loads after specific time interval but the listview is not updating. I use notifyDataSetChanged() inside the asyncTask but it is not working.
This is my trying code:
public class Twitter7FeedActivity extends Activity {
LazyAdapter adapter;
ListView list;
JSONObject jsonObj = null;
JSONArray jsonArray = null;
#SuppressLint("SimpleDateFormat")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_twitter7_feed);
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
new GetFeedTask().execute(CommonUtils.BEARER_TOKEN,
CommonUtils.URL);
} catch (Exception e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 50000);
}
protected class GetFeedTask extends AsyncTask<String, Void, String> {
private ProgressDialog dialog = new ProgressDialog(
Twitter7FeedActivity.this);
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
// related code
}
#Override
protected void onPostExecute(String jsonText) {
// related code
adapter = new LazyAdapter(Twitter7FeedActivity.this,
// tweets);
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
Have you tried moving this line:
list = (ListView) findViewById(R.id.list);
after your setContentView in your onCreate method?
// related code adapter = new LazyAdapter(Twitter7FeedActivity.this, tweets);
uncomment this code which is in onPostExecute() method. I think it may help you out. thanks...
You can do the work mentioned in your question using only a Handler. Something like this:
public class Twitter7FeedActivity extends Activity {
LazyAdapter adapter;
ListView list;
JSONObject jsonObj = null;
JSONArray jsonArray = null;
#SuppressLint("SimpleDateFormat")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_twitter7_feed);
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
ProgressDialog dialog;
public void run() {
try {
//Show your dialog here
runOnUiThread(new Runnable() {
public void run() {
runnable.this.dialog = new ProgressDialog( Twitter7FeedActivity.this);
runnable.this.dialog.setMessage("Please wait");
runnable.this.dialog.show();
}
});
//Do your AsyncTask's doInBackground work here
//Update the UI with runOnUiThread or using the Ui threa handler
runOnUiThread(new Runnable() {
public void run() {
// related code adapter = new LazyAdapter(Twitter7FeedActivity.this, tweets);
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
//Then post the thread to excecute after 50000 milliseconds.
handler.postDelayed(runnable, 50000);
} catch (Exception e)
{ }
}
};
handler.post(runnable);
}
}
This way you avoid using an AsyncTask inside a TimerTask.

Android: Thread with progressBar and setcurrentTab

final ProgressDialog Pdialog = ProgressDialog.show(SpinnerClass.this, "",
"Loading. Please wait...", true);
Thread ProgressThread = new Thread() {
#Override
public void run() {
try {
sleep(3000);
Pdialog.dismiss();
} catch(InterruptedException e) {
// do nothing
} finally {
}
}
};
ProgressThread.start();
TabHost1 TabHost1Object2 = new TabHost1();
TabHost1Object2.tabHost.setCurrentTab(2);
The problem I have with this thread is that it sets the current tab before the progress dialog starts. What have i done wrong ?
I want the dialog to run and dismiss, and after thread is done set tab.
use AsyncTask for this
some hints:
public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPostExecute(Void result) {
TabHost1 tab = new TabHost1();
tab.tabHost.setCurrentTab(2);
progressBar.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
while(myProgress<100){
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}
#Override
protected void onProgressUpdate(Integer p) {
progressBar.setProgress(p);
}
}
The thing is that,you are starting a thread which will not affect your main UI. So what eventually happens is that, your thread will run separately which will now allow the next lines of your code to be executed. So in your case,
TabHost1 TabHost1Object2 = new TabHost1();
TabHost1Object2.tabHost.setCurrentTab(2);
these lines will be executed irrespective to your thread which is also getting executed simultaneously. So what you can do here is you can either go for AsyncTask or create handlers to handle this part of your code. You have to change your code like this.
Do this in your onCreate()
Handler handler;
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
Pdialog.dismiss();
TabHost1 TabHost1Object2 = new TabHost1();
TabHost1Object2.tabHost.setCurrentTab(2);
}
};
And now in your thread,call the handler like this,
final ProgressDialog Pdialog = ProgressDialog.show(SpinnerClass.this, "",
"Loading. Please wait...", true);
Thread ProgressThread = new Thread() {
#Override
public void run() {
try {
sleep(3000);
} catch(InterruptedException e) {
// do nothing
} finally {
handler.sendEmptyMessage(0);
}
}
};
this will allow your tabhost to wait until the thread gets executed and will come into view after thread finishes execution.

Android: ProgressDialog and Show Data from XML Parsing Problem

I am parsing an XML from a URL and showing it. I want to show ProgressDialog while my XML Parser Method parse the XML and get it ready to show. The problem I am facing is that no data is shown after ProgressDialog rather it shows blank screen.
Here is my code:
ArrayList<XMLItem> items= new ArrayList<XMLItem>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mydata);
adapter= new MyAdapter(this, R.layout.customcell, items);
listView= (ListView) findViewById(id.ListView01);
listView.setAdapter(adapter);
final ProgressDialog dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
Thread thread=new Thread(new Runnable(){
public void run(){
doTheAutoRefresh();
runOnUiThread(new Runnable(){
public void run() {
if(dialog.isShowing())
dialog.dismiss();
adapter.notifyDataSetChanged(); //this line throws an exception and if i comment this line, blank screen is shown
}
});
}
});
thread.start();
}
private void doTheAutoRefresh() {
handler.postDelayed(new Runnable() {
public void run(){
loadData(); // this is where you put your refresh code
doTheAutoRefresh();
}
}, 15000);
}
private void loadData(){
Document doc;
try {
doc = XMLReader.parseURL("my url to parse xml");
NodeList nl = doc.getElementsByTagName("l");
for(int i=0; i<nl.getLength(); i++){
NamedNodeMap np = nl.item(i).getAttributes();
String t= np.getNamedItem("htn").getNodeValue();
String sT= np.getNamedItem("atn").getNodeValue();
XMLItem item= new XMLItem(t, sT);
items.add(item);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This code shows ProgressDialog perfectly, but after progress dialog, it shows blank screen. Please help me sorting out this problem.
Thanks
private class xyz extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(tranning.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please Wait...");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// do your load data function part here.
// just populate the data structures that are necessary
// for the adapter.
return null;
}
#Override
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
// notify adapter here.
adapter.notifyDataSetChanged();
refreshTimer(); // to do the same thing after 15 seconds.
}
}
}
now call the asycTask for the first time in your onCreate() probably.
new xyz().execute()
make a function to put a timer for refresh, we do that by using postDelayed.
private void refreshTimer(){
handler.postDelayed( runner , 15000);
}
private Runnable runner = new Runnable(){
public void run(){
new xyz().execute();
}
}
i think you need to implement AsyncTask ::
private class xyz extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(tranning.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please Wait...");
this.dialog.show();
// put your code which preload with processDialog
}
#Override
protected Void doInBackground(Void... arg0) {
// put your code here
return null;
}
#Override
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
and use this in main ::
new xyz().execute();
add a function showData() and call it after dismissing the dialog
ArrayList<XMLItem> items= new ArrayList<XMLItem>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mydata);
listView= (ListView) findViewById(id.ListView01);
final ProgressDialog dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
Thread thread=new Thread(new Runnable(){
public void run(){
loadData();
runOnUiThread(new Runnable(){
public void run() {
if(dialog.isShowing()){
dialog.dismiss();
showData(); //////////////////////////////////////
}
}
});
}
});
thread.start();
}
private void showData(){
adapter= new MyAdapter(this, R.layout.customcell, items);
listView.setAdapter(adapter);
}
private void loadData(){
Document doc;
try {
doc = XMLReader.parseURL("my url to parse xml");
NodeList nl = doc.getElementsByTagName("l");
for(int i=0; i<nl.getLength(); i++){
NamedNodeMap np = nl.item(i).getAttributes();
String t= np.getNamedItem("htn").getNodeValue();
String sT= np.getNamedItem("atn").getNodeValue();
XMLItem item= new XMLItem(t, sT);
items.add(item);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories

Resources