Sorry I know this question has been asked several time and has lots of answer but none of them solved my problem.
I'm calling web service and showing dialog, which is working ok. But I'm unable to dismiss the progressDialog. Although the same method is working inside fragment but this time I'm using it in Activity. Please point me where I'm making the mistake.
public void signupServiceResponse(String phNum,String password){
progressDialog = createProgressDialog(this, false);
//progressDialog.show();
final ContentServiceCall request = ServiceGenerator.createService(ContentServiceCall.class, "Empty");
final Call<UserServiceResponse> call = request.signUp(Constants.WS_VERSION,Constants.LOCAL_EN,Constants.PLATFORM, phNum,password);
call.enqueue(new Callback<UserServiceResponse>() {
#Override
public void onResponse(Call<UserServiceResponse> call, final Response<UserServiceResponse> response) {
if(response!=null && response.isSuccessful())
{
if(response.body()!=null && response.body().getResponse()!=null)
{
if(response.body().getResponse().getResponseCode()== Constants.RESPONSE_CODE_SUCCESS) {
if(response.body().getUser() != null && response.body().getUserSubscription()!= null && response.body().getUserSubscription() !=null) {
userEntity = response.body().getUser();
userProfileEntity = response.body().getUserProfile();
userSubscriptionEntity = response.body().getUserSubscription();
//insert in user table
int tableCode = 1; //table code 1 for user table
dbHelper.insertUserRegistration(userEntity, userProfileEntity, userSubscriptionEntity, tableCode);
dbHelper.close();
progressDialog.dismiss();
Intent i = new Intent(RegistrationActivity.this, ActivateAccountActivity.class);
startActivity(i);
}
} else if((response.body().getResponse().getResponseCode()== Constants.USERAlREADYEXIST_RESPONSE_CODE_SUCCESS)) {
// in case user data is cleared or app is reinstalled
boolean userCount = dbHelper.getUserCount();
if (userCount) {
Intent i = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(i);
} else if(!userCount){
// if user exist and data is cleared
userEntity = response.body().getUser();
userProfileEntity = response.body().getUserProfile();
userSubscriptionEntity = response.body().getUserSubscription();
int tableCode = 1;
dbHelper.insertUserRegistration(userEntity, userProfileEntity, userSubscriptionEntity, tableCode);
dbHelper.close();
}
} else if((response.body().getResponse().getResponseCode()== Constants.RESPONSE_CODE_PASSWORD_INCORRECT)){
Toast.makeText(RegistrationActivity.this,"Password incorrect",Toast.LENGTH_LONG).show();
btnForgetPassword.setVisibility(View.VISIBLE);
progressDialog.dismiss();
}
else {
}
}
else {
// leave it
}
}
else
{
// Display proper message
//Toast.makeText(getActivity(),getString(R.string.error_webservice_response),Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<UserServiceResponse> call, Throwable t) {
Log.e("Fail", "Failure");
Log.e("ERROR", t.getMessage());
progressDialog.dismiss();
Toast.makeText(RegistrationActivity.this,getString(R.string.error_internet_connectivity),Toast.LENGTH_LONG).show();
}
});
}
public ProgressDialog createProgressDialog(Context mContext, Boolean cancelable) {
final ProgressDialog dialog = new ProgressDialog(mContext);
try {
dialog.show();
} catch (WindowManager.BadTokenException e) {
}
dialog.setCancelable(cancelable);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog);
return dialog;
}
Make your dialog a global variable and initialize it in the onCreate() (If you're inside an Activity).
dialog = new ProgressDialog(mContext);
Add this method.
public ProgressDialog dismiss() {
if(dialog != null) {
dialog.dismiss();
}
}
Finally, instead of calling progressDialog.dismiss() simply call dismiss().
You have to check /write like this.
if(progressDialog!=null &&
progressDialog.isshowing){
progressDialog.dismiss();
}
I am using and it is working.
Related
I am implementing retrofit 2 in my app to call web services. My code is as below :
SignUp.java
ConnectionDetector connectionDetector = new ConnectionDetector(SignUpActivity.this);
if (connectionDetector.isConnectingToInternet()) {
ArrayList<HashMap<String, String>> arrayListCountryDetails = new ArrayList<>();
GetCountryList getCountryList = new GetCountryList();
arrayListCountryDetails = getCountryList.CallWebServiceForCountryDetails(this);
// The app should wait here till the above retrofit web service calling returns response
CountryDetailsAdapter countryDetailsAdapter = new CountryDetailsAdapter(SignUpActivity.this, arrayListCountryDetails);
spinnerCountryName.setAdapter(countryDetailsAdapter);
} else {
String message = "No internet connection.";
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(getResources().getString(R.string.app_name));
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
GetCountryList.java
public class GetCountryList {
ProgressDialog dialog;
APIService mAPIService;
ArrayList<HashMap<String, String>> arrayListCountryDetails;
public ArrayList<HashMap<String, String>> CallWebServiceForCountryDetails(final Context context) {
dialog = new ProgressDialog(context);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
arrayListCountryDetails = new ArrayList<>();
mAPIService = ApiUtils.getAPIService();
mAPIService.getCountryDetails().enqueue(new Callback<CountryDetailsResponseModel>() {
#Override
public void onResponse(Call<CountryDetailsResponseModel> call, Response<CountryDetailsResponseModel> response) {
if (response.isSuccessful()) {
HashMap<String, String> cntDetails = new HashMap<>();
cntDetails.put("airLineID", "0");
cntDetails.put("airLineName", "Select Airline");
arrayListCountryDetails.add(cntDetails);
// Get response
try {
if (response.body().getStatus() == 200 && response.body().getMessage().equalsIgnoreCase("success")) {
for (int count = 0; count < response.body().getCountry().size(); count++) {
cntDetails = new HashMap<>();
String countryID = response.body().getCountry().get(count).getCountryId();
String countryName = response.body().getCountry().get(count).getCountryName();
cntDetails.put("countryID", countryID);
cntDetails.put("countryName", countryName);
arrayListCountryDetails.add(cntDetails);
}
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
} else {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (Exception e) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
#Override
public void onFailure(Call<AirLineDetailsResponseModel> call, Throwable t) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
return arrayListCountryDetails;
}
}
When i am executing the code i am getting null pointer exception error as :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
at com.abc.xyz.SignUpActivity.initializeScreen(SignUpActivity.java:176)
at com.abc.xyz.SignUpActivity.onCreate(SignUpActivity.java:147)
at android.app.Activity.performCreate(Activity.java:6575)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3121)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3278)
at android.app.ActivityThread.access$1000(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6912)
at java.lang.reflect.Method.invoke(Native Method)
I know that this is because the spinner initialization execution is takes place before retrofit response.
Please suggest me how can i wait for the retrofit response. What changes i need to do in above code. Please i am not able to move ahead due to this issue.
Thanks in advance.
Very roughly do something like the following. I just placed the necessary part of code inside the AsyncTask methods. Modify as necessary.
if (connectionDetector.isConnectingToInternet()) {
// The app should wait here till the above retrofit web service calling returns response
AsyncTask task = new AsyncTask<Void, Void, List<Map<String, String>>>() {
#Override
protected String doInBackground(Void... params) {
List<Map<String, String>> arrayListCountryDetails = new ArrayList<>();
GetCountryList getCountryList = new GetCountryList();
arrayListCountryDetails = getCountryList.CallWebServiceForCountryDetails(this);
return arrayListCountryDetails;
}
#Override
protected void onPostExecute(List<Map<String, String>> arrayListCountryDetails) {
CountryDetailsAdapter countryDetailsAdapter = new CountryDetailsAdapter(SignUpActivity.this, arrayListCountryDetails);
spinnerCountryName.setAdapter(countryDetailsAdapter);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
task.execute();
}
Also remove any UI calls from your GetCountryList since this will be run on "background"
Pass Spinner object while loading data and set adapter after load complete
public class GetCountryList {
ProgressDialog dialog;
APIService mAPIService;
public void CallWebServiceForCountryDetails(final Context context,final Spinner spinnerCountryName) {
dialog = new ProgressDialog(context);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
final ArrayList<HashMap<String, String>> arrayListCountryDetails = new ArrayList<>();
mAPIService = ApiUtils.getAPIService();
mAPIService.getCountryDetails().enqueue(new Callback<CountryDetailsResponseModel>() {
#Override
public void onResponse(Call<CountryDetailsResponseModel> call, Response<CountryDetailsResponseModel> response) {
if (response.isSuccessful()) {
HashMap<String, String> cntDetails = new HashMap<>();
cntDetails.put("airLineID", "0");
cntDetails.put("airLineName", "Select Airline");
arrayListCountryDetails.add(cntDetails);
// Get response
try {
if (response.body().getStatus() == 200 && response.body().getMessage().equalsIgnoreCase("success")) {
for (int count = 0; count < response.body().getCountry().size(); count++) {
cntDetails = new HashMap<>();
String countryID = response.body().getCountry().get(count).getCountryId();
String countryName = response.body().getCountry().get(count).getCountryName();
cntDetails.put("countryID", countryID);
cntDetails.put("countryName", countryName);
arrayListCountryDetails.add(cntDetails);
}
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
//set Adapter
CountryDetailsAdapter countryDetailsAdapter = new CountryDetailsAdapter(context, arrayListCountryDetails);
spinnerCountryName.setAdapter(countryDetailsAdapter);
} else {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (Exception e) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
#Override
public void onFailure(Call<AirLineDetailsResponseModel> call, Throwable t) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
}
I have a custom progress dialog that seems to work everywhere except here in my code:
My login activity (relevant snippets):
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
context = this;
pd = AUtils.getProgressDialog(context, false);
UserExistsAuthenticateAndRoute = getIntent().getBooleanExtra("UserExistsAuthenticateAndRoute", false);
RouteToActivity = getIntent().getStringExtra("RouteToActivity");
//make sure there is no token in APrefs in memory during login
APrefs pref = new APrefs();
if (pref != null) {
pref.putNMToken(null);
pref.putNMRefreshToken(null);
}
ClickableSpan span = new ClickableSpan() {
#Override
public void onClick(View widget) {
}
};
setActionBar();
initUi();
mToolbarTitle.setText("Log In");
} catch (Exception exc) {
exc.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... voids) {
GDDataManager.get().login(GDUser, new DataCallBack() {
#Override
public void update(DataUpdate update) {
if (update.code == 0) {
final GDUser _gdUser = pref.getMember();
//call get status
if (_gdUser != null) {
Log.i(TAG, "getUserStatus()");
GDDataManager.get().getUserStatus(_gdUser, new DataCallBack() {
#Override
public void update(DataUpdate update) {
if (update.code == 0) {
setGdUserStatus((GDUserStatus) update.data);
loginController(getGdUserStatus(), _gdUser);
} else {
Log.e(TAG, "getUserStatus(), error response msg " + update.message);
if (update.message.contains("error")) {
App.toast(getString(R.string.general_server_error_message));
}
}
}
});
}
} else {
Log.e(TAG, "update message:" + update.message);
if (update.message.contains("error")) {
App.toast(getString(R.string.general_server_error_message));
} else if (update.message.contains("could not verify password")) {
App.toast(getString(R.string.could_not_verify_password));
} else if (update.message.contains("no user found")) {
App.toast(getString(R.string.no_user_found));
} else {
App.toast(update.message);
}
if (btnLogIn != null) {
//disable is valid in order to prevent double click
btnLogIn.setEnabled(false);
btnLogIn.setTextColor(ContextCompat.getColor(context, R.color.colorGrey));
}
edtEmail.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(context, R.drawable.cross_icon), null);
edtEmail.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_red));
edtPassword.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_red));
}
}//end update getUserStatus
}
);
return null;
}
};
try {
tryLoginTask.execute();
} catch (Exception exc) {
Log.d(TAG, exc.getMessage());
exc.printStackTrace();
//cancel task on exception , DISMISS DIALOG to avoid locking screen
tryLoginTask.cancel(true);
}
}//end tryLogin()
The static code from utility class, were the dialog is returned (relevant snippet):
public static Dialog getProgressDialog(Context c, boolean isCancelable) {
Dialog pd = new Dialog(c,c.getApplicationInfo().theme);
pd.setCanceledOnTouchOutside(isCancelable);
pd.requestWindowFeature (Window.FEATURE_NO_TITLE);
pd.setContentView (R.layout.progress_dialog);
pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(150,0,0,0)));
return pd;
}
Im not seeing any errors, exceptions, and the dialog is showiong in other places using the same approach. Sometimes I see it for fraction of a second however the task hasn't completed.
Any suggestions.
Thanks
AlertDialogs are foreground things. You should show your Dialogs in your UI thread. So if you want to show your Dialog in an AsyncTask you should approach with runOnUiThread:
runOnUiThread(new Runnable() {
#Override
public void run() {
// Show your dialog here
}
});
Documentations:
https://developer.android.com/reference/android/os/AsyncTask.html
https://developer.android.com/guide/components/processes-and-threads.html
I start my progress dialog in oncreate method of fragment before is initiate my web request call. In the web request call, if I fetch the response and if its success I call the notifydatasetchanged method to refresh the adapter . But the dialog gets dismissed lot before the view is updated . Please help .
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pd = ProgressDialog.show(getActivity(), "Loading...", "Please Wait...");
getProducts(highPrice, lowPrice, isLowtoHigh);
}
private void getProducts(String highPrice,String lowPrice,String isLowtoHigh) {
// loadingDialog.loading();
APIRequst.getProductsCategory(getActivity().getApplicationContext(), isLowtoHigh, lowPrice, highPrice, new APIRequestListner() {
#Override
public void onSuccess(String response) {
if (response == null || response.isEmpty()) {
Log.e("orderhistory", "success but empty");
} else {
Log.e("products", response);
try {
JSONObject mainObj = new JSONObject(response);
boolean result = mainObj.has("is_success") && mainObj.getBoolean("is_success");
String resultMessage = mainObj.getString("message");
if (resultMessage.equalsIgnoreCase("Success")) {
if (result) {
productItems.clear();
adptProductItems.clear();
JSONArray jsonOrderList = mainObj.has("categories") ? mainObj.getJSONArray("categories") : null;
if (jsonOrderList != null) {
for (int i = 0; i < jsonOrderList.length(); i++) {
JSONObject jsonObj = jsonOrderList.getJSONObject(i);
ProductListItem newItem = (new Gson()).fromJson(jsonObj.toString(), ProductListItem.class);
productItems.add(newItem);
}
adptProductItems.notifyDataSetChanged();
pd.dismiss();
}
}
} else {
if (resultMessage.equalsIgnoreCase("No Value")) {
if (pd.isShowing())
pd.dismiss();
productItems.clear();
adptProductItems.notifyDataSetChanged();
Toast.makeText(getActivity(), "Sorry no prducts to display", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// adapter.notifyDataSetChanged();
}
#Override
public void onFailure() {
if (pd.isShowing())
pd.dismiss();
// loadingDialog.dismissDialog();
}
});
}
try to move " pd.dismiss();" below onFailure()
#Override
public void onFailure() {
if (pd.isShowing())
pd.dismiss();
// loadingDialog.dismissDialog();
}
pd.dismiss();
and
adptProductItems.notifyDataSetChanged();
//pd.dismiss(); remove fromhere
may it will help as I did in my case..
I am trying to pull data from Microsoft Azure with this method. The problem is that it can sometimes be really slow, and I need these data in the shared preferences to do anything else in the application. How can I create a loading dialog that will wait for the data to be fetched? I tried putting this method in the AsyncTask doInBackground() method, but the dialog would just appear and then disappear after a millisecond. What is the right way to do this? I was reading similar topics on stackoverflow, but never found a solution.
Thank you!
private class LoadViewTask extends AsyncTask<String, Void, Boolean>
{
private ProgressDialog dialog;
private MainActivity activity;
public LoadViewTask(MainActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
private Context context;
#Override
protected void onPreExecute()
{
//Create a new progress dialog
dialog = ProgressDialog.show(MainActivity.this,"Loading...",
"", false, false);
}
//The code to be executed in a background thread.
#Override
protected Boolean doInBackground(final String... args)
{
try
{
mClient.invokeApi("getsettings", jObj, new ApiJsonOperationCallback() {
#Override
public void onCompleted(JsonElement result, Exception error,
ServiceFilterResponse response) {
SharedPreferences settings = getSharedPreferences("SettingsPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
if (error != null) {
System.out.println("Error");
} else {
JsonObject res = result.getAsJsonObject();
try {
if(res.get("gender").toString().equals("null")){
userGender = res.get("gender").toString();
editor.putString("gender", userGender);
} else {
int index1 = res.get("gender").toString().indexOf("\"");
int index2 = res.get("gender").toString().lastIndexOf("\"");
editor.putString("gender", res.get("gender").toString().substring(index1+1, index2));
}
if(res.get("dob").toString().equals("null")){
userDob = res.get("dob").toString();
editor.putString("dob", userDob);
} else {
editor.putString("dob", res.get("dob").toString().substring(1, 11));
}
if (res.get("club").isJsonNull()) {
userClub = 0;
editor.putInt("userClub", userClub);
System.out.println("userclub is null in MA: "+userClub);
} else {
editor.putInt("userClub", res.get("club").getAsInt());
}
editor.commit();
} catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final Boolean success)
{
//close the progress dialog
dialog.dismiss();
}
}
Just follow this steps
1) Create Method say loadDataFromServer() and put code inside
public void loadDataFromServer() {
dialog = ProgressDialog.show(MainActivity.this, "Loading...", "", false, false);
try {
mClient.invokeApi("getsettings", jObj, new ApiJsonOperationCallback() {
#Override
public void onCompleted(JsonElement result, Exception error, ServiceFilterResponse response) {
SharedPreferences settings = getSharedPreferences("SettingsPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
if (error != null) {
System.out.println("Error");
} else {
JsonObject res = result.getAsJsonObject();
try {
if (res.get("gender").toString().equals("null")) {
userGender = res.get("gender").toString();
editor.putString("gender", userGender);
} else {
int index1 = res.get("gender").toString().indexOf("\"");
int index2 = res.get("gender").toString().lastIndexOf("\"");
editor.putString("gender", res.get("gender").toString().substring(index1 + 1, index2));
}
if (res.get("dob").toString().equals("null")) {
userDob = res.get("dob").toString();
editor.putString("dob", userDob);
} else {
editor.putString("dob", res.get("dob").toString().substring(1, 11));
}
if (res.get("club").isJsonNull()) {
userClub = 0;
editor.putInt("userClub", userClub);
System.out.println("userclub is null in MA: " + userClub);
} else {
editor.putInt("userClub", res.get("club").getAsInt());
}
editor.commit();
dialog.dismiss(); // / DISMISS DIALOG HERE
} catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
2) Call this method like
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadDataFromServer();
}
3) dismiss dialog inside onCompleted() method. (I have added that line). just copy the method and call it.
Create a ProgressDialog and show() it before you call mClient.invokeApi and dismiss() it on onCompleted after you have done all the required processes
Try setting indeterminate to true,
//Create a new progress dialog
dialog = ProgressDialog.show(MainActivity.this,"Loading...",
"", true, false);
I am new in Android Programming.. I'M using Mono for android.. I want to made a progressdialog that show the progress when i'm importing data. I use Asynctask.. Anyone can help how to make my progress dialog show the progress. Or else any suggestion of what can be other possible way in making this.
public class importData : AsyncTask
{
private ProgressDialog _progressDialog;
WebReference.Service1 service = new WebReference.Service1();
private Context _context;
public importData(Context context)
{
_context = context;
}
protected override void OnPreExecute()
{
// i make a horizontal progressdialog, i want to see the progress while importing
base.OnPreExecute();
_progressDialog = new ProgressDialog(_context) { Indeterminate = false };
_progressDialog.SetMessage("Please wait...");
_progressDialog.SetProgressStyle(ProgressDialogStyle.Horizontal);
_progressDialog.Max = 806;
_progressDialog.Progress = 0;
_progressDialog.Show();
}
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] #params)
{
try
{
//My background Code in Importing Data
return true;
}
catch (Exception ex)
{
//When has an error return false
return false;
}
}
protected void OnProgressUpdate()
{
base.OnProgressUpdate();
//What i'm going to put in this part
}
protected override void OnPostExecute(Java.Lang.Object result)
{
base.OnPostExecute(result);
_progressDialog.Hide();
_progressDialog.Dismiss();
bool dd = (bool)result;
if (dd)
{
//Toast.MakeText(this, "Importing data completed", ToastLength.Short).Show();
Android.App.AlertDialog.Builder builder = new AlertDialog.Builder(_context);
AlertDialog ad = builder.Create();
ad.SetTitle("Info");
ad.SetIcon(Android.Resource.Drawable.IcDialogInfo);
ad.SetMessage("Importing deals completed");
ad.SetButton("OK", (s, e) => { });
ad.Show();
}
else {
Android.App.AlertDialog.Builder builder = new AlertDialog.Builder(_context);
AlertDialog ad = builder.Create();
ad.SetTitle("Error");
ad.SetIcon(Android.Resource.Drawable.IcDialogAlert);
ad.SetMessage("Failed");
ad.SetButton("OK", (s, e) => { });
ad.Show();
}
}
}
I Modified you code below. Hope it helps. Or give you an idea. In DoinBackground Loop your progressdialog and pass it in onprogressupdate using this.publishProgress ..
public class importData : AsyncTask
{
private ProgressDialog _progressDialog;
WebReference.Service1 service = new WebReference.Service1();
private Context _context;
public importData(Context context)
{
_context = context;
}
protected override void OnPreExecute()
{
// i make a horizontal progressdialog, i want to see the progress while importing
base.OnPreExecute();
_progressDialog = new ProgressDialog(_context) { Indeterminate = false };
_progressDialog.SetMessage("Please wait...");
_progressDialog.SetProgressStyle(ProgressDialogStyle.Horizontal);
_progressDialog.Max = 806;
_progressDialog.Progress = 0;
_progressDialog.Show();
}
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] #params)
{
try
{
for(int i=0; i<_progressDialog.Max; i++) {
this.PublishProgress(i);
}
//My background Code in Importing Data
return true;
}
catch (Exception ex)
{
//When has an error return false
return false;
}
}
protected override void OnProgressUpdate(params Java.Lang.Object[] values)
{
base.OnProgressUpdate();
//increment the progress of your progrssdialog
_progressDialog.IncrementProgressBy(1);
}
protected override void OnPostExecute(Java.Lang.Object result)
{
base.OnPostExecute(result);
_progressDialog.Hide();
_progressDialog.Dismiss();
bool dd = (bool)result;
if (dd)
{
//Toast.MakeText(this, "Importing data completed", ToastLength.Short).Show();
Android.App.AlertDialog.Builder builder = new AlertDialog.Builder(_context);
AlertDialog ad = builder.Create();
ad.SetTitle("Info");
ad.SetIcon(Android.Resource.Drawable.IcDialogInfo);
ad.SetMessage("Importing deals completed");
ad.SetButton("OK", (s, e) => { });
ad.Show();
}
else {
Android.App.AlertDialog.Builder builder = new AlertDialog.Builder(_context);
AlertDialog ad = builder.Create();
ad.SetTitle("Error");
ad.SetIcon(Android.Resource.Drawable.IcDialogAlert);
ad.SetMessage("Failed");
ad.SetButton("OK", (s, e) => { });
ad.Show();
}
}
}