Progress dialog dismisses before the view is displayed in the gridview - android

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..

Related

Asynctask not executing while running but executing in debugging

Am executing two AsyncTask in an sequence manner. While debugging its working fine. But while running the app, second AysncTask not executing. Tried with THREAD_POOL_EXECUTOR not helping.below is my code.I don't have any idea about this problem.Below is my complete code.While running headerList.size() tgrowing zero. If the AsyncTask executed correctly, the size will be 2.
public class MainmenuActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainmenu);
networkCheck(context,rl);
}
private void loadPage(){
// new GetMenu().execute();
GetMenu getMenuTask = new GetMenu();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getMenuTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
getMenuTask.execute();
}
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
Menu menu = navigationView.getMenu();
System.out.println("List Size "+ headerList.size());
for(int i=0;i<headerList.size();i++)
{
String title = headerList.get(i).getMenuName().toString();
GlobalClass.menuId = headerList.get(i).getLangID().toString();
adapter.addFragment(new OneFragment(), title);
menu.add(title);
//viewPager.setAdapter(adapter);
}
viewPager.setAdapter(adapter);
}
private void networkCheck(Context context,LinearLayout rl) {
boolean isConnected = NetworkCheck.isNetworkAvailable(context);
if (isConnected) {
if(GlobalClass.languagueSelection.toString().equals("")){
LanguageSelectionDialog languagueDialog =new LanguageSelectionDialog(MainmenuActivity.this);
languagueDialog.show();
}else{
loadPage();
}
} else {
Snackbar snackbar = Snackbar
.make(rl, "No Internet Connection", Snackbar.LENGTH_LONG)
.setDuration(Snackbar.LENGTH_LONG)
.setAction("Retry", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainmenuActivity.this, MainmenuActivity.class);
startActivity(i);
finish();
}
});
}
}
private class GetMenu extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainmenuActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(menuURL);
Log.e(TAG, "Response from MenuURL: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray lanList = jsonObj.getJSONArray("menu");
for (int i = 0; i < lanList.length(); i++) {
JSONObject jsonObject1 = lanList.getJSONObject(i);
String langID = jsonObject1.optString("id");
String menuID = jsonObject1.optString("menu");
headerList.add(new Language(langID,menuID));
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainmenuActivity.this, "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainmenuActivity.this,
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
}
public class LanguageSelectionDialog extends Dialog {
public LanguageSelectionDialog(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.languagueSelection = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.languague_selection_dialog);
getLanguagues = new GetLanguagues();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getLanguagues.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
getLanguagues.execute();
} }
private class GetLanguagues extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(languagueURL);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray lanList = jsonObj.getJSONArray("language");
for (int i = 0; i < lanList.length(); i++) {
JSONObject jsonObject1 = lanList.getJSONObject(i);
String id = jsonObject1.optString("id");
String langId = jsonObject1.optString("language");
dashBoardList.add(new LanguagueSelection(id,langId));
lanlist.add(langId);
GlobalClass.langId=id;
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
spnLanguagueSelection.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, lanlist));
getLanguagues.cancel(true);
}
}
}
}
StackTrace while Running:
12-28 07:13:05.294 17448-17468/com.appathon.siva.news E/ContentValues: Response from url: {"language":[{"id":"21","language":"Hindi"},{"id":"20","language":"English"},{"id":"19","language":"Tamil"}]}
12-28 07:13:10.175 17448-17448/com.appathon.siva.news I/Choreographer: Skipped 297 frames! The application may be doing too much work on its main thread.
12-28 07:13:11.616 17448-17448/com.appathon.siva.news I/System.out: List Size 0
12-28 07:13:11.662 17448-17463/com.appathon.siva.news W/EGL_emulation: eglSurfaceAttrib not implemented
12-28 07:13:11.662 17448-17463/com.appathon.siva.news W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xf3fcd200, error=EGL_SUCCESS
12-28 07:13:11.682 17448-17472/com.appathon.siva.news E/ContentValues: Response from MenuURL: {"menu":[{"id":"14","menu":"Latest News"},{"id":"13","menu":"Top News"}]}
StackTrace while Debugging
12-28 07:27:17.155 17557-17579/com.appathon.siva.news E/ContentValues: Response from url: {"language":[{"id":"21","language":"Hindi"},{"id":"20","language":"English"},{"id":"19","language":"Tamil"}]}
12-28 07:27:17.166 17557-17573/com.appathon.siva.news W/EGL_emulation: eglSurfaceAttrib not implemented
12-28 07:27:17.166 17557-17573/com.appathon.siva.news W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe3873d40, error=EGL_SUCCESS
12-28 07:27:30.429 17557-17583/com.appathon.siva.news E/ContentValues: Response from MenuURL: {"menu":[{"id":"14","menu":"Latest News"},{"id":"13","menu":"Top News"}]}
12-28 07:27:33.836 17557-17557/com.appathon.siva.news I/System.out: List Size 2
List size is printing in different scenarios.

Dialog does not show via AsyncTask

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

View.Visible working fine in Marshmallow but not working on Kikat

View.Visible is working fine the above version 5.0 in android but not working on Kitkat version. Not getting actual problem, Am searched a lot but not getting solution following is my code. Thank you in advance
public class mainActivity extends AppCompatActivity implements View.OnClickListener {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stb_commands);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
button1.setVisibility(View.GONE);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
HashMap data = new HashMap();
new mainActivity.AsyncTaskGenre(data).execute();
break;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mainActivity.this);
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected String doInBackground(Void... params) {
String request = "http://";
try {
JSONObject json = jsonParser.makeHttpRequest(request, "POST",data);
return json.toString();
} catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pDialog.dismiss();
Log.d("RESULT ",""+s);
if (s != null) {
try {
JSONObject jsonObject = new JSONObject(s);
String error = jsonObject.get("error").toString();
Log.d("RESULT", " " +error);
if (error.equals("false"))
{
button1.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(getApplicationContext(),"not found...!",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{
Toast.makeText(getApplicationContext(),"check connection...!",Toast.LENGTH_LONG).show();
}
}
}
At first Compare your String Value Properly
Code Rectify
if (error.equals("false")) // Why you set == ?
{
button1.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(getApplicationContext(),"not found...!",Toast.LENGTH_SHORT).show();
}
FYI
JSON Response is
{"error":false,"1":{"id":6,"name":"Prash"}}
String getError=jsonObject .getString("error").toString();
Now do your code
if (error.equals("false"))
{
button1.setVisibility(View.VISIBLE);
}
In java you can use equels instead of ==
if (error.equalsIgnoreCase("false"))
{
button1.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(getApplicationContext(),"not found...!",Toast.LENGTH_SHORT).show();
}
I found the problem there is parsing issue thank you guys.
JSONObject jsonObject = new JSONObject(s);
String error = jsonObject.get("error").toString();
Log.d("RESULT", " " +error);
if (error.equals("false"))
{
Iterator keys = jsonObject.keys();
JSONObject currentDynamicValue;
int i=0;
while (keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String) keys.next();
if (!currentDynamicKey.equals("error")) {
// get the value of the dynamic key
currentDynamicValue = jsonObject.getJSONObject(currentDynamicKey);
list.put(i, currentDynamicValue.get("command_id").toString());
i++;
final String command_id = currentDynamicValue.get("command_id").toString();
if(command_id.equals("0"))
{
button1.setVisibility(View.VISIBLE);
}
else{
Toast.makeText(getApplicationContext(), "Command not Found..!" , Toast.LENGTH_SHORT).show();
}
}
}
Attach debugger inside onPostExecution() method, and handle your conditions according to the response. as there must be something wrong in "jsonObject.get("error").toString()"this.SO debug and handel your response you can.There is nothing wrong with setVisiblity(View.VISIBLE).
rest your code seems to be fine. Give it a try and then reply.

My AsyncTask not getting cancelled android

I am working on a task that calls my AsyncTask , once the async task is executed , I wait for 20 seconds to get the data from server , if it is still loading I am cancelling it (handling timeout)
public void handleServerTimeOut() {
getStore = new GetStore();
getStore.execute();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (getStore != null && getStore.getStatus() != AsyncTask.Status.FINISHED) {
boolean result = getStore.cancel(true);
Log.e(TAG, " handleServerTimeOut() reached 20 seconds");
Log.e(TAG, "" + result);
}
}
}, 20000);
}
AsyncTask
class GetStore extends AsyncTask<Void, Void, String> {
String status, message;
JSONArray jsonArray;
String buildingIdGuest, buildingIdUser, finalBuildingID;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isCancelled()) {
return;
} else {
buildingIdUser = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_USER, "");
buildingIdGuest = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_GUEST, "");
if (buildingIdUser.equals("0") || buildingIdUser.equals("")) {
finalBuildingID = buildingIdGuest;
} else {
finalBuildingID = buildingIdUser;
}
error_flag = 0;
gridView.setVisibility(View.VISIBLE);
error_layout.setVisibility(View.INVISIBLE);
img_no_internet.setVisibility(View.INVISIBLE);
img_no_results.setVisibility(View.INVISIBLE);
img_server_error.setVisibility(View.INVISIBLE);
progressDialog.setMessage("Getting nearby stores ...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(true);
progressDialog.show();
}
}
#Override
protected String doInBackground(Void... params) {
if (NetworkCheck.isNetworkAvailable(getActivity())) {
try {
jsonObj = userFunction.getStores(OS, MAKE, MODEL, finalBuildingID);
Log.e(TAG, jsonObj.toString());
status = jsonObj.getString("status");
message = jsonObj.getString("message");
if (status.equalsIgnoreCase("success")) {
jsonArray = jsonObj.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
gridModel = new GridModel();
gridModel.setId(jsonArray.getJSONObject(i).getString("id"));
gridModel.setStore_name(jsonArray.getJSONObject(i).getString("name"));
gridModel.setImage_name(jsonArray.getJSONObject(i).getString("image_name"));
gridListData.add(gridModel);
}
Log.e(TAG, "****** = " + gridListData.toString());
} else if (status.equalsIgnoreCase("invalid parameters")) {
error_flag = 2;
Log.e(TAG, "invalid parameters");
} else if (status.equalsIgnoreCase("no stores")) {
error_flag = 3;
Log.e(TAG, "No Data");
}
Log.e(TAG, "****** status " + status);
return String.valueOf(jsonObj);
} catch (Exception e) {
error_flag = 1; // Handling server timeout.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
return;
}
});
Log.e(TAG, e.toString());
}
} else {
Log.e(TAG, "Network Error");
error_flag = 1;
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Log.e(TAG, " **** error **** " + error_flag);
if (error_flag == 1) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_no_internet.setVisibility(View.VISIBLE);
} else if (error_flag == 2) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_server_error.setVisibility(View.VISIBLE);
txtError.setVisibility(View.VISIBLE);
txtError.setText(message);
} else if (error_flag == 3) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_no_results.setVisibility(View.VISIBLE);
}
gridAdapter = new GridAdapter(getActivity(), gridListData);
gridView.setAdapter(gridAdapter);
if ((progressDialog != null) && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
I also wanted to cancel my AsyncTask when the user cancels the ProgressDialog
You are checking isCancelled() only once in your AsyncTask - in the onPreExecute() method. At the time you call cancel() on your task instance, this check has already been evaluated and this is why the async task is still completing and updating the UI.
To deal with the issue, I suggest you include more checks for cancellation, using the isCancelled() method. One obvious place to include such a check is in the onPostExecute() method, right before you update the UI. You could also include a check before making the actual request to the server, after receiving the response, etc.

Fetching data in AsyncTask

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

Categories

Resources