Android: ProgressDialog and Show Data from XML Parsing Problem - android

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();
}
}

Related

Android dialog bar during listview

i am trying to add items to list and i want to start dialog bar before the start of the loop which add items to list and dismiss dialog after loop finish
ProgressDialog pd;
pd = new ProgressDialog(SearchList.this);
pd.setTitle("Please wait");
pd.setMessage("loading String.. ");
pd.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
for (int i = 0; i <500000; i++) {
list.add("String "+i);
}
pd.dismiss();
} catch (Exception e) {
}
}
}).start();
m_adapter = new Adapter(this, R.layout.itemview, list);
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(m_adapter);
Use AsyncTask to show/hide ProgressDialog as follows:
protected void onPreExecute() {
dialog=ProgressDialog.show(mContext, "", "Your message");
super.onPreExecute();
}
protected void onPostExecute(Void result) {
if(dialog!=null)
{
dialog.dismiss();
}
}
Use doInBackground function to do your looping:
protected Void doInBackground(String... params) {}
See example how to use AsyncTask
Try this way,hope this will help you to solve your problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getList(this,new AddItemFinsihListener() {
#Override
public void onFinish(Object object) {
ArrayList<String> list = (ArrayList<String>) object;
for (String row : list){
System.out.println(row);
}
// try to set your list adapter here
}
});
}
public void getList(final Context context, final AddItemFinsihListener target) {
final ProgressDialog pd = new ProgressDialog(context);
new AsyncTask<Void,Void,Object>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setTitle("Please wait");
pd.setMessage("Page is loading..");
pd.show();
}
#Override
protected Object doInBackground(Void... params) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i <500000; i++) {
list.add("String "+i);
}
return list;
}
#Override
protected void onPostExecute(Object object) {
super.onPostExecute(object);
pd.dismiss();
target.onFinish(object);
}
}.execute();
}
interface AddItemFinsihListener{
public void onFinish(Object object);
}
You need to add the Array first before you initialized the adapter and add it to the ListView.
try this:
ProgressDialog pd;
pd = new ProgressDialog(SearchList.this);
pd.setTitle("Please wait");
pd.setMessage("loading String.. ");
pd.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
for (int i = 0; i <500000; i++) {
list.add("String "+i);
}
SearchList.this.runOnUiThread(new Runnable() {
#Override
public void run() {
m_adapter = new Adapter(this, R.layout.itemview, list);
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(m_adapter);
pd.dismiss();
}
});
} catch (Exception e) {
}
}
}).start();

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();
}

Horizontal ProgressDialog not shown in 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();
}

Show progressDialog in Android

I want to show a progressDialog on my page when the user clicks on the button.On click of button i am sorting my results that is a List.Now how can we show a progressDialog on click of a button.Please suggest me
This function i am using to sort that data :
public void sortByDate(View v) {
Collections.sort(tripParseData.getDetails());
setData(tripParseData);
}
After #Monica Suggestion
public void sortByDate(View v) {
new LoadData().execute();
}
class LoadData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
Collections.sort(tripParseData.getCoroprateBookingDetails());
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
setApprovalDetailsData(tripParseData);
}
}
you have to call progressdiolog.show before the long calculation starts and then the calculation has to run in a separate thread. A soon as this thread is finished, you have to call pd.dismiss() to close the prgoress dialog.
here you can see an example:
the progressdialog is created and displayed and a thread is called to run a heavy calculation:
Override
public void onClick(View v) {
pd = ProgressDialog.show(lexs, "Search", "Searching...", true, false);
Search search = new Search( ... );
SearchThread searchThread = new SearchThread(search);
searchThread.start();
}
and here the thread:
private class SearchThread extends Thread {
private Search search;
public SearchThread(Search search) {
this.search = search;
}
#Override
public void run() {
search.search();
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
displaySearchResults(search);
pd.dismiss();
}
};
}
Don't forget to vote me up :)
Paste This Class in ur activity and call new LoadData().execute to start the prgress dialog :
class LoadData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pg=new ProgressDialog(ChartsActivity.this);
pg=pg.show(ChartsActivity.this, "Loding", "Plz Wait...");
}
#Override
protected Void doInBackground(Void... params) {
sortByDate();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pg.dismiss();
}
}
I have not tested it but I think it can help you.
Declare these two objects in your class and member variables.
Thread thread = null;
ProgressDialog bar = null;
Use this logic on your button click listener it can work in your case. I have not tested it but It will give you Idea how things should work. you can also use handlemessage in place of runonuithread
if (thread == null
|| (thread != null && !thread.isAlive())) {
thread = new Thread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//DISPLAY YOUR PROGRESS BAR HERE.
bar = ProgressDialog.show(getApplicationContext(), "LOADING..", "PLEASE WAIT..");
}
});
// SORT COLLECTION HERE
runOnUiThread(new Runnable() {
#Override
public void run() {
//CLOSE YOUR PROGRESS BAR HERE.
bar.dismiss();
}
});
}
});
thread.start();
}
Hope this will help you.
try to use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
Sample code:
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
//Show UI
//Start your progress bar
showProgress();
}
#Override
protected Void doInBackground(Void... arg0) {
// do your sorting process
return null;
}
#Override
protected void onPostExecute(Void result) {
//Show UI
//dismiss your progress bar
hideProgress();
}
};
task.execute((Void[])null);
Show and hide progress code
public void showProgress() {
progressDialog = ProgressDialog.show(this, "",
"Loading. Please wait...");
progressDialog.setCancelable(false);
}
public void hideProgress() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}

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.

Categories

Resources