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);
Related
I am uploading some file to server using AsyncTask and I want to show a progress dialog in AsyncTask.
My AsyncTask is working fine and executing all the steps, but it never shows the dialog.I don't know what I have done wrong.
I have written below code but not working. Can someone help please!!!
Activity:
public class MainActivity extends AppCompatActivity {
ImageView videoImage ;
EditText editTextVideoTitle;
EditText editTextVideoDescription;
Button btnPostButton;
Button btnCancelButton;
private String mVideoPath;
private String mVideoThumb;
String strVideoTitle;
String strVideoDescription;
boolean videoPosted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_vid_with_desc);
editTextVideoTitle = (EditText) findViewById(R.id.videoTitle);
editTextVideoDescription = (EditText) findViewById(R.id.videoDescription);
btnPostButton = (Button) findViewById(R.id.postButton);
btnCancelButton = (Button) findViewById(R.id.cancelButton);;
mVideoPath = getIntent().getStringExtra("path");
mVideoThumb = getIntent().getStringExtra("thumb");
btnPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoPosted = postVideo();
if (videoPosted) {
Toast.makeText(getApplicationContext(), "Your video posted successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error in posting video, please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean postVideo() {
Log.i("Info", "PostVidWithDescActivity : postVideo : Start");
String strUserId = "";
String strReservedfield = "";
boolean isVideoPosted = false;
sharedPreferences = this.getSharedPreferences("com.app.rapid", Context.MODE_PRIVATE);
strVideoTitle = editTextVideoTitle.getText().toString();
strVideoDescription = editTextVideoDescription.getText().toString();
try {
strUserId = sharedPreferences.getString("userId", "");
strReservedfield = "ReservedField";
outputData = new PostToServerAsyncTask().execute(mVideoPath, strUserId, strVideoTitle, strVideoDescription, strReservedfield).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
if (null != outputData && outputData.equalsIgnoreCase("200")) {
isVideoPosted = true;
} else{
isVideoPosted = false;
}
return isVideoPosted;
}
private class PostToServerAsyncTask extends AsyncTask<String, Void, String> {
private String content;
private String Error = null;
private int serverResponseCode;
Context context;
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("inputBuilder","PostToServerAsyncTask : onPreExecute Start") ;
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setIndeterminate(false);
//progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.YELLOW));
progressDialog.setCancelable(false);
progressDialog.show();
Log.i("inputBuilder","PostToServerAsyncTask : onPreExecute End") ;
}
#Override
protected String doInBackground(String... inputData) {
/*
File upload code
*/
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Some string";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("inputBuilder","PostToServerAsyncTask : onPostExecute Start") ;
if (null != progressDialog && progressDialog.isShowing()) {
progressDialog.dismiss();
}
Log.i("inputBuilder","PostToServerAsyncTask : onPostExecute End") ;
}
}
}
Could you please try this?
#Override
protected void onPreExecute() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setIndeterminate(false);
//progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.YELLOW));
progressDialog.setCancelable(false);
progressDialog.show();
});
}
I think the general problem is in async task, which actually is on the separate thread
I have problem with save current state in progress bar in SharedPreferences.
this is my code. Problem when go with this activity and next go out with activity agian ,progress bar don't count state with stay pervious.
private UpdateQrCode updateQrCode;
SharedPreferences sharedpreferences;
private static final String TIME = "Time";
method onCreate witch have
#Override
protected void onCreate(Bundle savedInstanceState) {
...
sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Time)) {
int currentInterval = sharedpreferences.getInt(TIME, 0);
progressBar.setMax(currentInterval);
progressBar.setProgress(currentInterval);
} else {
interval = Integer.parseInt(intervalTotpDecrypt);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (updateQrCode != null) {
updateQrCode.cancel(true);
}
}
//this class asyncTask with update progress bar
private class UpdateQrCode extends AsyncTask<Void, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setMax(interval);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
secondTimeTextView.setText(String.valueOf(values[0]));
}
#Override
protected Integer doInBackground(Void... params) {
for (int i = interval; i >= 0; i--) {
publishProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
try {
NewXorString = generateQrCodeString(otpDecrypt, path3Decrypt, intervalTotpDecrypt);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
generateNewString = Cryptography.xorHex(NewXorString);
UpdateQrCodeString(generateNewString);
updateQrCode.execute();
}
#Override
protected void onCancelled() {
super.onCancelled();
updateQrCode.cancel(true);
}
}
//method with save to sharedPreference
public void saveStateProgressBar() {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(TIME, interval);
editor.commit();
}
are you using Editor to store values in shared preferences? e.g
SharedPreferences.Editor editor = prefs.edit();
editor.putString("progress", loadingProgress);
editor.commit();
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
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.
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..