Example usage for android.app AlertDialog.Builder setCancelable

List of usage examples for android.app AlertDialog.Builder setCancelable

Introduction

In this page you can find the example usage for android.app AlertDialog.Builder setCancelable.

Prototype

public void setCancelable(boolean flag) 

Source Link

Document

Sets whether this dialog is cancelable with the KeyEvent#KEYCODE_BACK BACK key.

Usage

From source file:com.speed.traquer.app.TraqComplaintTaxi.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_traq_complaint_taxi);
    easyTracker = EasyTracker.getInstance(TraqComplaintTaxi.this);
    //onCreateView(savedInstanceState);
    //InitialSetupUI();

    //Added UIHelper
    uiHelper = new UiLifecycleHelper(this, null);
    uiHelper.onCreate(savedInstanceState);

    inputTaxi = (EditText) findViewById(R.id.taxi_id);
    taxiDriver = (EditText) findViewById(R.id.taxi_driver);
    taxiLic = (EditText) findViewById(R.id.taxi_license);
    geoLat = (TextView) findViewById(R.id.geoLat);
    geoLong = (TextView) findViewById(R.id.geoLong);
    editDate = (EditText) findViewById(R.id.editDate);
    editTime = (EditText) findViewById(R.id.editTime);
    editCurrTime = (EditText) findViewById(R.id.editCurrTime);
    complainSend = (Button) findViewById(R.id.complain_send);

    ProgressBar barProgress = (ProgressBar) findViewById(R.id.progressLoading);
    ProgressBar barProgressFrom = (ProgressBar) findViewById(R.id.progressLoadingFrom);
    ProgressBar barProgressTo = (ProgressBar) findViewById(R.id.progressLoadingTo);

    actv_comp_taxi = (AutoCompleteTextView) findViewById(R.id.search_taxi_comp);
    SuggestionAdapter sa = new SuggestionAdapter(this, actv_comp_taxi.getText().toString(), taxiUrl,
            "compcode");
    sa.setLoadingIndicator(barProgress);
    actv_comp_taxi.setAdapter(sa);/*from  w  w  w.ja  v a2  s . c o  m*/

    actv_from = (AutoCompleteTextView) findViewById(R.id.search_from);
    SuggestionAdapter saFrom = new SuggestionAdapter(this, actv_from.getText().toString(), locUrl, "location");
    saFrom.setLoadingIndicator(barProgressFrom);
    actv_from.setAdapter(saFrom);

    actv_to = (AutoCompleteTextView) findViewById(R.id.search_to);
    SuggestionAdapter saTo = new SuggestionAdapter(this, actv_to.getText().toString(), locUrl, "location");
    saTo.setLoadingIndicator(barProgressTo);
    actv_to.setAdapter(saTo);

    /*if(isNetworkConnected()) {
    new getTaxiComp().execute(new ApiConnector());
    }*/

    //Setting Fonts
    String fontPath = "fonts/segoeuil.ttf";
    Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
    complainSend.setTypeface(tf);
    inputTaxi.setTypeface(tf);
    editDate.setTypeface(tf);
    editTime.setTypeface(tf);
    actv_comp_taxi.setTypeface(tf);
    actv_to.setTypeface(tf);
    actv_from.setTypeface(tf);
    taxiDriver.setTypeface(tf);
    taxiLic.setTypeface(tf);

    TextView txtComp = (TextView) findViewById(R.id.taxi_comp);
    txtComp.setTypeface(tf);

    TextView txtTaxiDriver = (TextView) findViewById(R.id.txt_taxi_driver);
    txtTaxiDriver.setTypeface(tf);

    TextView txtTaxiLic = (TextView) findViewById(R.id.txt_taxi_license);
    txtTaxiLic.setTypeface(tf);

    TextView txtNumber = (TextView) findViewById(R.id.taxi_number);
    txtNumber.setTypeface(tf);

    TextView txtTo = (TextView) findViewById(R.id.to);
    txtTo.setTypeface(tf);

    TextView txtDate = (TextView) findViewById(R.id.date);
    txtDate.setTypeface(tf);

    TextView txtTime = (TextView) findViewById(R.id.time);
    txtTime.setTypeface(tf);

    gLongitude = this.getIntent().getExtras().getDouble("Longitude");
    gLatitude = this.getIntent().getExtras().getDouble("Latitude");
    speedTaxiExceed = this.getIntent().getExtras().getDouble("SpeedTaxiExceed");

    isTwitterSelected = false;
    isFacebookSelected = false;
    isDefaultSelected = false;
    isSmsSelected = false;

    geoLat.setText(Double.toString(gLatitude));
    geoLong.setText(Double.toString(gLongitude));

    rateBtnBus = (ImageButton) findViewById(R.id.btn_rate_bus);

    rateBtnBus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (actv_comp_taxi.length() != 0) {
                final AlertDialog.Builder alertBox = new AlertDialog.Builder(TraqComplaintTaxi.this);
                alertBox.setIcon(R.drawable.info_icon);
                alertBox.setCancelable(false);
                alertBox.setTitle("Do you want to cancel complaint?");
                alertBox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        // finish used for destroyed activity
                        easyTracker.send(MapBuilder
                                .createEvent("Complaint", "Cancel Complaint (Yes)", "Complaint event", null)
                                .build());
                        finish();
                    }
                });

                alertBox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        easyTracker.send(MapBuilder
                                .createEvent("Complaint", "Cancel Complaint (No)", "Complaint event", null)
                                .build());
                        dialog.cancel();
                    }
                });

                alertBox.show();
            } else {
                Intent intent = new Intent(getApplicationContext(), TraqComplaint.class);
                intent.putExtra("Latitude", gLatitude);
                intent.putExtra("Longitude", gLongitude);
                intent.putExtra("SpeedBusExceed", speedTaxiExceed);
                startActivity(intent);
            }
        }
    });

    complainSend.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            String taxi_id = inputTaxi.getText().toString().toUpperCase();
            String taxi_comp = actv_comp_taxi.getText().toString();

            /*if(taxi_comp.length() == 0){
            Toast.makeText(TraqComplaintTaxi.this, "Taxi Company is required!", Toast.LENGTH_SHORT).show();
            }else */
            if (taxi_comp.length() < 2) {
                Toast.makeText(TraqComplaintTaxi.this, "Invalid Taxi Company.", Toast.LENGTH_SHORT).show();
            } else if (taxi_id.length() == 0) {
                Toast.makeText(TraqComplaintTaxi.this, "Taxi Plate Number is required!", Toast.LENGTH_SHORT)
                        .show();
            } else if (taxi_id.length() < 7) {
                Toast.makeText(TraqComplaintTaxi.this, "Invalid Taxi Number.", Toast.LENGTH_SHORT).show();
            } else {
                easyTracker.send(
                        MapBuilder.createEvent("Complaint", "Dialog Prompt", "Complaint event", null).build());
                PromptCustomDialog();
            }
        }
    });
    setCurrentDateOnView();
    getCurrentTime();

    //Shi Chuan's Code

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(TraqComplaintTaxi.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Check if twitter keys are set
    if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) {
        // Internet Connection is not present
        alert.showAlertDialog(TraqComplaintTaxi.this, "Twitter oAuth tokens",
                "Please set your twitter oauth tokens first!", false);
        // stop executing code by return
        return;
    }

    // Shared Preferences
    mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

    /** This if conditions is tested once is
     * redirected from twitter page. Parse the uri to get oAuth
     * Verifier
     * */

    if (!isTwitterLoggedInAlready()) {
        Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
            // oAuth verifier
            String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

            try {
                // Get the access token
                AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

                // Shared Preferences
                SharedPreferences.Editor e = mSharedPreferences.edit();

                // After getting access token, access token secret
                // store them in application preferences
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
                // Store login status - true
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit(); // save changes

                Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

                // Getting user details from twitter
                // For now i am getting his name only
                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);

                String username = user.getName();
                String description = user.getDescription();

                // Displaying in xml ui
                //lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>" + description));
            } catch (Exception e) {
                // Check log for login errors
                Log.e("Twitter Login Error", "> " + e.getMessage());
            }
        }
    }

    //LocationManager lm = (LocationManager)  this.getSystemService(Context.LOCATION_SERVICE);
    //LocationListener ll = new passengerLocationListener();
    //lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);

}

From source file:com.fvd.nimbus.BrowseActivity.java

void messageBox(String msg) {
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle(msg);/* w  w w . ja  v  a2s.  com*/
    dialog.setPositiveButton("OK", null);
    dialog.setCancelable(true);
    dialog.create().show();
}

From source file:com.speedtong.example.ui.chatting.ChattingActivity.java

public void upload(View view) {
    JSONArray all = messageDao.getAll();
    if (all.length() == 0) {
        Toast.makeText(this, "?", Toast.LENGTH_SHORT).show();
        return;/*from  w ww . j a v a 2s. c o m*/
    }

    // ??
    final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
    builder.setTitle("Upload");
    builder.setMessage("");
    builder.setCancelable(false);
    builder.setNegativeButton("", null);

    // 
    final Button btn = (Button) view;
    btn.setText("uploading ...");
    btn.setClickable(false);

    RequestParams params = new RequestParams();
    params.put("act", "upload_hxs");
    params.put("data", all.toString());
    Log.e("jsondata", all.toString());

    new AsyncHttpClient().post("http://cms.orenda.com.cn:29055/upload_data", params,
            new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    super.onSuccess(statusCode, headers, response);
                    String hasErrors = MockUtil.getString(response, "hasErrors");
                    if ("false".equals(hasErrors)) {
                        builder.setMessage("?");
                        messageDao.deleteAll();
                    } else {
                        String msg = MockUtil.getString(response, "message");
                        Log.e("upload.hasError=true", msg);
                        builder.setMessage(msg);
                    }

                    btn.setText("UPLOAD");
                    btn.setClickable(true);
                    builder.show();
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString,
                        Throwable throwable) {
                    super.onFailure(statusCode, headers, responseString, throwable);
                    Log.e("onFailure1", String.valueOf(responseString) + "|" + throwable);
                    builder.show();
                    btn.setText("UPLOAD");
                    btn.setClickable(true);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable,
                        JSONArray errorResponse) {
                    super.onFailure(statusCode, headers, throwable, errorResponse);
                    Log.e("onFailure2", String.valueOf(errorResponse) + "|" + throwable);
                    builder.show();
                    btn.setText("UPLOAD");
                    btn.setClickable(true);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable,
                        JSONObject errorResponse) {
                    super.onFailure(statusCode, headers, throwable, errorResponse);
                    Log.e("onFailure3", String.valueOf(errorResponse) + "|" + throwable);
                    builder.show();
                    btn.setText("UPLOAD");
                    btn.setClickable(true);
                }
            });
}

From source file:activities.PaintActivity.java

private void showPopup() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    AlertDialog avisoDialog = builder.setCancelable(false).setMessage(aviso_paleta)
            .setPositiveButton(aviso_paleta_ok, new DialogInterface.OnClickListener() {
                @Override//from w  w w.j  a  va 2  s.com
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            }).create();

    avisoDialog.show();
}

From source file:com.dragon4.owo.ar_trace.ARCore.MixView.java

public void setErrorDialog() {
    //  ?? ? ?//from ww  w  . ja v  a 2 s .  c om
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    // ??  ? 
    builder.setMessage(getString(DataView.CONNECTION_ERROR_DIALOG_TEXT));
    builder.setCancelable(false);

    // ? ? 
    /*Retry*/
    builder.setPositiveButton(DataView.CONNECTION_ERROR_DIALOG_BUTTON1, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            fError = false;
            //TODO improve
            try {
                repaint(); // ? 
            } catch (Exception ex) { //  ? 
                doError(ex);
            }
        }
    });
    /*Open settings*/
    builder.setNeutralButton(DataView.CONNECTION_ERROR_DIALOG_BUTTON2, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            //   ?? 
            Intent intent1 = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
            startActivityForResult(intent1, 42);
        }
    });
    /*Close application*/
    builder.setNegativeButton(DataView.CONNECTION_ERROR_DIALOG_BUTTON3, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            System.exit(0); // ?  
        }
    });
    AlertDialog alert = builder.create();
    alert.show(); //  ? 
}

From source file:com.ibuildapp.romanblack.WebPlugin.WebPlugin.java

@Override
public void create() {
    try {//from   w w  w . j a va  2s  .com

        setContentView(R.layout.romanblack_html_main);
        root = (FrameLayout) findViewById(R.id.romanblack_root_layout);
        webView = new ObservableWebView(this);
        webView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));
        root.addView(webView);

        webView.setHorizontalScrollBarEnabled(false);
        setTitle("HTML");

        Intent currentIntent = getIntent();
        Bundle store = currentIntent.getExtras();
        widget = (Widget) store.getSerializable("Widget");
        if (widget == null) {
            handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100);
            return;
        }
        appName = widget.getAppName();

        if (widget.getPluginXmlData().length() == 0) {
            if (currentIntent.getStringExtra("WidgetFile").length() == 0) {
                handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100);
                return;
            }
        }

        if (widget.getTitle() != null && widget.getTitle().length() > 0) {
            setTopBarTitle(widget.getTitle());
        } else {
            setTopBarTitle(getResources().getString(R.string.romanblack_html_web));
        }

        currentUrl = (String) getSession();
        if (currentUrl == null) {
            currentUrl = "";
        }

        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.isConnectedOrConnecting()) {
            isOnline = true;
        }

        // topbar initialization
        setTopBarLeftButtonText(getString(R.string.common_home_upper), true, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        if (isOnline) {
            webView.getSettings().setJavaScriptEnabled(true);
        }

        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.getSettings().setGeolocationEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setUseWideViewPort(false);
        webView.getSettings().setSavePassword(false);
        webView.clearHistory();
        webView.invalidate();

        if (Build.VERSION.SDK_INT >= 19) {
        }
        webView.getSettings().setUserAgentString(
                "Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");

        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.invalidate();

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                }
                    break;
                case MotionEvent.ACTION_UP: {
                    if (!v.hasFocus()) {
                        v.requestFocus();
                    }
                }
                    break;

                case MotionEvent.ACTION_MOVE: {
                }
                    break;

                }
                return false;
            }
        });

        webView.setBackgroundColor(Color.WHITE);
        try {
            if (widget.getBackgroundColor() != Color.TRANSPARENT) {
                webView.setBackgroundColor(widget.getBackgroundColor());
            }
        } catch (IllegalArgumentException e) {
        }

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                    String mimetype, long contentLength) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {

            FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);

            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin,
                    final GeolocationPermissions.Callback callback) {
                AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this);
                builder.setTitle(R.string.location_dialog_title);
                builder.setMessage(R.string.location_dialog_description);
                builder.setCancelable(true);

                builder.setPositiveButton(R.string.location_dialog_allow,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                callback.invoke(origin, true, false);
                            }
                        });

                builder.setNegativeButton(R.string.location_dialog_not_allow,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                callback.invoke(origin, false, false);
                            }
                        });

                AlertDialog alert = builder.create();
                alert.show();
            }

            @Override
            public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
                if (customView != null) {
                    customViewCallback.onCustomViewHidden();
                    return;
                }

                view.setBackgroundColor(Color.BLACK);
                view.setLayoutParams(LayoutParameters);
                root.addView(view);
                customView = view;
                customViewCallback = callback;
                webView.setVisibility(View.GONE);
            }

            @Override
            public void onHideCustomView() {
                if (customView == null) {
                    return;
                } else {
                    closeFullScreenVideo();
                }
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {

                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);//Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                isMedia = true;
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            //For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                isMedia = true;
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                    FileChooserParams fileChooserParams) {
                isV21 = true;
                mUploadMessageV21 = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
                return true;
            }

            @Override
            public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                if (state == states.EMPTY) {
                    currentUrl = url;
                    setSession(currentUrl);
                    state = states.LOAD_START;
                    handler.sendEmptyMessage(SHOW_PROGRESS);
                }
            }

            @Override
            public void onLoadResource(WebView view, String url) {

                if (!alreadyLoaded
                        && (url.startsWith("http://www.youtube.com/get_video_info?")
                                || url.startsWith("https://www.youtube.com/get_video_info?"))
                        && Build.VERSION.SDK_INT < 11) {
                    try {
                        String path = url.contains("https://www.youtube.com/get_video_info?")
                                ? url.replace("https://www.youtube.com/get_video_info?", "")
                                : url.replace("http://www.youtube.com/get_video_info?", "");

                        String[] parqamValuePairs = path.split("&");

                        String videoId = null;

                        for (String pair : parqamValuePairs) {
                            if (pair.startsWith("video_id")) {
                                videoId = pair.split("=")[1];
                                break;
                            }
                        }

                        if (videoId != null) {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                    .setData(Uri.parse("http://www.youtube.com/watch?v=" + videoId)));
                            needRefresh = true;
                            alreadyLoaded = !alreadyLoaded;

                            return;
                        }
                    } catch (Exception ex) {
                    }
                } else {
                    super.onLoadResource(view, url);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (hideProgress) {
                    if (TextUtils.isEmpty(WebPlugin.this.url)) {
                        state = states.LOAD_COMPLETE;
                        handler.sendEmptyMessage(HIDE_PROGRESS);
                        super.onPageFinished(view, url);
                    } else {
                        view.loadUrl("javascript:(function(){" + "l=document.getElementById('link');"
                                + "e=document.createEvent('HTMLEvents');" + "e.initEvent('click',true,true);"
                                + "l.dispatchEvent(e);" + "})()");
                        hideProgress = false;
                    }
                } else {
                    state = states.LOAD_COMPLETE;
                    handler.sendEmptyMessage(HIDE_PROGRESS);
                    super.onPageFinished(view, url);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                if (errorCode == WebViewClient.ERROR_BAD_URL) {
                    startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),
                            DOWNLOAD_REQUEST_CODE);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this);
                builder.setMessage(R.string.notification_error_ssl_cert_invalid);
                builder.setPositiveButton(WebPlugin.this.getResources().getString(R.string.wp_continue),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                handler.proceed();
                            }
                        });
                builder.setNegativeButton(WebPlugin.this.getResources().getString(R.string.wp_cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                handler.cancel();
                            }
                        });
                final AlertDialog dialog = builder.create();
                dialog.show();
            }

            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                super.onFormResubmission(view, dontResend, resend);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {

                    if (url.contains("youtube.com/watch")) {
                        if (Build.VERSION.SDK_INT < 11) {
                            try {
                                startActivity(
                                        new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                                .setData(Uri.parse(url)));
                                return true;
                            } catch (Exception ex) {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    } else if (url.contains("paypal.com")) {
                        if (url.contains("&bn=ibuildapp_SP")) {
                            return false;
                        } else {
                            url = url + "&bn=ibuildapp_SP";

                            webView.loadUrl(url);

                            return true;
                        }
                    } else if (url.contains("sms:")) {
                        try {
                            Intent smsIntent = new Intent(Intent.ACTION_VIEW);
                            smsIntent.setData(Uri.parse(url));
                            startActivity(smsIntent);
                            return true;
                        } catch (Exception ex) {
                            Log.e("", ex.getMessage());
                            return false;
                        }
                    } else if (url.contains("tel:")) {
                        Intent callIntent = new Intent(Intent.ACTION_CALL);
                        callIntent.setData(Uri.parse(url));
                        startActivity(callIntent);
                        return true;
                    } else if (url.contains("mailto:")) {
                        MailTo mailTo = MailTo.parse(url);

                        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                        emailIntent.setType("plain/text");
                        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                                new String[] { mailTo.getTo() });

                        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mailTo.getSubject());
                        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, mailTo.getBody());
                        WebPlugin.this.startActivity(Intent.createChooser(emailIntent,
                                getString(R.string.romanblack_html_send_email)));
                        return true;
                    } else if (url.contains("rtsp:")) {
                        Uri address = Uri.parse(url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, address);

                        final PackageManager pm = getPackageManager();
                        final List<ResolveInfo> matches = pm.queryIntentActivities(intent, 0);
                        if (matches.size() > 0) {
                            startActivity(intent);
                        } else {
                            Toast.makeText(WebPlugin.this, getString(R.string.romanblack_html_no_video_player),
                                    Toast.LENGTH_SHORT).show();
                        }

                        return true;
                    } else if (url.startsWith("intent:") || url.startsWith("market:")
                            || url.startsWith("col-g2m-2:")) {
                        Intent it = new Intent();
                        it.setData(Uri.parse(url));
                        startActivity(it);

                        return true;
                    } else if (url.contains("//play.google.com/")) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        return true;
                    } else {
                        if (url.contains("ibuildapp.com-1915109")) {
                            String param = Uri.parse(url).getQueryParameter("widget");
                            finish();
                            if (param != null && param.equals("1001"))
                                com.appbuilder.sdk.android.Statics.launchMain();
                            else if (param != null && !"".equals(param)) {
                                View.OnClickListener widget = Statics.linkWidgets.get(Integer.valueOf(param));
                                if (widget != null)
                                    widget.onClick(view);
                            }
                            return false;
                        }

                        currentUrl = url;
                        setSession(currentUrl);
                        if (!isOnline) {
                            handler.sendEmptyMessage(HIDE_PROGRESS);
                            handler.sendEmptyMessage(STOP_LOADING);
                        } else {
                            String pageType = "application/html";
                            if (!url.contains("vk.com")) {
                                getPageType(url);
                            }
                            if (pageType.contains("application") && !pageType.contains("html")
                                    && !pageType.contains("xml")) {
                                startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),
                                        DOWNLOAD_REQUEST_CODE);
                                return super.shouldOverrideUrlLoading(view, url);
                            } else {
                                view.getSettings().setLoadWithOverviewMode(true);
                                view.getSettings().setUseWideViewPort(true);
                                view.setBackgroundColor(Color.WHITE);
                            }
                        }
                        return false;
                    }

                } catch (Exception ex) { // Error Logging
                    return false;
                }
            }
        });

        handler.sendEmptyMessage(SHOW_PROGRESS);

        new Thread() {
            @Override
            public void run() {

                EntityParser parser;
                if (widget.getPluginXmlData() != null) {
                    if (widget.getPluginXmlData().length() > 0) {
                        parser = new EntityParser(widget.getPluginXmlData());
                    } else {
                        String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile"));
                        parser = new EntityParser(xmlData);
                    }
                } else {
                    String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile"));
                    parser = new EntityParser(xmlData);
                }

                parser.parse();

                url = parser.getUrl();
                html = parser.getHtml();

                if (url.length() > 0 && !isOnline) {
                    handler.sendEmptyMessage(NEED_INTERNET_CONNECTION);
                } else {
                    if (isOnline) {
                    } else {
                        if (html.length() == 0) {
                        }
                    }
                    if (html.length() > 0 || url.length() > 0) {
                        handler.sendEmptyMessageDelayed(SHOW_HTML, 700);
                    } else {
                        handler.sendEmptyMessage(HIDE_PROGRESS);
                        handler.sendEmptyMessage(INITIALIZATION_FAILED);
                    }
                }
            }
        }.start();

    } catch (Exception ex) {
    }
}

From source file:com.trukr.shipper.fragment.RequestStatus.java

private void readOrder() {
    pd = new ProgressDialog(mContext, android.app.AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
    pd.setMessage("Loading...");
    pd.setCancelable(false);//from w  w w. j  a  va2s .c  o  m
    pd.show();
    // Get the value of orderId from intent get
    try {
        Intent iin = getIntent();
        Bundle b = iin.getExtras();
        if (b != null) {
            orderId = (String) b.get("OrderId");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    queue = Volley.newRequestQueue(mContext);
    JSONObject object = null;
    try {
        object = new JSONObject();
        object.put("UserType", IConstant.UserType);
        object.put("UserId", userId);
        object.put("AuthToken", authToken);
        object.put("OrderId", orderId);
        System.out.println("readputparams-------->" + userId + authToken + orderId);
    } catch (JSONException e1) {
        e1.printStackTrace();
    }
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, IConstant.ReadShipment, object,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("Test", response.toString());
                    closeprogress();
                    try {
                        int StatusCode = Integer.parseInt(response.getString("StatusCode"));
                        String Message = response.getString("Message");
                        if (StatusCode == 97) {
                            TrukrApplication.unauthorisedAlertDialog(mContext, IConstant.alert, Message);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (response.getString("Message").equals("Success")) {
                            orderNo = response.getString("OrderId");
                            orderStatus = response.getString("OrderStatus");
                            tv_orderStatus.setText(orderStatus);
                            JSONObject shipment = response.getJSONObject("Shipment");
                            JSONObject source = shipment.getJSONObject("Source");
                            JSONObject destination = shipment.getJSONObject("Destination");
                            fromAdd = source.getString("FromAddress");
                            toAdd = destination.getString("ToAddress");
                            String fromlat = source.getString("FromLatitude");
                            String fromlon = source.getString("FromLongitude");
                            String tolat = destination.getString("ToLatitude");
                            String tolon = destination.getString("ToLongitude");

                            preferences = getSharedPreferences("Details", MODE_PRIVATE);
                            editor = preferences.edit();
                            editor.putString("FromAddress", fromAdd);
                            editor.putString("FromLatitude", fromlat);
                            editor.putString("FromLongitude", fromlon);
                            editor.putString("ToAddress", toAdd);
                            editor.putString("ToLatitude", tolat);
                            editor.putString("ToLongitude", tolon);
                            editor.commit();

                            JSONObject driver = response.getJSONObject("Driver");
                            driversname = driver.getString("DriverName");
                            driverContactValue = driver.getString("DriverContact");
                            driverLicenseValue = driver.getString("DriverLicense");
                            driverUsDotNumberValue = driver.getString("USDotNumber");
                            driverMcNumberValue = driver.getString("MCNumber");
                            driverLicensePlatesValue = driver.getString("LicensePlates");
                            truckSafetyRatingValue = driver.getString("TruckSafetyRating");
                            insuranceValue = driver.getString("Insurance");
                            driverImage = driver.getString("DriverImage");
                            System.out.println("DriverDetai--->" + driversname + driverContactValue
                                    + driverLicenseValue + driverUsDotNumberValue + driverMcNumberValue);
                            tv_drivername.setText(driversname);
                            try {
                                Picasso.with(getApplicationContext()).load(driverImage).into(driverProfile);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            System.out.println(fromAdd.toString() + toAdd.toString());
                            System.out.println(fromlat.toString() + fromlon.toString());
                            System.out.println(tolat.toString() + tolon.toString());
                            latstart = Double.parseDouble(fromlat);
                            latEnd = Double.parseDouble(tolat);
                            longStart = Double.parseDouble(fromlon);
                            longEnd = Double.parseDouble(tolon);
                            System.out.println("Directions----->" + latstart + latEnd + longStart + longEnd);

                            if (map == null) {
                                map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
                                // check if map is created successfully or not
                                if (map == null) {
                                    Toast.makeText(RequestStatus.this, "Sorry! unable to create maps",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                            //   map.addMarker(new MarkerOptions().position(new LatLng(latstart, longStart))/*.title("Marker in Pondy")*/.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_icon)).title(fromAdd));
                            map.animateCamera(
                                    CameraUpdateFactory.newLatLngZoom(new LatLng(latstart, longStart), 7));
                            map.animateCamera(CameraUpdateFactory.zoomTo(7));
                            String url = getDirectionsUrl();
                            // Start downloading json data from Google Directions API
                            DownloadTask downloadTask = new DownloadTask();
                            downloadTask.execute(url);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    closeprogress();
                    Log.d("Response: ", error.toString());
                    String json;
                    if (error.networkResponse != null && error.networkResponse.data != null) {
                        try {
                            json = new String(error.networkResponse.data,
                                    HttpHeaderParser.parseCharset(error.networkResponse.headers));
                            Log.e("Error list-->", json);
                            try {
                                //  Parsing json object response response will be a json object
                                if (json != null) {
                                    JSONObject jsonObject = new JSONObject(json);
                                    String message = jsonObject.getString("message");
                                    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
                                    AlertDialog.Builder dlgAlert = new AlertDialog.Builder(
                                            getApplicationContext());
                                    dlgAlert.setMessage(message);
                                    dlgAlert.setTitle("Login ");
                                    dlgAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            //dismiss the dialog
                                            dialog.dismiss();
                                        }
                                    });
                                    dlgAlert.setCancelable(true);
                                    dlgAlert.create().show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(),
                                        Toast.LENGTH_LONG).show();
                            }
                        } catch (UnsupportedEncodingException e) {
                            Log.e("Error 111", e.getMessage());
                        }
                    }
                }
            });
    // volley time out error
    request.setRetryPolicy(new DefaultRetryPolicy(500000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(request);
}

From source file:ch.uzh.supersede.feedbacklibrary.FeedbackActivity.java

private void onRequestPermissionsResultDenied(final int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults, @NonNull final String permission, int dialogMessage,
        @NonNull String dialogInstructions) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
        // The user denied without checking 'Never ask again'. Show again the rationale
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle(R.string.supersede_feedbacklibrary_permission_request_title);
        alertBuilder.setMessage(dialogMessage);
        alertBuilder.setPositiveButton(R.string.supersede_feedbacklibrary_retry_string,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(FeedbackActivity.this, new String[] { permission },
                                requestCode);
                    }//  w  ww . ja  v  a2s. c om
                });
        alertBuilder.setNegativeButton(R.string.supersede_feedbacklibrary_not_now_text,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertBuilder.setCancelable(false);
        alertBuilder.show();
    } else {
        // The user denied and checked the 'Never ask again' option. Show a short explanation dialog
        DialogUtils.showInformationDialog(this, new String[] { dialogInstructions }, false);
    }
}

From source file:com.xrmaddness.offthegrid.ListActivity.java

void verify_dialog(final contact c) {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle(R.string.action_verify);
    alert.setMessage(getString(R.string.dialog_verify) + ": " + pgp.fingerprint(c.address_get()));
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {

            Log.d("verify_dialog", "verified contact");
            c.keystat_set(c.KEYSTAT_VERIFIED);
            db.contact_update(c);/*  ww  w. j a v  a2 s.  c o  m*/
            view_contacts();
            send_key(c);
        }
    });
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
        }
    });
    alert.setCancelable(true);
    alert.show();
}

From source file:com.github.akinaru.hcidebugger.activity.HciDebuggerActivity.java

/**
 * show a dialog when problem occur/*from  ww  w. ja  v  a2  s . c  om*/
 *
 * @param message
 */
private void showWarningDialog(final String message) {

    runOnUiThread(new Runnable() {
        @Override
        public void run() {

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                    case DialogInterface.BUTTON_POSITIVE:
                        SnoopFileDialog dialogBrowse = new SnoopFileDialog(HciDebuggerActivity.this);
                        setCurrentDialog(dialogBrowse);
                        dialogBrowse.show();
                        break;

                    case DialogInterface.BUTTON_NEGATIVE:
                        pool.execute(decodingTask);
                        break;
                    }
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(HciDebuggerActivity.this);

            builder.setCancelable(false);
            builder.setMessage(message)
                    .setPositiveButton(getResources().getString(R.string.browse_button), dialogClickListener)
                    .setNegativeButton(getResources().getString(R.string.warning_dialog_retry),
                            dialogClickListener)
                    .show();
        }
    });
}