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.aujur.ebookreader.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 w ww  .j a  v a  2 s .  c  om
    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;
                    searchResultWraper.setSearchResult(searchResults);

                    // showSearchResultDialog(result);
                    Intent intent = new Intent(getActivity(), ReadingOptionsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("SELECTED_TAB", 4);
                    intent.putExtras(bundle);
                    startActivity(intent);

                } 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.jwetherell.quick_response_code.EncoderActivity.java

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    com.ranorex.android.RanorexAndroidAutomation.Hook(this);
    // Get text views
    textoSsid = (TextView) findViewById(R.id.ssid);
    textoPassword = (TextView) findViewById(R.id.password);
    descripcion = (TextView) findViewById(R.id.descripcion);
    icon = (ImageView) findViewById(R.id.icon);
    //textoCifrado = (TextView) findViewById(R.id.cifrado);

    settings = getSharedPreferences(MainActivity.PREFS, 0);

    // if(settings.contains("connected_wifi_5ghz") && settings.getBoolean("connected_wifi_5ghz", false))
    //      descripcion.setText("");

    final ProgressDialog dialog = new ProgressDialog(EncoderActivity.this);

    dialog.setMessage("Generando Qr...");
    dialog.show();//  w ww .  j a va2s.  c o m
    dialog.setCancelable(false);

    try {

        if (settings.contains("ssid") && settings.contains("password1")) {
            // Get ssid, psk and encrypted of settings.

            if (!getIntent().getBooleanExtra("is_5ghz", false)) // Network 2.4 GHz.
            {
                cifradoSettings = settings.getString("cifrado", "WPA");
                ssidSettings = settings.getString("ssid", "");
                pskSettings = settings.getString("password1", "");
                if (settings.contains("connected_wifi_5ghz")
                        && !settings.getBoolean("connected_wifi_5ghz", false)
                        || !settings.contains("connected_wifi_5ghz")) {
                    descripcion.setVisibility(View.VISIBLE);
                }
            } else // Network 5 GHz.
            {
                cifradoSettings = settings.getString("cifrado5ghz", "WPA");
                ssidSettings = settings.getString("ssid5ghz", "");
                pskSettings = settings.getString("password5ghz", "");
                icon.setImageResource(R.drawable.wifiplus120);
                ((TextView) findViewById(R.id.textView1)).setText("WifiPlus");
                if (settings.contains("connected_wifi_5ghz")
                        && settings.getBoolean("connected_wifi_5ghz", false)) {
                    descripcion.setVisibility(View.VISIBLE);
                }
            }

            ssidFull = ssidSettings;
            pskFull = pskSettings;

            if (cifradoSettings.contains("WPA")) {
                cifradoQR = "WPA";
                string = "WIFI:T:" + cifradoQR + ";S:" + ssidSettings + ";P:" + pskSettings + ";;";
            } else if (cifradoSettings.contains("abierta")) {
                cifradoQR = "nopass";
                string = "WIFI:T:" + cifradoQR + ";S:" + ssidSettings + ";;";
            } else if (cifradoSettings.contains("WEP")) {
                cifradoQR = "WEP";
                string = "WIFI:T:" + cifradoQR + ";S:" + ssidSettings + ";P:" + pskSettings + ";;";
            }

            // Update texts
            textoSsid.setText(ssidSettings);

            try {
                if (pskSettings.length() > 39)
                    pskSettings = ellipsis(pskSettings, 39);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (pskSettings.equalsIgnoreCase("sin password") || pskSettings.equalsIgnoreCase(""))
                pskSettings = "Sin password";

            textoPassword.setText(pskSettings);

        }

    } catch (IllegalArgumentException e) {
        Log.e(TAG, "Could not encode barcode", e);
    }

    new AsyncTask<String, Integer, Bitmap>() {

        @Override
        protected Bitmap doInBackground(String... params) {
            QRCodeEncoder qrCodeEncoder = null;
            // This assumes the view is full screen, which is a good assumption
            WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
            Display display = manager.getDefaultDisplay();
            int width = display.getWidth();
            int height = display.getHeight();
            int smallerDimension = width < height ? width : height;
            smallerDimension = smallerDimension * 7 / 8;

            try {
                qrCodeEncoder = new QRCodeEncoder(string, null, Contents.Type.TEXT,
                        BarcodeFormat.QR_CODE.toString(), smallerDimension);
                Hashtable hints = new Hashtable();
                hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                QRCodeWriter qrcw = new QRCodeWriter();
                BitMatrix matrix = qrcw.encode(string, BarcodeFormat.QR_CODE, width, height, hints);
                bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                for (int y = 0; y < matrix.getHeight(); y++) {
                    for (int x = 0; x < matrix.getWidth(); x++) {
                        if (!matrix.get(x, y))
                            bm.setPixel(x, y, Color.WHITE);
                        else
                            bm.setPixel(x, y, Color.BLACK);
                    }
                }
            } catch (WriterException we) {
                we.printStackTrace();
                Log.e(TAG, "Could not encode barcode", we);
            }

            return bm;
        }

        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                viewCode = (ImageView) findViewById(R.id.image_view);
                viewCode.setImageBitmap(bitmap);//bitmap);
                dialog.dismiss();
            } else {
                Toast.makeText(EncoderActivity.this, "Problema al generar Qr", Toast.LENGTH_LONG).show();
            }
        }
    }.execute();

    if (bm != null) {
        dialog.dismiss();
    }

}

From source file:com.android.mms.ui.ComposeMessageActivity.java

private void processPickResult(final Intent data) {
    // The EXTRA_PHONE_URIS stores the phone's urls that were selected by user in the
    // multiple phone picker.
    final Parcelable[] uris = data.getParcelableArrayExtra(Intents.EXTRA_PHONE_URIS);

    final int recipientCount = uris != null ? uris.length : 0;

    final int recipientLimit = MmsConfig.getRecipientLimit();
    if (recipientLimit != Integer.MAX_VALUE && recipientCount > recipientLimit) {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.too_many_recipients, recipientCount, recipientLimit))
                .setPositiveButton(android.R.string.ok, null).create().show();
        return;/*from  w w w .j  a  va 2s  .c o m*/
    }

    final Handler handler = new Handler();
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setTitle(getText(R.string.pick_too_many_recipients));
    progressDialog.setMessage(getText(R.string.adding_recipients));
    progressDialog.setIndeterminate(true);
    progressDialog.setCancelable(false);

    final Runnable showProgress = new Runnable() {
        @Override
        public void run() {
            progressDialog.show();
        }
    };
    // Only show the progress dialog if we can not finish off parsing the return data in 1s,
    // otherwise the dialog could flicker.
    handler.postDelayed(showProgress, 1000);

    new Thread(new Runnable() {
        @Override
        public void run() {
            final ContactList list;
            try {
                list = ContactList.blockingGetByUris(uris);
            } finally {
                handler.removeCallbacks(showProgress);
                progressDialog.dismiss();
            }
            // TODO: there is already code to update the contact header widget and recipients
            // editor if the contacts change. we can re-use that code.
            final Runnable populateWorker = new Runnable() {
                @Override
                public void run() {
                    mRecipientsEditor.populate(list);
                    updateTitle(list);
                }
            };
            handler.post(populateWorker);
        }
    }, "ComoseMessageActivity.processPickResult").start();
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

private void runReport(final DeletePostModel reportPostModel) {
    final EditText inputField = new EditText(activity);
    inputField.setSingleLine();//from   ww w . ja  v a  2s .  c  o m
    if (presentationModel.source.boardModel.allowReport != BoardModel.REPORT_WITH_COMMENT) {
        inputField.setEnabled(false);
        inputField.setKeyListener(null);
    } else {
        inputField.setText(reportPostModel.reportReason == null ? "" : reportPostModel.reportReason);
    }

    DialogInterface.OnClickListener dlgOnClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            if (currentTask != null)
                currentTask.cancel();
            if (pullableLayout.isRefreshing())
                setPullableNoRefreshing();
            reportPostModel.reportReason = inputField.getText().toString();
            final ProgressDialog progressDlg = new ProgressDialog(activity);
            final CancellableTask reportTask = new CancellableTask.BaseCancellableTask();
            progressDlg.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    reportTask.cancel();
                }
            });
            progressDlg.setCanceledOnTouchOutside(false);
            progressDlg.setMessage(resources.getString(R.string.dialog_report_progress));
            progressDlg.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    String error = null;
                    String targetUrl = null;
                    if (reportTask.isCancelled())
                        return;
                    try {
                        targetUrl = chan.reportPost(reportPostModel, null, reportTask);
                    } catch (Exception e) {
                        if (e instanceof InteractiveException) {
                            if (reportTask.isCancelled())
                                return;
                            ((InteractiveException) e).handle(activity, reportTask,
                                    new InteractiveException.Callback() {
                                        @Override
                                        public void onSuccess() {
                                            if (!reportTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                onClick(dialog, which);
                                            }
                                        }

                                        @Override
                                        public void onError(String message) {
                                            if (!reportTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
                                                runReport(reportPostModel);
                                            }
                                        }
                                    });
                            return;
                        }

                        Logger.e(TAG, "cannot report post", e);
                        error = e.getMessage() == null ? "" : e.getMessage();
                    }
                    if (reportTask.isCancelled())
                        return;
                    final boolean success = error == null;
                    final String result = success ? targetUrl : error;
                    Async.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (reportTask.isCancelled())
                                return;
                            progressDlg.dismiss();
                            if (success) {
                                if (result == null) {
                                    update();
                                } else {
                                    UrlHandler.open(result, activity);
                                }
                            } else {
                                Toast.makeText(activity,
                                        TextUtils.isEmpty(result) ? resources.getString(R.string.error_unknown)
                                                : result,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            });
        }
    };
    new AlertDialog.Builder(activity).setTitle(R.string.dialog_report_reason).setView(inputField)
            .setPositiveButton(R.string.dialog_report_button, dlgOnClick)
            .setNegativeButton(android.R.string.cancel, null).create().show();
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

@SuppressLint("InflateParams")
private void runDelete(final DeletePostModel deletePostModel, final boolean hasFiles) {
    Context dialogContext = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
            ? new ContextThemeWrapper(activity, R.style.Theme_Neutron)
            : activity;/*ww w.  ja v  a 2 s.c o  m*/
    View dlgLayout = LayoutInflater.from(dialogContext).inflate(R.layout.dialog_delete, null);
    final EditText inputField = (EditText) dlgLayout.findViewById(R.id.dialog_delete_password_field);
    final CheckBox onlyFiles = (CheckBox) dlgLayout.findViewById(R.id.dialog_delete_only_files);
    inputField.setText(chan.getDefaultPassword());

    if (!presentationModel.source.boardModel.allowDeletePosts
            && !presentationModel.source.boardModel.allowDeleteFiles) {
        Logger.e(TAG, "board model doesn't support deleting");
        return;
    } else if (!presentationModel.source.boardModel.allowDeletePosts) {
        onlyFiles.setEnabled(false);
        onlyFiles.setChecked(true);
    } else if (presentationModel.source.boardModel.allowDeleteFiles && hasFiles) {
        onlyFiles.setEnabled(true);
    } else {
        onlyFiles.setEnabled(false);
    }

    DialogInterface.OnClickListener dlgOnClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            if (currentTask != null)
                currentTask.cancel();
            if (pullableLayout.isRefreshing())
                setPullableNoRefreshing();
            deletePostModel.onlyFiles = onlyFiles.isChecked();
            deletePostModel.password = inputField.getText().toString();
            final ProgressDialog progressDlg = new ProgressDialog(activity);
            final CancellableTask deleteTask = new CancellableTask.BaseCancellableTask();
            progressDlg.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    deleteTask.cancel();
                }
            });
            progressDlg.setCanceledOnTouchOutside(false);
            progressDlg.setMessage(resources.getString(R.string.dialog_delete_progress));
            progressDlg.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    String error = null;
                    String targetUrl = null;
                    if (deleteTask.isCancelled())
                        return;
                    try {
                        targetUrl = chan.deletePost(deletePostModel, null, deleteTask);
                    } catch (Exception e) {
                        if (e instanceof InteractiveException) {
                            if (deleteTask.isCancelled())
                                return;
                            ((InteractiveException) e).handle(activity, deleteTask,
                                    new InteractiveException.Callback() {
                                        @Override
                                        public void onSuccess() {
                                            if (!deleteTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                onClick(dialog, which);
                                            }
                                        }

                                        @Override
                                        public void onError(String message) {
                                            if (!deleteTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
                                                runDelete(deletePostModel, hasFiles);
                                            }
                                        }
                                    });
                            return;
                        }

                        Logger.e(TAG, "cannot delete post", e);
                        error = e.getMessage() == null ? "" : e.getMessage();
                    }
                    if (deleteTask.isCancelled())
                        return;
                    final boolean success = error == null;
                    final String result = success ? targetUrl : error;
                    Async.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (deleteTask.isCancelled())
                                return;
                            progressDlg.dismiss();
                            if (success) {
                                if (result == null) {
                                    update();
                                } else {
                                    UrlHandler.open(result, activity);
                                }
                            } else {
                                Toast.makeText(activity,
                                        TextUtils.isEmpty(result) ? resources.getString(R.string.error_unknown)
                                                : result,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            });
        }
    };
    new AlertDialog.Builder(activity).setTitle(R.string.dialog_delete_password).setView(dlgLayout)
            .setPositiveButton(R.string.dialog_delete_button, dlgOnClick)
            .setNegativeButton(android.R.string.cancel, null).create().show();
}

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

public void setLineData3(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  .j  a  va 2s .co m
    ringProgressDialog.setCancelable(true);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {

                int yMaxAxisValue = 0;
                try {

                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            rlRootGraphLayout.removeView(mChartView);
                        }
                    });

                } catch (Exception edsx) {
                    edsx.printStackTrace();
                }
                date.setDate(1);
                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 First day of the month as first month

                int[] x = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                        23, 24, 25, 26, 27, 28, 29, 30, 31 };

                // Creating an XYSeries for Consumed water
                XYSeries callories = new XYSeries("Callories");

                List<Ingridient> list;
                Date dt = date; // **
                // Adding data to Income and Expense Series
                for (int i = 1; i <= daysInMonth; i++) {
                    // get all water records consumed per this month
                    list = DataBaseUtils.getAllFoodConsumedInMonth(
                            Utils.formatDate(dt, DataBaseUtils.DATE_PATTERN_YYYY_MM_DD));
                    // init "average" data
                    int totalCallories = 0;
                    for (Ingridient ingridient : list) {
                        totalCallories += ingridient.kkal;
                    }
                    callories.add(i, totalCallories);
                    dt = DateUtils.addDays(dt, 1);
                    yMaxAxisValue = Math.max(yMaxAxisValue, totalCallories);
                }

                // Creating a dataset to hold each series
                final XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
                // Adding Income Series to the dataset
                dataset.addSeries(callories);

                // Creating XYSeriesRenderer to customize protein series
                XYSeriesRenderer calloriesRenderer = new XYSeriesRenderer();
                calloriesRenderer.setColor(Color.rgb(220, 255, 110));
                calloriesRenderer.setFillPoints(true);
                calloriesRenderer.setLineWidth(3);
                calloriesRenderer.setDisplayChartValues(true);

                // Creating a XYMultipleSeriesRenderer to customize the whole chart
                final XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
                // multiRenderer.setXLabels(0);

                for (int i = 0; i < x.length; i++) {
                    multiRenderer.addXTextLabel(i, String.valueOf(x[i]));
                }

                // Adding incomeRenderer and expenseRenderer to multipleRenderer
                // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
                // should be same
                multiRenderer.setChartTitle(String.format("Callories statistic"));
                multiRenderer.setXTitle(Utils.getSpecificDateValue(DATE, "MMM") + " of "
                        + Utils.formatDate(DATE, DataBaseUtils.DATE_PATTERN_YYYY));
                multiRenderer.setYTitle(getActivity().getResources().getString(R.string.callories_consumption));
                multiRenderer.setAxesColor(Color.WHITE);
                multiRenderer.setShowLegend(true);
                multiRenderer.addSeriesRenderer(calloriesRenderer);
                multiRenderer.setShowGrid(true);
                multiRenderer.setClickEnabled(true);
                multiRenderer.setXLabelsAngle(20);
                multiRenderer.setYAxisMax(yMaxAxisValue + 200);
                multiRenderer.setXLabelsColor(Color.WHITE);
                multiRenderer.setZoomButtonsVisible(false);
                // configure visible area
                multiRenderer.setXAxisMax(31);
                multiRenderer.setXAxisMin(1);
                multiRenderer.setAxisTitleTextSize(15);
                multiRenderer.setZoomEnabled(true);

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        mChartView = ChartFactory.getLineChartView(getActivity(), dataset, multiRenderer);
                        rlRootGraphLayout.addView(mChartView, 0);
                        if (isLeftIn) {
                            rightIn.setDuration(1000);
                            mChartView.startAnimation(rightIn);
                        } else {
                            leftIn.setDuration(1000);
                            mChartView.startAnimation(leftIn);
                        }
                    }
                });

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

}

From source file:fm.smart.r1.ItemActivity.java

public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // this should be called once image has been chosen by user
    // using requestCode to pass item id - haven't worked out any other way
    // to do it/*  w w w. ja v a2s .com*/
    // if (requestCode == SELECT_IMAGE)
    if (resultCode == Activity.RESULT_OK) {
        // TODO check if user is logged in
        if (LoginActivity.isNotLoggedIn(this)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setClassName(this, LoginActivity.class.getName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            // avoid navigation back to this?
            LoginActivity.return_to = ItemActivity.class.getName();
            LoginActivity.params = new HashMap<String, String>();
            LoginActivity.params.put("item_id", (String) item.getId());
            startActivity(intent);
            // TODO in this case forcing the user to rechoose the image
            // seems a little
            // rude - should probably auto-submit here ...
        } else {
            // Bundle extras = data.getExtras();
            // String sentence_id = (String) extras.get("sentence_id");
            final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
            myOtherProgressDialog.setTitle("Please Wait ...");
            myOtherProgressDialog.setMessage("Uploading image ...");
            myOtherProgressDialog.setIndeterminate(true);
            myOtherProgressDialog.setCancelable(true);

            final Thread add_image = new Thread() {
                public void run() {
                    // TODO needs to check for interruptibility

                    String sentence_id = Integer.toString(requestCode);
                    Uri selectedImage = data.getData();
                    // Bitmap bitmap = Media.getBitmap(getContentResolver(),
                    // selectedImage);
                    // ByteArrayOutputStream bytes = new
                    // ByteArrayOutputStream();
                    // bitmap.compress(Bitmap.CompressFormat.JPEG, 40,
                    // bytes);
                    // ByteArrayInputStream fileInputStream = new
                    // ByteArrayInputStream(
                    // bytes.toByteArray());

                    // TODO Might have to save to file system first to get
                    // this
                    // to work,
                    // argh!
                    // could think of it as saving to cache ...

                    // add image to sentence
                    FileInputStream is = null;
                    FileOutputStream os = null;
                    File file = null;
                    ContentResolver resolver = getContentResolver();
                    try {
                        Bitmap bitmap = Media.getBitmap(getContentResolver(), selectedImage);
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
                        // ByteArrayInputStream bais = new
                        // ByteArrayInputStream(bytes.toByteArray());

                        // FileDescriptor fd =
                        // resolver.openFileDescriptor(selectedImage,
                        // "r").getFileDescriptor();
                        // is = new FileInputStream(fd);

                        String filename = "test.jpg";
                        File dir = ItemActivity.this.getDir("images", MODE_WORLD_READABLE);
                        file = new File(dir, filename);
                        os = new FileOutputStream(file);

                        // while (bais.available() > 0) {
                        // / os.write(bais.read());
                        // }
                        os.write(bytes.toByteArray());

                        os.close();

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        if (os != null) {
                            try {
                                os.close();
                            } catch (IOException e) {
                            }
                        }
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                            }
                        }
                    }

                    // File file = new
                    // File(Uri.decode(selectedImage.toString()));

                    // ensure item is in users default list

                    ItemActivity.add_item_result = new AddItemResult(Main.lookup.addItemToGoal(Main.transport,
                            Main.default_study_goal_id, item.getId(), null));

                    Result result = ItemActivity.add_item_result;

                    if (ItemActivity.add_item_result.success()
                            || ItemActivity.add_item_result.alreadyInList()) {

                        // ensure sentence is in users default goal

                        ItemActivity.add_sentence_goal_result = new AddSentenceResult(
                                Main.lookup.addSentenceToGoal(Main.transport, Main.default_study_goal_id,
                                        item.getId(), sentence_id, null));

                        result = ItemActivity.add_sentence_goal_result;
                        if (ItemActivity.add_sentence_goal_result.success()) {

                            String media_entity = "http://test.com/test.jpg";
                            String author = "tansaku";
                            String author_url = "http://smart.fm/users/tansaku";
                            Log.d("DEBUG-IMAGE-URI", selectedImage.toString());
                            ItemActivity.add_image_result = addImage(file, media_entity, author, author_url,
                                    "1", sentence_id, (String) item.getId(), Main.default_study_goal_id);
                            result = ItemActivity.add_image_result;
                        }
                    }
                    final Result display = result;
                    myOtherProgressDialog.dismiss();
                    ItemActivity.this.runOnUiThread(new Thread() {
                        public void run() {
                            final AlertDialog dialog = new AlertDialog.Builder(ItemActivity.this).create();
                            dialog.setTitle(display.getTitle());
                            dialog.setMessage(display.getMessage());
                            dialog.setButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    if (ItemActivity.add_image_result != null
                                            && ItemActivity.add_image_result.success()) {
                                        ItemListActivity.loadItem(ItemActivity.this, item.getId().toString());
                                    }
                                }
                            });

                            dialog.show();
                        }
                    });

                }

            };

            myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    add_image.interrupt();
                }
            });
            OnCancelListener ocl = new OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    add_image.interrupt();
                }
            };
            myOtherProgressDialog.setOnCancelListener(ocl);
            closeMenu();
            myOtherProgressDialog.show();
            add_image.start();

        }
    }
}

From source file:org.telegram.ui.CacheControlActivity.java

private void cleanupFolders() {
    final ProgressDialog progressDialog = new ProgressDialog(getParentActivity());
    progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.setCancelable(false);
    progressDialog.show();/*from  w  w  w  .j a  v a 2s  . co m*/
    Utilities.globalQueue.postRunnable(new Runnable() {
        @Override
        public void run() {
            boolean imagesCleared = false;
            for (int a = 0; a < 6; a++) {
                if (!clear[a]) {
                    continue;
                }
                int type = -1;
                int documentsMusicType = 0;
                if (a == 0) {
                    type = FileLoader.MEDIA_DIR_IMAGE;
                } else if (a == 1) {
                    type = FileLoader.MEDIA_DIR_VIDEO;
                } else if (a == 2) {
                    type = FileLoader.MEDIA_DIR_DOCUMENT;
                    documentsMusicType = 1;
                } else if (a == 3) {
                    type = FileLoader.MEDIA_DIR_DOCUMENT;
                    documentsMusicType = 2;
                } else if (a == 4) {
                    type = FileLoader.MEDIA_DIR_AUDIO;
                } else if (a == 5) {
                    type = FileLoader.MEDIA_DIR_CACHE;
                }
                if (type == -1) {
                    continue;
                }
                File file = FileLoader.getInstance().checkDirectory(type);
                if (file != null) {
                    try {
                        File[] array = file.listFiles();
                        if (array != null) {
                            for (int b = 0; b < array.length; b++) {
                                String name = array[b].getName().toLowerCase();
                                if (documentsMusicType == 1 || documentsMusicType == 2) {
                                    if (name.endsWith(".mp3") || name.endsWith(".m4a")) {
                                        if (documentsMusicType == 1) {
                                            continue;
                                        }
                                    } else if (documentsMusicType == 2) {
                                        continue;
                                    }
                                }
                                if (name.equals(".nomedia")) {
                                    continue;
                                }
                                if (array[b].isFile()) {
                                    array[b].delete();
                                }
                            }
                        }
                    } catch (Throwable e) {
                        FileLog.e("tmessages", e);
                    }
                }
                if (type == FileLoader.MEDIA_DIR_CACHE) {
                    cacheSize = getDirectorySize(
                            FileLoader.getInstance().checkDirectory(FileLoader.MEDIA_DIR_CACHE),
                            documentsMusicType);
                    imagesCleared = true;
                } else if (type == FileLoader.MEDIA_DIR_AUDIO) {
                    audioSize = getDirectorySize(
                            FileLoader.getInstance().checkDirectory(FileLoader.MEDIA_DIR_AUDIO),
                            documentsMusicType);
                } else if (type == FileLoader.MEDIA_DIR_DOCUMENT) {
                    if (documentsMusicType == 1) {
                        documentsSize = getDirectorySize(
                                FileLoader.getInstance().checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT),
                                documentsMusicType);
                    } else {
                        musicSize = getDirectorySize(
                                FileLoader.getInstance().checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT),
                                documentsMusicType);
                    }
                } else if (type == FileLoader.MEDIA_DIR_IMAGE) {
                    imagesCleared = true;
                    photoSize = getDirectorySize(
                            FileLoader.getInstance().checkDirectory(FileLoader.MEDIA_DIR_IMAGE),
                            documentsMusicType);
                } else if (type == FileLoader.MEDIA_DIR_VIDEO) {
                    videoSize = getDirectorySize(
                            FileLoader.getInstance().checkDirectory(FileLoader.MEDIA_DIR_VIDEO),
                            documentsMusicType);
                }
            }
            final boolean imagesClearedFinal = imagesCleared;
            totalSize = cacheSize + videoSize + audioSize + photoSize + documentsSize + musicSize;
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    if (imagesClearedFinal) {
                        ImageLoader.getInstance().clearMemory();
                    }
                    if (listAdapter != null) {
                        listAdapter.notifyDataSetChanged();
                    }
                    try {
                        progressDialog.dismiss();
                    } catch (Exception e) {
                        FileLog.e("tmessages", e);
                    }
                }
            });
        }
    });
}

From source file:fm.smart.r1.activity.ItemActivity.java

@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // this should be called once image has been chosen by user
    // using requestCode to pass item id - haven't worked out any other way
    // to do it/* ww w  . ja va2 s. com*/
    // if (requestCode == SELECT_IMAGE)
    if (resultCode == Activity.RESULT_OK) {
        // TODO check if user is logged in
        if (Main.isNotLoggedIn(this)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setClassName(this, LoginActivity.class.getName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            // avoid navigation back to this?
            LoginActivity.return_to = ItemActivity.class.getName();
            LoginActivity.params = new HashMap<String, String>();
            LoginActivity.params.put("item_id", (String) item.item_node.atts.get("id"));
            startActivity(intent);
            // TODO in this case forcing the user to rechoose the image
            // seems a little
            // rude - should probably auto-submit here ...
        } else {
            // Bundle extras = data.getExtras();
            // String sentence_id = (String) extras.get("sentence_id");
            final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
            myOtherProgressDialog.setTitle("Please Wait ...");
            myOtherProgressDialog.setMessage("Uploading image ...");
            myOtherProgressDialog.setIndeterminate(true);
            myOtherProgressDialog.setCancelable(true);

            final Thread add_image = new Thread() {
                public void run() {
                    // TODO needs to check for interruptibility

                    String sentence_id = Integer.toString(requestCode);
                    Uri selectedImage = data.getData();
                    // Bitmap bitmap = Media.getBitmap(getContentResolver(),
                    // selectedImage);
                    // ByteArrayOutputStream bytes = new
                    // ByteArrayOutputStream();
                    // bitmap.compress(Bitmap.CompressFormat.JPEG, 40,
                    // bytes);
                    // ByteArrayInputStream fileInputStream = new
                    // ByteArrayInputStream(
                    // bytes.toByteArray());

                    // TODO Might have to save to file system first to get
                    // this
                    // to work,
                    // argh!
                    // could think of it as saving to cache ...

                    // add image to sentence
                    FileInputStream is = null;
                    FileOutputStream os = null;
                    File file = null;
                    ContentResolver resolver = getContentResolver();
                    try {
                        Bitmap bitmap = Media.getBitmap(getContentResolver(), selectedImage);
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
                        // ByteArrayInputStream bais = new
                        // ByteArrayInputStream(bytes.toByteArray());

                        // FileDescriptor fd =
                        // resolver.openFileDescriptor(selectedImage,
                        // "r").getFileDescriptor();
                        // is = new FileInputStream(fd);

                        String filename = "test.jpg";
                        File dir = ItemActivity.this.getDir("images", MODE_WORLD_READABLE);
                        file = new File(dir, filename);
                        os = new FileOutputStream(file);

                        // while (bais.available() > 0) {
                        // / os.write(bais.read());
                        // }
                        os.write(bytes.toByteArray());

                        os.close();

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        if (os != null) {
                            try {
                                os.close();
                            } catch (IOException e) {
                            }
                        }
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                            }
                        }
                    }

                    // File file = new
                    // File(Uri.decode(selectedImage.toString()));

                    // ensure item is in users default list

                    ItemActivity.add_item_result = addItemToList(Main.default_study_list_id,
                            (String) item.item_node.atts.get("id"), ItemActivity.this);
                    Result result = ItemActivity.add_item_result;

                    if (ItemActivity.add_item_result.success()
                            || ItemActivity.add_item_result.alreadyInList()) {

                        // ensure sentence is in users default list

                        ItemActivity.add_sentence_list_result = addSentenceToList(sentence_id,
                                (String) item.item_node.atts.get("id"), Main.default_study_list_id,
                                ItemActivity.this);
                        result = ItemActivity.add_sentence_list_result;
                        if (ItemActivity.add_sentence_list_result.success()) {

                            String media_entity = "http://test.com/test.jpg";
                            String author = "tansaku";
                            String author_url = "http://smart.fm/users/tansaku";
                            Log.d("DEBUG-IMAGE-URI", selectedImage.toString());
                            ItemActivity.add_image_result = addImage(file, media_entity, author, author_url,
                                    "1", sentence_id, (String) item.item_node.atts.get("id"),
                                    Main.default_study_list_id);
                            result = ItemActivity.add_image_result;
                        }
                    }
                    final Result display = result;
                    myOtherProgressDialog.dismiss();
                    ItemActivity.this.runOnUiThread(new Thread() {
                        public void run() {
                            final AlertDialog dialog = new AlertDialog.Builder(ItemActivity.this).create();
                            dialog.setTitle(display.getTitle());
                            dialog.setMessage(display.getMessage());
                            dialog.setButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    if (ItemActivity.add_image_result != null
                                            && ItemActivity.add_image_result.success()) {
                                        ItemListActivity.loadItem(ItemActivity.this,
                                                item.item_node.atts.get("id").toString());
                                    }
                                }
                            });

                            dialog.show();
                        }
                    });

                }

            };

            myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    add_image.interrupt();
                }
            });
            OnCancelListener ocl = new OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    add_image.interrupt();
                }
            };
            myOtherProgressDialog.setOnCancelListener(ocl);
            closeMenu();
            myOtherProgressDialog.show();
            add_image.start();

        }
    }
}

From source file:org.telegram.messenger.MessagesController.java

public void startSecretChat(final Context context, final TLRPC.User user) {
    if (user == null) {
        return;/* www  . j a  v  a2s  .  c o m*/
    }
    final ProgressDialog progressDialog = new ProgressDialog(context);
    progressDialog.setMessage(context.getString(R.string.Loading));
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.setCancelable(false);
    progressDialog.show();
    TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig();
    req.random_length = 256;
    req.version = MessagesStorage.lastSecretVersion;
    ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() {
        @Override
        public void run(TLObject response, TLRPC.TL_error error) {
            if (error == null) {
                TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response;
                if (response instanceof TLRPC.TL_messages_dhConfig) {
                    if (!Utilities.isGoodPrime(res.p, res.g)) {
                        Utilities.RunOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        progressDialog.dismiss();
                                    }
                                } catch (Exception e) {
                                    FileLog.e("tmessages", e);
                                }
                            }
                        });
                        return;
                    }
                    MessagesStorage.secretPBytes = res.p;
                    MessagesStorage.secretG = res.g;
                    MessagesStorage.lastSecretVersion = res.version;
                    MessagesStorage.Instance.saveSecretParams(MessagesStorage.lastSecretVersion,
                            MessagesStorage.secretG, MessagesStorage.secretPBytes);
                }
                final byte[] salt = new byte[256];
                for (int a = 0; a < 256; a++) {
                    salt[a] = (byte) ((byte) (random.nextDouble() * 256) ^ res.random[a]);
                }

                BigInteger i_g_a = BigInteger.valueOf(MessagesStorage.secretG);
                i_g_a = i_g_a.modPow(new BigInteger(1, salt), new BigInteger(1, MessagesStorage.secretPBytes));
                byte[] g_a = i_g_a.toByteArray();
                if (g_a.length > 256) {
                    byte[] correctedAuth = new byte[256];
                    System.arraycopy(g_a, 1, correctedAuth, 0, 256);
                    g_a = correctedAuth;
                }

                TLRPC.TL_messages_requestEncryption req2 = new TLRPC.TL_messages_requestEncryption();
                req2.g_a = g_a;
                req2.user_id = getInputUser(user);
                req2.random_id = (int) (random.nextDouble() * Integer.MAX_VALUE);
                ConnectionsManager.Instance.performRpc(req2, new RPCRequest.RPCRequestDelegate() {
                    @Override
                    public void run(final TLObject response, TLRPC.TL_error error) {
                        if (error == null) {
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        try {
                                            progressDialog.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                    }
                                    TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) response;
                                    chat.user_id = chat.participant_id;
                                    encryptedChats.put(chat.id, chat);
                                    chat.a_or_b = salt;
                                    TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
                                    dialog.id = ((long) chat.id) << 32;
                                    dialog.unread_count = 0;
                                    dialog.top_message = 0;
                                    dialog.last_message_date = ConnectionsManager.Instance.getCurrentTime();
                                    dialogs_dict.put(dialog.id, dialog);
                                    dialogs.add(dialog);
                                    dialogsServerOnly.clear();
                                    Collections.sort(dialogs, new Comparator<TLRPC.TL_dialog>() {
                                        @Override
                                        public int compare(TLRPC.TL_dialog tl_dialog,
                                                TLRPC.TL_dialog tl_dialog2) {
                                            if (tl_dialog.last_message_date == tl_dialog2.last_message_date) {
                                                return 0;
                                            } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) {
                                                return 1;
                                            } else {
                                                return -1;
                                            }
                                        }
                                    });
                                    for (TLRPC.TL_dialog d : dialogs) {
                                        if ((int) d.id != 0) {
                                            dialogsServerOnly.add(d);
                                        }
                                    }
                                    NotificationCenter.Instance.postNotificationName(dialogsNeedReload);
                                    MessagesStorage.Instance.putEncryptedChat(chat, user, dialog);
                                    NotificationCenter.Instance.postNotificationName(encryptedChatCreated,
                                            chat);
                                }
                            });
                        } else {
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        try {
                                            progressDialog.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                        builder.setTitle(context.getString(R.string.AppName));
                                        builder.setMessage(String.format(
                                                context.getString(R.string.CreateEncryptedChatOutdatedError),
                                                user.first_name, user.first_name));
                                        builder.setPositiveButton(
                                                ApplicationLoader.applicationContext.getString(R.string.OK),
                                                null);
                                        builder.show().setCanceledOnTouchOutside(true);
                                    }
                                }
                            });
                        }
                    }
                }, null, true,
                        RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
            } else {
                Utilities.RunOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!((ActionBarActivity) context).isFinishing()) {
                            try {
                                progressDialog.dismiss();
                            } catch (Exception e) {
                                FileLog.e("tmessages", e);
                            }
                        }
                    }
                });
            }
        }
    }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
}