To use ProgressDialog till GridView gets loaded from webservice - android

I am fetching Image and Text for GridView from a webservice, so its takes some time to display the GridView. I want to show a ProgressDialog till Grid gets fully loaded. What I have done till now is as below:
public class PCGridMain extends Activity
{
WebService web = new WebService();
private GridView gridView;
ProgressDialog dialog;
Bitmap icon;
int i, total;
URL url= null;
List<GridItem> list;
#Override
public void onCreate(Bundle grid)
{
super.onCreate(grid);
dialog = ProgressDialog.show(PCGridMain.this, "Loading...", "Loading App, Please wait.", true);
DialogWork dWork = new DialogWork();
dWork.execute();
setContentView(R.layout.main);
gridView = (GridView)findViewById(R.id.gridView1);
web.WebService1();
total = web.totalService;
list = new ArrayList<GridItem>();
for(i=0; i<total; i++)
{
Log.v("Try Block", "See what we get:-");
try
{
Log.v("GridMain", "try url" + Integer.toString(i));
url = new URL(web.arr[i][2]);
}
catch (MalformedURLException e)
{
Log.v("GridMain", "catch MalformedURLException" + Integer.toString(i));
e.printStackTrace();
}
try
{
Log.v("GridMain", "try BitmapFactory" + Integer.toString(i));
icon = BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch (IOException e)
{
Log.v("GridMain", "catch IOException" + Integer.toString(i));
e.printStackTrace();
}
list.add(new GridItem(icon, web.arr[i][1])); // Adding Icon & LAbel
}
gridView.setAdapter(new GridAdapter(this, list));
gridView.setOnItemClickListener(Itemlistener);
}
private OnItemClickListener Itemlistener = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
ViewHolder holder = (ViewHolder)view.getTag();
if(holder == null)
{
return;
}
Toast.makeText(PCGridMain.this, holder.label.getText(), Toast.LENGTH_SHORT).show();
Log.v("GridMain", "Intent Creation");
Intent intent = new Intent(view.getContext(), ShowService.class); Log.v("GridMain", "Intent Created");
intent.putExtra("ServiceId", web.arr[position][0]); Log.v("GridMain", "ValueAdded Sid");
intent.putExtra("SName", holder.label.getText()); Log.v("GridMain", "ValueAdded SName");
startActivity(intent);
}
};
class DialogWork extends AsyncTask<URL, Integer, Long>
{
protected Long doInBackground(URL... params)
{
try
{
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress)
{
}
protected void onPostExecute(Long result)
{
try
{
//setContentView(R.layout.main);
//gridView.setAdapter(new GridAdapter(PCGridMain.this, list));
dialog.dismiss();
}
catch (Exception e)
{
e.printStackTrace();
dialog.dismiss();
}
}
}
Please tell me that what code has to be placed at what exact location, whenever I do some changes, it either shows no effect or App closes due to some issue.
Thanks,
Haps.

Try to put all rendering part from server in doInBackground() and set the adapter in onPostExecute() . And even start the progressdialog in onPreExecute() in and dismiss it on onPostExecute() but not in onCreate(). I think it will solve ur problem....

This should be your inner AsyncTask class, change parameters as you need.
private class yourTask extends AsyncTask<Void, Void, ArrayList> {
String message;
ProgressDialog dialog;
public refreshTask(String message) {
this.message = message;
this.dialog = new ProgressDialog(PCGridMain.this);
}
#Override
protected void onPreExecute() {
dialog.setMessage(message);
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected ArrayList doInBackground(String... params) {
// Some work
}
#Override
protected void onPostExecute(ArrayList result) {
if(dialog.isShowing())
dialog.dismiss();
}
}
So you may call this class like:
new yourTask('Dialog message').execute();
I hope it solves your issue.

Here I am giving the complete answer to my question, So that it may help others to make it done easily...
public class PCGridMain extends Activity
{
WebService web = new WebService();
private GridView gridView;
ProgressDialog dialog;
Bitmap icon;
int i, total;
URL url= null;
List<GridItem> list;
#Override
public void onCreate(Bundle grid)
{
super.onCreate(grid);
Log.v("GridMain", "setContent");
setContentView(R.layout.main);
gridView = (GridView)findViewById(R.id.gridView1);
DialogWork dWork = new DialogWork();
dWork.execute();
}
private void ForLoop()
{
for(i=0; i<total; i++)
{
Log.v("Try Block", "See what we get:-");
try
{
Log.v("GridMain", "try url" + Integer.toString(i));
url = new URL(web.arr[i][2]);
}
catch (MalformedURLException e)
{
Log.v("GridMain", "catch MalformedURLException" + Integer.toString(i));
e.printStackTrace();
}
try
{
Log.v("GridMain", "try BitmapFactory" + Integer.toString(i));
icon = BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch (IOException e)
{
Log.v("GridMain", "catch IOException" + Integer.toString(i));
e.printStackTrace();
}
list.add(new GridItem(icon, web.arr[i][1])); // Adding Icon & LAbel
}
}
private OnItemClickListener Itemlistener = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
ViewHolder holder = (ViewHolder)view.getTag();
if(holder == null)
{
return;
}
Toast.makeText(PCGridMain.this, holder.label.getText(), Toast.LENGTH_SHORT).show();
Log.v("GridMain", "Intent Creation");
Intent intent = new Intent(view.getContext(), ShowService.class); Log.v("GridMain", "Intent Created");
intent.putExtra("ServiceId", web.arr[position][0]); Log.v("GridMain", "ValueAdded Sid");
intent.putExtra("SName", holder.label.getText()); Log.v("GridMain", "ValueAdded SName");
startActivity(intent);
}
};
class DialogWork extends AsyncTask<URL, Integer, String>
{
protected void onPreExecute()
{
Log.v("GridMain", "PreExecute()");
dialog = ProgressDialog.show(PCGridMain.this, "Loading...", "Loading App, Please wait.", false, true);
}
protected Long doInBackground(URL... params)
{
String response = "";
try
{
Log.v("GridMain", "doInBackground");
response = web.WebService1();
total = web.totalService;
}
catch (InterruptedException e)
{
Log.v("GridMain", "InterruptedException");
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String result)
{
try
{
// Response is in RESULT_VAR
Log.v("GridMain", "onPostExecute");
list = new ArrayList<GridItem>();
ForLoop();
gridView.setAdapter(new GridAdapter(PCGridMain.this, list));
gridView.setOnItemClickListener(Itemlistener);
dialog.dismiss();
}
catch (Exception e)
{
Log.v("GridMain", "Exception e");
e.printStackTrace();
dialog.dismiss();
}
}
}
}
I have used it as according to my needs, its just for the help, the complete code might give problem to you. So just take it as a reference.
Thanks & Regards,
Haps.

try dialog with this code else code seems working
dialog= new ProgressDialog(this);
dialog.setMessage("Loading");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.show();

Related

AsyncTask in Android Studio

When i make my app run it doesn't go into onPostExecute() but when i debug it it works ,what can i do??I tried the thread.sleep() method but it doesn't help!!
Please what can i do in order for my AsyncTask to work while running
try {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
try {
tempBook = backend.returnBook(book.getName(), book.getAuthor(), book.getEdition());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Void aVoid) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
book_provider.setId_Book(tempBook.getId_Book());
}
}.execute();
} catch (Exception e) {
e.printStackTrace();
}
book_provider.setId_Provider(provider.getId_Provider());
book_provider.setPrice(Integer.parseInt(price.getText().toString()));
book_provider.setAmount_In_Stock(Integer.parseInt(quantity.getText().toString()));
try {
backend.addBook_Provider(book_provider);
} catch (Exception e) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(Add_Book.this);
builder1.setMessage(e.getMessage());
builder1.setIcon(R.drawable.ic_warning_black_24dp);
builder1.setTitle("WARNING!");
builder1.setCancelable(true);
builder1.setPositiveButton("Update this book",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent1 = new Intent(Add_Book.this, details_book_provider.class);
intent1.putExtra("book", book);
intent1.putExtra("provider", provider);
startActivity(intent1);
}
});
}
AsyncTask allows you to specify the return types of the objects which you want to use for the different methods. The declaration is AsyncTask
For this example I'm going to assume that tempBook is an instance of the class Book. You would need to do something like:
new AsyncTask<Void, Void, Book>() {
#Override
protected Book doInBackground(Void... params) {
try {
return backend.returnBook(
book.getName(),
book.getAuthor(),
book.getEdition()
);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(Book result) {
book_provider.setId_Book(result.getId_Book());
}
}.execute();
First of all you should remove sleep in main thread as you've been told.
Also I'll recommend to move the code
book_provider.setId_Provider(provider.getId_Provider());
book_provider.setPrice(Integer.parseInt(price.getText().toString()));
book_provider.setAmount_In_Stock(Integer.parseInt(quantity.getText().toString()));
to the onPostExecute
You should understand that it's Async code and this code is executed before the command
book_provider.setId_Book(tempBook.getId_Book());

My activity keep show the dialog, It seem don't do the doInBackground

My activity keep show the dialog, It seem don't do the doInBackground. It keep should the "Loading" screen .
Here is my code :
private class MapTask extends AsyncTask<Void, Void, Void> {
protected ProgressDialog dialog;
protected Context context;
public MapTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.dialog = new ProgressDialog(context, 1);
this.dialog.setMessage("Loading");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
try {
String countryName=country.getTitle();
List<Address> address = new Geocoder(context).getFromLocationName(countryName, 1);
if (address == null) {
Log.e(null, "Not found");
} else {
Address loc = address.get(0);
Log.e(null, loc.getLatitude() + " " + loc.getLongitude());
LatLng pos = new LatLng(loc.getLatitude(), loc.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 6));
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (Exception e) {
Log.v("ASYNC", "ERROR : " + e);
e.printStackTrace();
}
return null;
}
}
Could somebody help me?
You are not calling dialog.dismiss() anywhere. You should do it in the onPostExecute of your AsyncTask:
#Override
protected void onPostExecute(Void... aVoid) {
dialog.dismiss();
}
In fact it is doing the doInBackground stuff, the problem is that you aren't dismissing the dialog in onPostExecute() method
Just add dialog.dismiss() in onPostExecute method.

Spinner OnItemSelectedListener in Custom adapter Listview call recursively without selecting any item

I have custom adapter list view with two spinner view.
Each spinner has a background process. On initializing, the spinner view.OnItemSelectedListener is recursively called unnecessarily without any external input to the listener
Class file
public class ClientListAdapter extends BaseAdapter implements SpinnerAdapter {
Context context;
int layoutResourceId;
ArrayList<GetClientListDetail> data = null;
ArrayList<GetClientListDetail> temp = null;
String ID, str;
Typeface typeface;
PopupWindow cp;
private ProgressDialog progressDialog;
String[] Status1 = new String[] { "Waiting", "Away","No Show"};
String[] Status2 = new String[] { "In Service",
"Generate Bill", "Completed" };
SpinnerAdapterlist TherapistAdapter = null;
ArrayAdapter<String> StatusAdapter = null;
ArrayList<GetTherapistProperties> TherapistList ;
private LayoutInflater inflater;
RemoveClient RC;
ChangeStatus CS;
ChangeTherapist CT;
ClientListHolder holder ;
int _therapistID;
GetClientListDetail ap;
GetTherapistProperties tp;
boolean networkavailable=false;
public ClientListAdapter(Context context, int textViewResourceId,
ArrayList<GetClientListDetail> gld, ArrayList<GetTherapistProperties> therapislist) {
super();
this.layoutResourceId = textViewResourceId;
this.context = context;
this.data = gld;
this.mGalleryCount1 = gld.size();
this.mGalleryCount2=gld.size();
this.TherapistList=therapislist;
inflater=LayoutInflater.from(context);
Resources res = context.getResources();
TherapistAdapter = new SpinnerAdapterlist(context,
R.layout.spinnerlayout, TherapistList);
StatusAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_dropdown_item_1line, Status1);
}
#Override
public int getCount() {
return data.size();
}
#Override
public GetClientListDetail getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
holder = new ClientListHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.tv_no = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_no);
holder.tv_name = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_name);
holder.tv_status = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_status);
holder.tv_therapist = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_therapist);
holder.iv_edit=(ImageView) row.findViewById(R.id.btn_clientwaitlayout_edit);
holder.iv_action = (ImageView) row
.findViewById(R.id.btn_clientwaitlayout_action);
holder.tv_unchange_therapist=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_name);
holder.tv_unchange_status=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_status);
row.setTag(holder);
} else {
holder = (ClientListHolder) row.getTag();
}
holder.tv_therapist.setAdapter(TherapistAdapter);
holder.tv_status.setAdapter(StatusAdapter);
ap = data.get(position);
tp=TherapistList.get(position);
holder.tv_name.setText(ap.getCLDName());
holder.tv_no.setText(ap.getCLDNo());
if(ap.getCLDStatus().equals("1") ){
Log.d("LOOP","Sub If condition");
holder.tv_therapist.setVisibility(View.VISIBLE);
holder.tv_status.setVisibility(View.VISIBLE);
holder.tv_unchange_therapist.setVisibility(View.GONE);
holder.tv_unchange_status.setVisibility(View.GONE);
holder.iv_action.setVisibility(View.GONE);
holder.iv_edit.setVisibility(View.VISIBLE);
try {
for(int x=0;x<TherapistList.size();x++){
if(ap.getCLDTherapist().equals(TherapistList.get(x).getID())){
holder.tv_therapist.setSelection(x);
}else{
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
holder.tv_status.setSelection(Integer.parseInt(ap.getCLDStatus()) - 1);
} catch (ArrayIndexOutOfBoundsException e2) {
// TODO Auto-generated catch block
holder.tv_status.setSelection(0);
}
}else if(ap.getCLDStatus().equals("2") | ap.getCLDStatus().equals("6")){
holder.tv_therapist.setVisibility(View.VISIBLE);
holder.tv_status.setVisibility(View.VISIBLE);
holder.tv_unchange_therapist.setVisibility(View.GONE);
holder.tv_unchange_status.setVisibility(View.GONE);
holder.iv_action.setVisibility(View.GONE);
holder.iv_edit.setVisibility(View.GONE);
try {
for(int x=0;x<TherapistList.size();x++){
if(ap.getCLDTherapist().equals(TherapistList.get(x).getID())){
holder.tv_therapist.setSelection(x);
}else{
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(ap.getCLDStatus().equals("2")){
holder.tv_status.setSelection(1);
}else{
holder.tv_status.setSelection(2);
}
} catch (ArrayIndexOutOfBoundsException e2) {
// TODO Auto-generated catch block
holder.tv_status.setSelection(0);
}
}else{
holder.tv_therapist.setVisibility(View.GONE);
holder.tv_status.setVisibility(View.GONE);
holder.tv_unchange_therapist.setVisibility(View.VISIBLE);
holder.tv_unchange_status.setVisibility(View.VISIBLE);
holder.iv_action.setVisibility(View.VISIBLE);
holder.iv_edit.setVisibility(View.GONE);
for(int y=0;y<TherapistList.size();y++){
if(ap.getCLDTherapist().equals(TherapistList.get(y).getID())){
holder.tv_unchange_therapist.setText(TherapistList.get(y).getName());
break;
}else{
holder.tv_unchange_therapist.setText("Not Available");
}
}
if (ap.getCLDStatus().equals("2")) {
holder.tv_unchange_status.setText(Status1[1]);
} else if (ap.getCLDStatus().equals("3")) {
holder.tv_unchange_status.setText(Status2[0]);
} else if (ap.getCLDStatus().equals("4")) {
holder.tv_unchange_status.setText(Status2[1]);
} else if (ap.getCLDStatus().equals("5")) {
holder.tv_unchange_status.setText(Status2[2]);
} else if (ap.getCLDStatus().equals("6")) {
holder.tv_unchange_status.setText(Status1[2]);
}
}
holder.tv_therapist.setTag(ap.getCLDClientID());
holder.tv_status.setTag(ap.getCLDClientID());
holder.iv_edit.setTag(ap.getCLDClientID());
holder.iv_action.setTag(ap.getCLDClientID());
holder.iv_action.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
ImageView b = (ImageView) v;
String id = b.getTag().toString();
Log.d("ID is", id);
Intent CDV=new Intent(context, TabSample.class);
CDV.putExtra("ID", id);
//CDV.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//context.startActivity(CDV);
((Activity) context).startActivityForResult(CDV,5);
try {
Log.d("POSITION", "" + position + " "
+ data.get(position).getCLDClientID());
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
holder.tv_status
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int id=arg2+1;
try {
try {
CS=new ChangeStatus();
CS.setClientID(data.get(position).getCLDClientID());
CS.setSalonID("1");
if(id==3){
CS.setStatus("6");
}else{
CS.setStatus(String.valueOf(id));
}
new LoadChangeStatus().execute();
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
holder.tv_therapist
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
try {
try {
Spinner sp = (Spinner) arg0;
String str = sp.getTag().toString();
TextView th_id=(TextView)arg1.findViewById(R.id.spnradptno);
CT=new ChangeTherapist();
CT.setClientID(str);
CT.setSalonID("1");
CT.setTherapist(th_id.getText().toString());
new LoadChangeTherapist().execute();
Log.d("SPR TXT", th_id.getText().toString()+" "+position+" "+str);
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
Log.d("Error in spinner",e.toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("Error2 in spinner",e.toString());
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Log.d("Nothing","Selected");
}
});
holder.iv_edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
ImageView b = (ImageView) v;
String id = b.getTag().toString();
Log.d("ID is", id);
Intent CDV=new Intent(context, TabSample.class);
CDV.putExtra("ID", id);
((Activity) context).startActivityForResult(CDV,5);
try {
Log.d("POSITION", "" + position + " "
+ data.get(position).getCLDClientID());
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
return row;
}
static class ClientListHolder {
TextView tv_no;
TextView tv_name;
Spinner tv_therapist;
Spinner tv_status;
ImageView iv_action;
ImageView iv_edit;
TextView tv_unchange_therapist;
TextView tv_unchange_status;
}
public class LoadChangeStatus extends AsyncTask<Integer, Integer, Integer> {
// Before running code in the separate thread
int LoadChangeStatus= 0;
#Override
protected void onPreExecute() {
// Create a new progress dialog
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal progress bar
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
// Set the dialog message to 'Loading application View, please
// wait...'
progressDialog.setMessage("Loading, please wait...");
// This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(false);
// This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
// The maximum number of items is 100
// Set the current progress to zero
// Display the progress dialog
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected Integer doInBackground(Integer... params) {
try {
// temp.clear();
networkavailable=new Network().isNetworkAvailable(context);
if(networkavailable){
temp = CS.Change_Status(CS, context);
LoadChangeStatus=1;
}else{
LoadChangeStatus=2;
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("ERROR", "LoadChangeStatus backgroung");
}
return null;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
}
// after executing the code in the thread
#Override
protected void onPostExecute(Integer result) {
// close the progress dialog
progressDialog.dismiss();
if(LoadChangeStatus==1){
try {
data.clear();
data.addAll(temp);
notifyDataSetChanged();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(LoadChangeStatus==2){
Toast.makeText(context, "Network Not Available", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "Changing Status Failed. Please Try Again", Toast.LENGTH_LONG).show();
}
}
}
public class LoadChangeTherapist extends
AsyncTask<Integer, Integer, Integer> {
// Before running code in the separate thread
int LoadChangeTherapist = 0;
#Override
protected void onPreExecute() {
// Create a new progress dialog
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal progress bar
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
// Set the dialog message to 'Loading application View, please
// wait...'
progressDialog.setMessage("Loading, please wait...");
// This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(false);
// This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
// The maximum number of items is 100
// Set the current progress to zero
// Display the progress dialog
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected Integer doInBackground(Integer... params) {
try {
// temp.clear();
networkavailable=new Network().isNetworkAvailable(context);
if(networkavailable){
temp = CT.Get_Change_Therapist(CT, context);
LoadChangeTherapist=1;
}else{
LoadChangeTherapist=2;
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("ERROR", "LoadChangeStatus backgroung");
}
return null;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
}
// after executing the code in the thread
#Override
protected void onPostExecute(Integer result) {
// close the progress dialog
progressDialog.dismiss();
if (LoadChangeTherapist == 1) {
try {
data.clear();
data.addAll(temp);
notifyDataSetChanged();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (LoadChangeTherapist == 2) {
Toast.makeText(context, "Network Not Available", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "Removing Client Failed. Please Try Again", Toast.LENGTH_LONG).show();
}
}
}
public class LoadRemoveClient extends AsyncTask<Integer, Integer, Integer> {
// Before running code in the separate thread
int LoadRemoveClient = 0;
#Override
protected void onPreExecute() {
// Create a new progress dialog
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal progress bar
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
// Set the dialog message to 'Loading application View, please
// wait...'
progressDialog.setMessage("Loading, please wait...");
// This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(false);
// This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
// The maximum number of items is 100
// Set the current progress to zero
// Display the progress dialog
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected Integer doInBackground(Integer... params) {
Log.d("ERROR", "LoadRemoveClient backgroung");
try {
networkavailable=new Network().isNetworkAvailable(context);
if(networkavailable){
temp = RC.Get_Client_List_Detail(RC, context);
LoadRemoveClient=1;
}else{
LoadRemoveClient=2;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
}
// after executing the code in the thread
#Override
protected void onPostExecute(Integer result) {
// close the progress dialog
progressDialog.dismiss();
if (LoadRemoveClient == 1) {
try {
data.clear();
data.addAll(temp);
notifyDataSetChanged();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (LoadRemoveClient == 2) {
Toast.makeText(context, "Network Not Available", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "Removing Client Failed. Please Try Again", Toast.LENGTH_LONG).show();
}
}
}
}
How to avoid unnecessarily calling of view.OnItemSelectedListener of spinner view On initializing custom adapter list view
You can't stop or avoid calling of onItemSelectedListener on initialization. But you can prevent this by declare an integer and set value as 0 and while on calling getview method, check the integer with size of data(Your array list size).if the integer is less than the size than increment the integer value else do your background work. But it's not right way to do because when you scroll the listview the same problem rise again. You do this if you have fixed array list size. It is better to use AutoCompleteTextView instead of SpinnerView.
It gets called for the selection of the first item(Kind of default value).
Try one thing don't set adapter to spinner if row!=null for ex:
if (row == null) {
holder = new ClientListHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.tv_no = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_no);
holder.tv_name = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_name);
holder.tv_status = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_status);
holder.tv_therapist = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_therapist);
holder.iv_edit=(ImageView) row.findViewById(R.id.btn_clientwaitlayout_edit);
holder.iv_action = (ImageView) row
.findViewById(R.id.btn_clientwaitlayout_action);
holder.tv_unchange_therapist=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_name);
holder.tv_unchange_status=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_status);
holder.tv_therapist.setAdapter(TherapistAdapter);
holder.tv_status.setAdapter(StatusAdapter);
row.setTag(holder);
} else {
holder = (ClientListHolder) row.getTag();
}

progress dialog circle only showing after task

i've an progress circle that is set inside an AsyncTask. It shows for about a second as the asynctask is executing, then disappears. once the task is completed if i press the back button the circle shows for a long time. why is this?
private class AsyncGetRota extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog= ProgressDialog.show(NfcscannerActivity.this,
"Connecting to Server"," retrieving rota...", true);
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(String... params) {
try {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressDialog.dismiss();
};
}
[update]
getRota.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "onclicked getRota");
String[] params = new String[]{"36", "18-09-2012"};
AsyncGetRota agr = new AsyncGetRota();
agr.execute(params);
for(int i = 0; i < 60; i++){
if(agr.isCancelled() == true){
Log.e(TAG, "asyncTask is finished");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}//end of for loop
Intent intent = new Intent(NfcscannerActivity.this,
GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", rotaArray);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}// end of onclick
});
...
new MyAsyncTask().execute(string);
...
}
class MyAsyncTask extends AsyncTask<String, Void, Whatever > {
...
#Override
protected Whatever doInBackground(String... params) {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
return rotaArray;
}
#Override
protected void onPostExecute(Whatever result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
Intent intent = new Intent(NfcscannerActivity.this, GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", result);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}
}
You should let the execution continue after you start the AsyncTask, and not block it using some loop or something..
try to implement it like this:
protected void onPreExecute() {
dialog = new ProgressDialog(activity);
dialog.setMessage("Processing...");
dialog.show();
}
protected void onPostExecute(Void result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
};
that's always works for me
Couple of problems here, you do not initialize ProgressDialog, initialize a constructor that initializes you ProgressDialog like this...
public AsyncGetRota(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
Then in onPostExecute check if your ProgressDialog is null, like this
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
}

Android: Async Task, how to handle efficiently?

I am using this Asnc class my application, but at times when i quit the application. It crashes. "window leaked error : at line progDialog.show();" - Guess the ProgressDialog is causing the issue as it is still referencing to the activity(context), but i cant use getApplicationContext(), if i use getApplicationContext(), then the ProgressDialog wont work. How can i fix this issue ?
protected void executeSLPWebserviceTask(double latitude, double longitude,
String progressStr) {
WebserviceTask task = new WebserviceTask(this, progressStr);
task.execute(latitude, longitude);
}
class WebserviceTask extends AsyncTask<Double, Void, Float> implements OnDismissListener{
Context context;
ProgressDialog progDialog;
String progressString;
public WebserviceTask(Context context, String progressStr) {
this.context = context;
this.progressString = progressStr;
initProgDialog();
}
void initProgDialog(){
if(!isCancelled()){
try {
progDialog = new ProgressDialog(context);
progDialog.setCanceledOnTouchOutside(false);
progDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.btn_cancel),new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
progDialog.dismiss();
}
});
progDialog.setMessage(progressString);
progDialog.setOnDismissListener(this);
progDialog.show();
} catch (Exception e) {
Log.e("Web&RemoteServiceActivity", "Failed to add window for web service task");
}
}
}
#Override
protected void onPreExecute() {
addTask(this);
super.onPreExecute();
}
protected Float doInBackground(Double... latLong) {
Float slpFloat = 0f;
if(!isCancelled()){
if(internetServiceBound)
{
try {
slpFloat = internetSLPService.getSLPFromInternet(latLong[0].floatValue(),latLong[1].floatValue());
} catch (RemoteException e) {
Log.e("Webservice task", "Failed to get slp - Remote exception");
this.cancel(true);
}
catch (NullPointerException e) {
Log.e("Webservice task", "Failed to get slp - Null pointer exception");
this.cancel(true);
}
}
}
return slpFloat;
}
protected void onPostExecute(Float slpFloat) {
if (!isCancelled()) {
if(slpFloat >= 300 && slpFloat<=1100){
//seaLevelPressure = slpFloat;
setReferenceSeaLevelPressure(slpFloat);
updateSeaLevelPressureFromWeb(slpFloat);
Toast toast = Toast.makeText(getApplicationContext(), getString(R.string.msg_slp_updated_from_internet) + " : " + slpFloat, Toast.LENGTH_LONG);
toast.show();
addToastJob(toast);
progDialog.dismiss();
//lastCalibratedTime = System.currentTimeMillis();
}else if(slpFloat==0){
//If SLP value returned is 0, notify slp fetch fail and cancel progress dialog
Toast toast = Toast.makeText(getApplicationContext(),getString(R.string.msg_slp_fetch_fail), Toast.LENGTH_SHORT);
toast.show();
addToastJob(toast);
progDialog.dismiss();
}else{
//Notify invalid SLP and cancel progress dialog
Toast toast = Toast.makeText(getApplicationContext(),getString(R.string.msg_internet_slp_invalid), Toast.LENGTH_SHORT);
toast.show();
addToastJob(toast);
progDialog.dismiss();
}
}
this.cancel(true);
}
public void onDismiss(DialogInterface dialog) {
this.cancel(true);
}
#Override
protected void onCancelled() {
if(progDialog != null){
if(progDialog.isShowing())
progDialog.dismiss();
}
super.onCancelled();
}
}
Create progressDialog by overriding onCreateDialog(int id) in your activity. In your task in onPreExecute() method use showDialog(PROGRESS_DIALOG_ID); and in onPostExecute() method use dismissDialog(PROGRESS_DIALOG_ID);

Categories

Resources