Example usage for android.app ProgressDialog dismiss

List of usage examples for android.app ProgressDialog dismiss

Introduction

In this page you can find the example usage for android.app ProgressDialog dismiss.

Prototype

@Override
public void dismiss() 

Source Link

Document

Dismiss this dialog, removing it from the screen.

Usage

From source file:com.ccxt.whl.activity.LoginActivity.java

private void userinfo(String accessToken) {
    final ProgressDialog pd = new ProgressDialog(this);
    pd.setMessage("?...");
    pd.show();/*from w  w w.  j av  a  2s .c  o m*/

    mAuthorization.getUserInfo(accessToken, new UserInfoListener() {

        @Override
        public void onSuccess(FrontiaUser.FrontiaUserDetail result) {
            //if (null != mResultTextView) {
            Log.d("log useid===>" + result.getId());
            Log.d("log AccessToken===>" + result.getAccessToken());
            Log.d("log BaiduAccessToken===>" + result.getBaiduAccessToken());
            Log.d("log MediaUserId===>" + result.getMediaUserId());
            //Log.d("log MediaUserId===>"+result.get);

            String resultStr = "username:" + result.getName() + "\n" + "birthday:" + result.getBirthday() + "\n"
                    + "city:" + result.getCity() + "\n" + "province:" + result.getProvince() + "\n" + "sex:"
                    + result.getSex() + "\n" + "pic url:" + result.getHeadUrl() + "\n";
            Log.d("log userinfo===>" + resultStr);

            sex = "" + result.getSex();
            birthday = result.getBirthday();
            headurl = result.getHeadUrl();
            province = result.getProvince();
            city = result.getCity();

            RequestParams params = new RequestParams();
            params.add("name", name);
            params.add("access_token", access_token);
            params.add("sex", sex);
            params.add("birthday", birthday);
            params.add("headurl", headurl);
            params.add("province", province);
            params.add("city", city);
            params.add("meida_type", "sinaweibo");
            params.add("meida_uid", meida_uid);
            //id
            params.add("uid", uid);

            /*
             //Log.d("log",response);
                  try {
                     Map<String, Object> lm = JsonToMapList.getMap(response);
                       Map<String, Object> result = JsonToMapList.getMap(lm.get("result").toString());
                       String resultStr = "status:" + lm.get("status") + "\n"
                         + "message:" + lm.get("message") + "\n"
                         + "result:" + lm.get("result") + "\n"
                         + "uid:" + result.get("uid") + "\n"
                         + "umd5:" + result.get("umd5") + "\n"
                         + "is_res:" + result.get("is_res") + "\n";
                       Log.d("log",resultStr);
             } catch (Exception e) {
                // TODO: handle exception
             }
                         
                         
                 //String huanxin_username = MD5.MD5Hash(result.getName());
             //String huanxin_pwd = MD5.MD5Hash(result.getName());
             //s_reg_login(huanxin_username, huanxin_pwd);
             */

            HttpRestClient.get(Constant.S_LOGIN_URL, params, new BaseJsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse,
                        Object response) {
                    // TODO Auto-generated method stub
                    Log.d("log" + rawJsonResponse);
                    //if(str != null && str.length()!= 0){//?   
                    //}
                    if (!LoginActivity.this.isFinishing())
                        pd.dismiss();

                    if (CommonUtils.isNullOrEmpty(rawJsonResponse)) {
                        Toast.makeText(getApplicationContext(), "?,?", 0)
                                .show();
                        return;
                    }
                    Map<String, Object> lm = JsonToMapList.getMap(rawJsonResponse);

                    if (CommonUtils.isNullOrEmpty(lm.get("result").toString())) {
                        //if(false){

                    } else {
                        Map<String, Object> result = JsonToMapList.getMap(lm.get("result").toString());
                        String resultStr = "status:" + lm.get("status") + "\n" + "message:" + lm.get("message")
                                + "\n" + "result:" + lm.get("result") + "\n" + "uid:" + result.get("uid") + "\n"
                                + "umd5:" + result.get("umd5") + "\n" + "is_res:" + result.get("is_res") + "\n"
                                + "headurl:" + result.get("headurl") + "\n" + "name:" + result.get("name")
                                + "\n" + "sex:" + result.get("sex") + "\n" + "age:" + result.get("age") + "\n"
                                + "province:" + result.get("province") + "\n" + "city:" + result.get("city")
                                + "\n" + "pwd:" + result.get("pwd") + "\n";
                        Log.d("log" + resultStr);
                        //???id nullsaveinfo Preference
                        //DemoApplication.getInstance().setUser(result.get("umd5").toString());
                        //System.out.println("========================"+result.get("umd5").toString());
                        /********/
                        PreferenceUtils.getInstance(getBaseContext())
                                .setSettingUserPic(result.get("headurl").toString());
                        PreferenceUtils.getInstance(getBaseContext())
                                .setSettingUserNickName(result.get("name").toString());
                        PreferenceUtils.getInstance(getBaseContext())
                                .setSettingUserSex(result.get("sex").toString());
                        PreferenceUtils.getInstance(getBaseContext())
                                .setSettingUserAge(result.get("age").toString());
                        PreferenceUtils.getInstance(getBaseContext()).setSettingUserArea(
                                result.get("province").toString() + " " + result.get("city").toString());
                        PreferenceUtils.getInstance(getBaseContext())
                                .setSettingUserZhiye(result.get("zhiye").toString());
                        PreferenceUtils.getInstance(getBaseContext())
                                .setSettingUserQianming(result.get("qianming").toString());

                        String huanxin_username = result.get("umd5").toString();
                        String huanxin_pwd = result.get("pwd").toString();
                        Log.d("log huanxin_username:" + huanxin_username + "|huanxin_pwd:" + huanxin_pwd
                                + "|token:" + access_token);
                        //???
                        if (result.get("is_res").toString().equals("yes")) {
                            login(huanxin_username, huanxin_pwd);
                        } else {
                            s_reg_login(huanxin_username, huanxin_pwd);
                        }

                    }

                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData,
                        Object errorResponse) {
                    pd.dismiss();
                    Toast.makeText(getApplicationContext(), ",?", 0).show();
                    return;
                    // TODO Auto-generated method stub

                }

                @Override
                protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                    // TODO Auto-generated method stub
                    return null;
                }
            });

        }

        @Override
        public void onFailure(int errCode, String errMsg) {
            Log.d("log nihao ===>" + "errCode:" + errCode + ", errMsg:" + errMsg);
            sex = "";
            birthday = "";
            headurl = "";
            province = "";
            city = "";
            pd.dismiss();
            Toast.makeText(getApplicationContext(), "????", 0).show();
            return;
        }

    });
}

From source file:tm.veriloft.mapsplayground.MapsActivity.java

private void fetchAndDrawRoute(final LatLng... latLngs) {
    final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(SERVER_PORT);

    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Loading..");
    progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
        @Override/* w  ww  . java 2 s.co m*/
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            asyncHttpClient.cancelRequests(MapsActivity.this, true);
            showCenteredToast("Drawing route got cancelled");
        }
    });

    final RequestParams requestParams = new RequestParams();

    for (LatLng latLng : latLngs) {
        requestParams.add("loc", latLng.latitude + "," + latLng.longitude);
        l("Added latLng to request, " + latLng);
    }

    asyncHttpClient.get(this, SERVER, requestParams, new JsonHttpResponseHandler() {
        @Override
        public void onStart() {
            progressDialog.show();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            try {
                ArrayList<LatLng> route = MapUtils.decodePoly(response.getString("route_geometry"));
                PolylineOptions routeOptions = new PolylineOptions();

                for (int i = 0; i < route.size(); i++) {
                    routeOptions.add(route.get(i));
                    l("Returned point " + route.get(i));
                    if (returnedPointsMarkers)
                        addedMarkers.add(mMap.addMarker(new MarkerOptions().position(route.get(i))
                                .title("#" + i + " point of #" + drawnRoutes.size())));
                }

                routeOptions.width(ROUTE_WIDTH).color(ROUTE_COLOR);
                drawnRoutes.add(mMap.addPolyline(routeOptions));

                List<LatLng> points = routeOptions.getPoints();

                if (focusAfterRouteDraw)
                    focusTo(points.get(0), 13);

                if (endMarkerRouteDraw) {
                    LatLng trueEndPoint = MapUtils.findTrueEndPoint(latLngs[latLngs.length - 1], route.get(0),
                            route.get(route.size() - 1));
                    addedMarkers.add(mMap.addMarker(
                            new MarkerOptions().position(trueEndPoint).title("End of #" + drawnRoutes.size())));
                }

                if (requestedPointMarkerRouteDraw)
                    addedMarkers.add(mMap.addMarker(new MarkerOptions().position(latLngs[latLngs.length - 1])
                            .title("Requested point of #" + drawnRoutes.size())));

            } catch (JSONException exception) {
                exception.printStackTrace();
                showCenteredToast("Exception while parsing! Error: " + exception.getLocalizedMessage());
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
            showCenteredToast("Network error! Error: " + throwable.getLocalizedMessage());
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            showCenteredToast("Network error! Server returned non-json response, response: " + responseString
                    + ", Error: " + throwable.getLocalizedMessage());
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            showCenteredToast("Network error! Error: " + throwable.getLocalizedMessage());
        }

        @Override
        public void onFinish() {
            progressDialog.dismiss();
        }
    });
}

From source file:com.ccxt.whl.activity.LoginActivity.java

/**
 * ?//  w  w w. j  a  va  2s  .  com
 * 
 * @param view
 */
public void login(final String username, final String password) {
    if (!CommonUtils.isNetWorkConnected(this)) {
        Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
        return;
    }
    //final String username = usernameEditText.getText().toString();
    //final String password = passwordEditText.getText().toString();
    if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
        progressShow = true;
        final ProgressDialog pd = new ProgressDialog(LoginActivity.this);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                progressShow = false;
            }
        });
        pd.setMessage("...");
        pd.show();
        // sdk??
        EMChatManager.getInstance().login(username, password, new EMCallBack() {

            @Override
            public void onSuccess() {
                /*****************
                 * ?
                 *****************/
                if (!progressShow) {
                    return;
                }
                // ?????
                //               DemoApplication.getInstance().setUserName(username);
                DemoApplication.getInstance().setUser(username);
                DemoApplication.getInstance().setPassword(password);
                DemoApplication.getInstance().setUserNickName(name);
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.setMessage("???...");
                    }
                });
                try {
                    // demo??????username??
                    List<String> usernames = EMChatManager.getInstance().getContactUserNames();
                    Map<String, User> userlist = new HashMap<String, User>();
                    for (String username : usernames) {
                        User user = new User();
                        user.setUsername(username);
                        setUserHearder(username, user);
                        userlist.put(username, user);
                    }
                    // user""
                    User newFriends = new User();
                    newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
                    newFriends.setNick("");
                    newFriends.setHeader("");
                    userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
                    // "?"
                    User groupUser = new User();
                    groupUser.setUsername(Constant.GROUP_USERNAME);
                    groupUser.setNick("?");
                    groupUser.setHeader("");
                    userlist.put(Constant.GROUP_USERNAME, groupUser);

                    // 
                    DemoApplication.getInstance().setContactList(userlist);
                    /***?MainActivity?db* /
                    // db
                    UserDao dao = new UserDao(LoginActivity.this);
                    List<User> users = new ArrayList<User>(userlist.values());
                    dao.saveContactList(users);/**/

                    // ??,sdkEMGroupManagerdb
                    EMGroupManager.getInstance().getGroupsFromServer();
                    // after login, we join groups in separate threads;
                    EMGroupManager.getInstance().joinGroupsAfterLogin();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (!LoginActivity.this.isFinishing())
                    pd.dismiss();
                // ?
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, final String message) {
                if (!progressShow) {
                    return;
                }
                //Log.d("log","code"+code);
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();

                        Toast.makeText(getApplicationContext(), ": " + message, 0).show();

                    }
                });
            }
        });
    }
}

From source file:com.nttec.everychan.chans.fourchan.FourchanModule.java

private void addPasscodePreference(PreferenceGroup preferenceGroup) {
    final Context context = preferenceGroup.getContext();
    PreferenceScreen passScreen = preferenceGroup.getPreferenceManager().createPreferenceScreen(context);
    passScreen.setTitle("4chan pass");
    EditTextPreference passTokenPreference = new EditTextPreference(context);
    EditTextPreference passPINPreference = new EditTextPreference(context);
    Preference passLoginPreference = new Preference(context);
    Preference passClearPreference = new Preference(context);
    passTokenPreference.setTitle("Token");
    passTokenPreference.setDialogTitle("Token");
    passTokenPreference.setKey(getSharedKey(PREF_KEY_PASS_TOKEN));
    passTokenPreference.getEditText().setSingleLine();
    passTokenPreference.getEditText()/*from   w  w w . j  a  v  a 2 s  .  c o  m*/
            .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
    passPINPreference.setTitle("PIN");
    passPINPreference.setDialogTitle("PIN");
    passPINPreference.setKey(getSharedKey(PREF_KEY_PASS_PIN));
    passPINPreference.getEditText().setSingleLine();
    passPINPreference.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
    passLoginPreference.setTitle("Log In");
    passLoginPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (!useHttps())
                Toast.makeText(context, "Using HTTPS even if HTTP is selected", Toast.LENGTH_SHORT).show();
            final String token = preferences.getString(getSharedKey(PREF_KEY_PASS_TOKEN), "");
            final String pin = preferences.getString(getSharedKey(PREF_KEY_PASS_PIN), "");
            final String authUrl = "https://sys.4chan.org/auth"; //only https
            final CancellableTask passAuthTask = new CancellableTask.BaseCancellableTask();
            final ProgressDialog passAuthProgressDialog = new ProgressDialog(context);
            passAuthProgressDialog.setMessage("Logging in");
            passAuthProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    passAuthTask.cancel();
                }
            });
            passAuthProgressDialog.setCanceledOnTouchOutside(false);
            passAuthProgressDialog.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (passAuthTask.isCancelled())
                            return;
                        setPasscodeCookie(null, true);
                        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                        pairs.add(new BasicNameValuePair("act", "do_login"));
                        pairs.add(new BasicNameValuePair("id", token));
                        pairs.add(new BasicNameValuePair("pin", pin));
                        HttpRequestModel request = HttpRequestModel.builder()
                                .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).build();
                        String response = HttpStreamer.getInstance().getStringFromUrl(authUrl, request,
                                httpClient, null, passAuthTask, false);
                        if (passAuthTask.isCancelled())
                            return;
                        if (response.contains("Your device is now authorized")) {
                            String passId = null;
                            for (Cookie cookie : httpClient.getCookieStore().getCookies()) {
                                if (cookie.getName().equals("pass_id")) {
                                    String value = cookie.getValue();
                                    if (!value.equals("0")) {
                                        passId = value;
                                        break;
                                    }
                                }
                            }
                            if (passId == null) {
                                showToast("Could not get pass id");
                            } else {
                                setPasscodeCookie(passId, true);
                                showToast("Success! Your device is now authorized.");
                            }
                        } else if (response.contains("Your Token must be exactly 10 characters")) {
                            showToast("Incorrect token");
                        } else if (response.contains("You have left one or more fields blank")) {
                            showToast("You have left one or more fields blank");
                        } else if (response.contains("Incorrect Token or PIN")) {
                            showToast("Incorrect Token or PIN");
                        } else {
                            Matcher m = Pattern
                                    .compile("<strong style=\"color: red; font-size: larger;\">(.*?)</strong>")
                                    .matcher(response);
                            if (m.find()) {
                                showToast(m.group(1));
                            } else {
                                showWebView(response);
                            }
                        }
                    } catch (Exception e) {
                        showToast(e.getMessage() == null ? resources.getString(R.string.error_unknown)
                                : e.getMessage());
                    } finally {
                        passAuthProgressDialog.dismiss();
                    }
                }

                private void showToast(final String message) {
                    if (context instanceof Activity) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }

                private void showWebView(final String html) {
                    if (context instanceof Activity) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                WebView webView = new WebView(context);
                                webView.getSettings().setSupportZoom(true);
                                webView.loadData(html, "text/html", null);
                                new AlertDialog.Builder(context).setView(webView)
                                        .setNeutralButton(android.R.string.ok, null).show();
                            }
                        });
                    }
                }
            });
            return true;
        }
    });
    passClearPreference.setTitle("Reset pass cookie");
    passClearPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            setPasscodeCookie(null, true);
            Toast.makeText(context, "Cookie is reset", Toast.LENGTH_LONG).show();
            return true;
        }
    });
    passScreen.addPreference(passTokenPreference);
    passScreen.addPreference(passPINPreference);
    passScreen.addPreference(passLoginPreference);
    passScreen.addPreference(passClearPreference);
    preferenceGroup.addPreference(passScreen);
}

From source file:net.nightwhistler.pageturner.fragment.ReadingFragment.java

public void performSearch(String query) {

    LOG.debug("Starting search for: " + query);

    final ProgressDialog searchProgress = new ProgressDialog(context);
    searchProgress.setOwnerActivity(getActivity());
    searchProgress.setCancelable(true);/*w w  w .  j a  v a2 s.  c om*/
    searchProgress.setMax(100);
    searchProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

    final int[] counter = { 0 }; //Yes, this is essentially a pointer to an int :P

    final SearchTextTask task = new SearchTextTask(bookView.getBook());

    task.setOnPreExecute(() -> {

        searchProgress.setMessage(getString(R.string.search_wait));
        searchProgress.show();

        // Hide on-screen keyboard if it is showing
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

    });

    task.setOnProgressUpdate((values) -> {

        if (isAdded()) {

            LOG.debug("Found match at index=" + values[0].getIndex() + ", offset=" + values[0].getStart()
                    + " with context " + values[0].getDisplay());
            SearchResult res = values[0];

            if (res.getDisplay() != null) {
                counter[0] = counter[0] + 1;
                String update = String.format(getString(R.string.search_hits), counter[0]);
                searchProgress.setMessage(update);
            }

            searchProgress.setProgress(bookView.getPercentageFor(res.getIndex(), res.getStart()));
        }
    });

    task.setOnCancelled((result) -> {
        if (isAdded()) {
            Toast.makeText(context, R.string.search_cancelled, Toast.LENGTH_LONG).show();
        }
    });

    task.setOnPostExecute((result) -> {
        searchProgress.dismiss();

        if (!task.isCancelled() && isAdded()) {

            List<SearchResult> resultList = result.getOrElse(new ArrayList<>());

            if (resultList.size() > 0) {
                searchResults = resultList;
                showSearchResultDialog(resultList);
            } else {
                Toast.makeText(context, R.string.search_no_matches, Toast.LENGTH_LONG).show();
            }
        }
    });

    searchProgress.setOnCancelListener(dialog -> task.cancel(true));
    executeTask(task, query);
}

From source file:com.atahani.telepathy.ui.fragment.AboutDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View customLayout = inflater.inflate(R.layout.fragment_about_dialog, null);
    //config app version information
    mAppPreferenceTools = new AppPreferenceTools(TApplication.applicationContext);
    AppCompatTextView txAndroidAppVerInfo = (AppCompatTextView) customLayout
            .findViewById(R.id.tx_android_ver_info);
    txAndroidAppVerInfo.setText(String.format(getString(R.string.label_telepathy_for_android),
            mAppPreferenceTools.getTheLastAppVersion()));
    txAndroidAppVerInfo.setOnClickListener(new View.OnClickListener() {
        @Override/* w  w w.ja  va  2 s .  c om*/
        public void onClick(View v) {
            try {
                //open browser to navigate telepathy website
                Uri telepathyWebSiteUri = Uri.parse("https://github.com/atahani/telepathy-android.git");
                startActivity(new Intent(Intent.ACTION_VIEW, telepathyWebSiteUri));
                ((TelepathyBaseActivity) getActivity()).setAnimationOnStart();
            } catch (Exception ex) {
                AndroidUtilities.processApplicationError(ex, true);
                if (isAdded() && getActivity() != null) {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            getString(R.string.re_action_internal_app_error), Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });
    //config google play store link
    AppCompatTextView txRateUsOnGooglePlayStore = (AppCompatTextView) customLayout
            .findViewById(R.id.tx_rate_us_on_play_store);
    txRateUsOnGooglePlayStore.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //navigate to market for rate application
            Uri uri = Uri.parse("market://details?id=" + TApplication.applicationContext.getPackageName());
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
            // To count with Play market backstack, After pressing back button,
            // to taken back to our application, we need to add following flags to intent.
            goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
            try {
                startActivity(goToMarket);
                ((TelepathyBaseActivity) getActivity()).setAnimationOnStart();
            } catch (ActivityNotFoundException e) {
                startActivity(
                        new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id="
                                + TApplication.applicationContext.getPackageName())));
            }
        }
    });
    //config twitter link
    AppCompatTextView txTwitterLink = (AppCompatTextView) customLayout.findViewById(R.id.tx_twitter_telepathy);
    txTwitterLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                // If Twitter app is not installed, start browser.
                Uri twitterUri = Uri.parse("http://twitter.com/");
                startActivity(new Intent(Intent.ACTION_VIEW, twitterUri));
                ((TelepathyBaseActivity) getActivity()).setAnimationOnStart();
            } catch (Exception ex) {
                AndroidUtilities.processApplicationError(ex, true);
                if (isAdded() && getActivity() != null) {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            getString(R.string.re_action_internal_app_error), Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });
    //config privacy link
    AppCompatTextView txPrivacyLink = (AppCompatTextView) customLayout.findViewById(R.id.tx_privacy);
    txPrivacyLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                //open browser to navigate privacy link
                Uri privacyPolicyUri = Uri
                        .parse("https://github.com/atahani/telepathy-android/blob/master/LICENSE.md");
                startActivity(new Intent(Intent.ACTION_VIEW, privacyPolicyUri));
                ((TelepathyBaseActivity) getActivity()).setAnimationOnStart();
            } catch (Exception ex) {
                AndroidUtilities.processApplicationError(ex, true);
                if (isAdded() && getActivity() != null) {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            getString(R.string.re_action_internal_app_error), Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });
    //config report bug to open mail application and send bugs report
    AppCompatTextView txReportBug = (AppCompatTextView) customLayout.findViewById(R.id.tx_report_bug);
    txReportBug.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                final Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
                emailIntent.setType("plain/text");
                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        getString(R.string.label_report_bug_email_subject));
                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailDeviceInformation());
                emailIntent.setData(Uri.parse("mailto:" + getString(R.string.telepathy_report_bug_email)));
                startActivity(Intent.createChooser(emailIntent,
                        getString(R.string.label_report_bug_choose_mail_app)));
                ((TelepathyBaseActivity) getActivity()).setAnimationOnStart();
            } catch (Exception ex) {
                AndroidUtilities.processApplicationError(ex, true);
                if (isAdded() && getActivity() != null) {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            getString(R.string.re_action_internal_app_error), Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });
    //config the about footer image view
    AboutFooterImageView footerImageView = (AboutFooterImageView) customLayout
            .findViewById(R.id.im_delete_user_account);
    footerImageView.setTouchOnImageViewEventListener(new AboutFooterImageView.touchOnImageViewEventListener() {
        @Override
        public void onDoubleTab() {
            try {
                //confirm account delete via alert dialog
                final AlertDialog.Builder confirmAccountDeleteDialog = new AlertDialog.Builder(getActivity());
                confirmAccountDeleteDialog.setTitle(getString(R.string.label_delete_user_account));
                confirmAccountDeleteDialog
                        .setMessage(getString(R.string.label_delete_user_account_description));
                confirmAccountDeleteDialog.setNegativeButton(getString(R.string.action_no), null);
                confirmAccountDeleteDialog.setPositiveButton(getString(R.string.action_yes),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //ok to delete account action
                                final ProgressDialog progressDialog = new ProgressDialog(getActivity());
                                progressDialog.setCancelable(false);
                                progressDialog.setCanceledOnTouchOutside(false);
                                progressDialog
                                        .setMessage(getString(R.string.re_action_on_deleting_user_account));
                                progressDialog.show();
                                TService tService = ((TelepathyBaseActivity) getActivity()).getTService();
                                tService.deleteUserAccount(new Callback<TOperationResultModel>() {
                                    @Override
                                    public void success(TOperationResultModel tOperationResultModel,
                                            Response response) {
                                        if (getActivity() != null && isAdded()) {
                                            //broad cast to close all of the realm  instance
                                            Intent intentToCloseRealm = new Intent(
                                                    Constants.TELEPATHY_BASE_ACTIVITY_INTENT_FILTER);
                                            intentToCloseRealm.putExtra(Constants.ACTION_TO_DO_PARAM,
                                                    Constants.CLOSE_REALM_DB);
                                            LocalBroadcastManager.getInstance(getActivity())
                                                    .sendBroadcastSync(intentToCloseRealm);
                                            mAppPreferenceTools.removeAllOfThePref();
                                            //                                 for sign out google first build GoogleAPIClient
                                            final GoogleApiClient googleApiClient = new GoogleApiClient.Builder(
                                                    TApplication.applicationContext)
                                                            .addApi(Auth.GOOGLE_SIGN_IN_API).build();
                                            googleApiClient.connect();
                                            googleApiClient.registerConnectionCallbacks(
                                                    new GoogleApiClient.ConnectionCallbacks() {
                                                        @Override
                                                        public void onConnected(Bundle bundle) {
                                                            Auth.GoogleSignInApi.signOut(googleApiClient)
                                                                    .setResultCallback(
                                                                            new ResultCallback<Status>() {
                                                                                @Override
                                                                                public void onResult(
                                                                                        Status status) {
                                                                                    //also revoke google access
                                                                                    Auth.GoogleSignInApi
                                                                                            .revokeAccess(
                                                                                                    googleApiClient)
                                                                                            .setResultCallback(
                                                                                                    new ResultCallback<Status>() {
                                                                                                        @Override
                                                                                                        public void onResult(
                                                                                                                Status status) {
                                                                                                            progressDialog
                                                                                                                    .dismiss();
                                                                                                            TelepathyBaseActivity currentActivity = (TelepathyBaseActivity) TApplication.mCurrentActivityInApplication;
                                                                                                            if (currentActivity != null) {
                                                                                                                Intent intent = new Intent(
                                                                                                                        TApplication.applicationContext,
                                                                                                                        SignInActivity.class);
                                                                                                                intent.setFlags(
                                                                                                                        Intent.FLAG_ACTIVITY_CLEAR_TASK
                                                                                                                                | Intent.FLAG_ACTIVITY_NEW_TASK);
                                                                                                                currentActivity
                                                                                                                        .startActivity(
                                                                                                                                intent);
                                                                                                                currentActivity
                                                                                                                        .setAnimationOnStart();
                                                                                                                currentActivity
                                                                                                                        .finish();
                                                                                                            }
                                                                                                        }
                                                                                                    });
                                                                                }
                                                                            });
                                                        }

                                                        @Override
                                                        public void onConnectionSuspended(int i) {
                                                            //do nothing
                                                        }
                                                    });
                                        }
                                    }

                                    @Override
                                    public void failure(RetrofitError error) {
                                        progressDialog.dismiss();
                                        if (getActivity() != null && isAdded()) {
                                            CommonFeedBack commonFeedBack = new CommonFeedBack(
                                                    getActivity().findViewById(android.R.id.content),
                                                    getActivity());
                                            commonFeedBack.checkCommonErrorAndBackUnCommonOne(error);
                                        }
                                    }
                                });
                            }
                        });
                confirmAccountDeleteDialog.show();
            } catch (Exception ex) {
                AndroidUtilities.processApplicationError(ex, true);
                if (isAdded() && getActivity() != null) {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            getString(R.string.re_action_internal_app_error), Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });
    builder.setView(customLayout);
    return builder.create();
}

From source file:com.progym.custom.fragments.CalloriesProgressYearlyLineFragment.java

public void setYearProgressData(final Date date, final boolean isLeftIn) {

    final ProgressDialog ringProgressDialog = ProgressDialog.show(getActivity(),
            getResources().getString(R.string.please_wait), getResources().getString(R.string.populating_data),
            true);//from w  w  w . jav  a 2  s.  c  o m
    ringProgressDialog.setCancelable(true);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                int yMaxAxisValue = 0;

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            rlRootGraphLayout.removeView(viewChart);
                        } catch (Exception edsx) {
                            edsx.printStackTrace();
                        }
                    }
                });

                DATE = date;
                // Get amount of days in a month to find out average
                int daysInMonth = Utils.getDaysInMonth(date.getMonth(),
                        Integer.valueOf(Utils.formatDate(date, DataBaseUtils.DATE_PATTERN_YYYY)));
                // set January as first month
                date.setMonth(0);
                date.setDate(1);

                int[] x = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

                final XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
                CategorySeries seriesCallories = new CategorySeries("Callories");

                List<Ingridient> list;
                Date dt = date; // *
                for (int element : x) {
                    list = DataBaseUtils.getAllFoodConsumedInMonth(
                            Utils.formatDate(dt, DataBaseUtils.DATE_PATTERN_YYYY_MM));

                    // init "average" data
                    int totalCallories = 0;
                    for (Ingridient ingridient : list) {
                        totalCallories += ingridient.kkal;
                    }
                    // add value to series
                    seriesCallories.add(totalCallories / daysInMonth);
                    // calculate maximum Y axis values
                    yMaxAxisValue = Math.max(yMaxAxisValue, totalCallories / daysInMonth);
                    // increment month
                    dt = DateUtils.addMonths(dt, 1);
                }

                int[] colors = new int[] { getActivity().getResources().getColor(R.color.purple) };
                final XYMultipleSeriesRenderer renderer = buildBarRenderer(colors);
                setChartSettings(renderer,
                        String.format("Callories statistic for %s year",
                                Utils.getSpecificDateValue(DATE, "yyyy")),
                        "Months", "Calories consumption", 0.7, 12.3, 0, yMaxAxisValue + 30, Color.GRAY,
                        Color.LTGRAY);

                renderer.getSeriesRendererAt(0).setDisplayChartValues(true);
                renderer.getSeriesRendererAt(0).setChartValuesTextSize(15f);
                renderer.setXLabels(0);
                renderer.setClickEnabled(false);
                renderer.setZoomEnabled(false);
                renderer.setPanEnabled(false, false);
                renderer.setZoomButtonsVisible(false);
                renderer.setPanLimits(new double[] { 1, 11 });
                renderer.setShowGrid(true);
                renderer.setShowLegend(true);
                renderer.setFitLegend(true);

                for (int i = 0; i < ActivityWaterProgress.months_short.length; i++) {
                    renderer.addXTextLabel(i + 1, ActivityWaterProgress.months_short[i]);

                }
                dataset.addSeries(seriesCallories.toXYSeries());

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        viewChart = ChartFactory.getBarChartView(getActivity(), dataset, renderer,
                                Type.DEFAULT);
                        rlRootGraphLayout.addView(viewChart, 0);

                        if (isLeftIn) {
                            rightIn.setDuration(1000);
                            viewChart.startAnimation(rightIn);
                        } else {
                            leftIn.setDuration(1000);
                            viewChart.startAnimation(leftIn);
                        }
                    }
                });

            } catch (Exception e) {
            }
            ringProgressDialog.dismiss();
        }
    }).start();

}

From source file:net.nightwhistler.pageturner.activity.ReadingFragment.java

@Override
public void performSearch(String query) {

    LOG.debug("Starting search for: " + query);

    final ProgressDialog searchProgress = new ProgressDialog(context);
    searchProgress.setOwnerActivity(getActivity());
    searchProgress.setCancelable(true);/*from www  . ja  v a 2s  .  c o  m*/
    searchProgress.setMax(100);
    searchProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

    final SearchTextTask task = new SearchTextTask(bookView.getBook()) {

        int i = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            searchProgress.setMessage(getString(R.string.search_wait));
            searchProgress.show();

            // Hide on-screen keyboard if it is showing
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

        }

        @Override
        protected void onProgressUpdate(SearchResult... values) {

            if (!isAdded()) {
                return;
            }

            super.onProgressUpdate(values);

            LOG.debug("Found match at index=" + values[0].getIndex() + ", offset=" + values[0].getStart()
                    + " with context " + values[0].getDisplay());
            SearchResult res = values[0];

            if (res.getDisplay() != null) {
                i++;
                String update = String.format(getString(R.string.search_hits), i);
                searchProgress.setMessage(update);
            }

            searchProgress.setProgress(bookView.getPercentageFor(res.getIndex(), res.getStart()));
        }

        @Override
        protected void onCancelled() {
            if (isAdded()) {
                Toast.makeText(context, R.string.search_cancelled, Toast.LENGTH_LONG).show();
            }
        }

        protected void onPostExecute(java.util.List<SearchResult> result) {

            searchProgress.dismiss();

            if (!isCancelled() && isAdded()) {
                if (result.size() > 0) {
                    searchResults = result;
                    showSearchResultDialog(result);
                } else {
                    Toast.makeText(context, R.string.search_no_matches, Toast.LENGTH_LONG).show();
                }
            }
        };
    };

    searchProgress.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            task.cancel(true);
        }
    });

    task.execute(query);
}

From source file:com.dmsl.anyplace.UnifiedNavigationActivity.java

private void startNavigationTask(String id) {

    if (!NetworkUtils.isOnline(this)) {
        Toast.makeText(this, "No connection available!", Toast.LENGTH_SHORT).show();
        return;//from   w  w  w.  jav  a 2s  .  c  o  m
    }

    // show the info window for the destination marker
    Marker marker = visiblePois.getMarkerFromPoisModel(id);
    if (marker != null) {
        marker.showInfoWindow();
    }

    final BuildingModel b = userData.getSelectedBuilding();
    final String floor = userData.getSelectedFloorNumber();

    class Status {
        Boolean task1 = false;
        Boolean task2 = false;
    }
    final Status status = new Status();

    final ProgressDialog dialog;
    dialog = new ProgressDialog(this);
    dialog.setIndeterminate(true);
    dialog.setTitle("Plotting navigation");
    dialog.setMessage("Please be patient...");
    dialog.setCancelable(true);
    dialog.setCanceledOnTouchOutside(false);

    GeoPoint entrance = null;
    GeoPoint pos = userData.getPositionWifi();
    if (pos == null) {
        // Find The nearest building entrance from the destination poi
        PoisModel _entrance = null;
        PoisModel dest = mAnyplaceCache.getPoisMap().get(id);
        double min = Double.MAX_VALUE;
        String currentFloor = userData.getSelectedFloorNumber();
        for (PoisModel pm : mAnyplaceCache.getPoisMap().values()) {
            if (pm.floor_number.equalsIgnoreCase(currentFloor) && pm.is_building_entrance) {
                double distance = Math.abs(pm.lat() - dest.lat()) + Math.abs(pm.lng() - dest.lng());
                if (min > distance) {
                    _entrance = pm;
                    min = distance;
                }
            }
        }

        if (_entrance != null) {
            entrance = new GeoPoint(_entrance.lat(), _entrance.lng());
        } else {
            Toast.makeText(this, "No entrance found!", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    final GeoPoint entrancef = entrance;

    // Does not run if entrance==null or is near the building
    final AsyncTask<Void, Void, String> async1f = new NavDirectionsTask(
            new NavDirectionsTask.NavDirectionsListener() {

                @Override
                public void onNavDirectionsSuccess(String result, List<LatLng> points) {
                    onNavDirectionsAboart();

                    if (!points.isEmpty()) {
                        // points.add(new LatLng(entrancef.dlat, entrancef.dlon));
                        pathLineOutsideOptions = new PolylineOptions().addAll(points).width(10).color(Color.RED)
                                .zIndex(100.0f);
                        pathLineOutside = mMap.addPolyline(pathLineOutsideOptions);
                    }
                }

                @Override
                public void onNavDirectionsErrorOrCancel(String result) {
                    onNavDirectionsAboart();
                    // display the error cause
                    Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onNavDirectionsAboart() {
                    status.task1 = true;
                    if (status.task1 && status.task2)
                        dialog.dismiss();
                    else {
                        // First task executed calls this
                        clearLastNavigationInfo();
                    }
                }

            }, userData.getLocationGPSorIP(), entrance);

    // start the navigation task
    final AsyncTask<Void, Void, String> async2f = new NavRouteTask(new NavRouteTask.NavRouteListener() {
        @Override
        public void onNavRouteSuccess(String result, List<PoisNav> points) {
            onNavDirectionsAboart();

            // set the navigation building and new points
            userData.setNavBuilding(b);
            userData.setNavPois(points);

            // handle drawing of the points
            handlePathDrawing(points);
        }

        @Override
        public void onNavRouteErrorOrCancel(String result) {
            onNavDirectionsAboart();
            // display the error cause
            Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
        }

        public void onNavDirectionsAboart() {
            status.task2 = true;
            if (status.task1 && status.task2)
                dialog.dismiss();
            else {
                // First task executed calls this
                clearLastNavigationInfo();
            }
        }
    }, this, id, (pos == null) ? entrancef : pos, floor);

    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            async1f.cancel(true);
            async2f.cancel(true);
        }
    });
    dialog.show();
    async1f.execute();
    async2f.execute();
}

From source file:org.linphone.ContactsManager.java

public synchronized void prepareContactsInBackgroundWithUI(final Activity activity,
        final FragmentManager manager, final ProgressDialog pd) {
    if (contactCursor != null) {
        contactCursor.close();//from   w  ww  .j a  v a  2  s. com
    }
    if (sipContactCursor != null) {
        sipContactCursor.close();
    }

    //      if(LinphoneActivity.instance().getResources().getBoolean(R.bool.use_linphone_friend)){
    //         contactList = new ArrayList<Contact>();
    //         for(LinphoneFriend friend : LinphoneManager.getLc().getFriendList()){
    //            Contact contact = new Contact(friend.getRefKey(),friend.getAddress());
    //            contactList.add(contact);
    //         }
    //         contactCursor = getFriendListCursor(contactList,true);
    //         return;
    //      }

    Log.e("LINPHONE", "preparing contacts in background:use_linphone_friend");
    //if(mAccount == null) return;

    contactCursor = Compatibility.getContactsCursor(contentResolver, getContactsId());

    Log.e("LINPHONE", "preparing contacts in background contactCursor" + contactCursor == null);
    sipContactCursor = Compatibility.getSIPContactsCursor(contentResolver, getContactsId());

    Thread sipContactsHandler = new Thread(new Runnable() {
        @Override
        public void run() {
            if (sipContactCursor != null && sipContactCursor.getCount() > 0) {
                for (int i = 0; i < sipContactCursor.getCount(); i++) {
                    Contact contact = Compatibility.getContact(contentResolver, sipContactCursor, i);
                    if (contact == null)
                        continue;

                    contact.refresh(contentResolver);
                    //Add tag to Linphone contact if it not existed
                    if (LinphoneActivity.isInstanciated()
                            && LinphoneActivity.instance().getResources().getBoolean(R.bool.use_linphone_tag)) {
                        if (!isContactHasLinphoneTag(contact, contentResolver)) {
                            Compatibility.createLinphoneContactTag(context, contentResolver, contact,
                                    findRawContactID(contentResolver, String.valueOf(contact.getID())));
                        }
                    }

                    sipContactList.add(contact);
                }
            }
            if (contactCursor != null) {
                for (int i = 0; i < contactCursor.getCount(); i++) {
                    Contact contact = Compatibility.getContact(contentResolver, contactCursor, i);
                    if (contact == null)
                        continue;

                    //Remove linphone contact tag if the contact has no sip address
                    if (LinphoneActivity.isInstanciated()
                            && LinphoneActivity.instance().getResources().getBoolean(R.bool.use_linphone_tag)) {
                        if (removeContactTagIsNeeded(contact)
                                && findRawLinphoneContactID(contact.getID()) != null) {
                            removeLinphoneContactTag(contact);
                        }
                    }
                    for (Contact c : sipContactList) {
                        if (c != null && c.getID().equals(contact.getID())) {
                            contact = c;
                            break;
                        }
                    }
                    contactList.add(contact);
                }

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pd.dismiss();
                        manager.popBackStackImmediate();
                    }
                });
            }
        }
    });

    contactList = new ArrayList<Contact>();
    sipContactList = new ArrayList<Contact>();

    sipContactsHandler.start();
}