Example usage for android.widget ProgressBar setProgress

List of usage examples for android.widget ProgressBar setProgress

Introduction

In this page you can find the example usage for android.widget ProgressBar setProgress.

Prototype

@android.view.RemotableViewMethod
public synchronized void setProgress(int progress) 

Source Link

Document

Sets the current progress to the specified value.

Usage

From source file:io.github.trulyfree.easyaspi.MainActivity.java

/**
 * @param stageText/*from www  . ja v a 2s.c om*/
 * @param progressBar
 * @return
 */
private StagedCallback makeModuleCallback(final TextView stageText, final ProgressBar progressBar) {
    return new StagedCallback() {
        private String[] names;
        private int stage = 0;

        @Override
        public void setStages(String[] names) {
            this.names = names;
        }

        @Override
        public void onStart() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    stageText.setText(names[stage]);
                }
            });
        }

        @Override
        public void onProgress(final int current) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int numerator = stage * 100 + current;
                    int denominator = names.length;
                    final int progress = numerator / denominator;
                    progressBar.setProgress(progress);
                }
            });
        }

        @Override
        public void onFinish() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    stage++;
                    if (stage == names.length) {
                        stageText.setText("");
                        progressBar.setProgress(0);
                        Toast.makeText(MainActivity.this, "Download(s) successful.", Toast.LENGTH_SHORT).show();
                        refreshFilling();
                    }
                }
            });
        }
    };
}

From source file:com.ternup.caddisfly.activity.VideoActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_video);

    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
    File sdDir = this.getExternalFilesDir(null);
    final File videoFile = new File(sdDir, "training.mp4");

    if (videoFile.exists()) {
        playVideo(videoFile);//from ww  w .  ja va2  s .  c o m
    } else {

        if (NetworkUtils.checkInternetConnection(this)) {
            progressBar.setVisibility(View.VISIBLE);
            downloading = true;
            AsyncHttpClient client = new AsyncHttpClient();
            client.get("http://caddisfly.ternup.com/akvoapp/caddisfly-training.mp4",
                    new FileAsyncHttpResponseHandler(videoFile) {
                        @Override
                        public void onFailure(int i, Header[] headers, Throwable throwable, File file) {
                            progressBar.setVisibility(View.GONE);
                        }

                        @Override
                        public void onSuccess(int statusCode, Header[] headers, File response) {
                            playVideo(response);
                            progressBar.setVisibility(View.GONE);
                        }

                        @Override
                        public void onProgress(int bytesWritten, int totalSize) {
                            //int progressPercentage = (int)100*bytesWritten/totalSize;
                            progressBar.setMax(totalSize);
                            progressBar.setProgress(bytesWritten);
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                            progressBar.setVisibility(View.GONE);
                            downloading = false;
                        }
                    });
        }
    }

}

From source file:net.olejon.mdapp.MedicationFelleskatalogenFragment.java

@SuppressLint("SetJavaScriptEnabled")
@Override//from   w w w.j  a  v a 2s . c  o  m
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
    ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_medication_felleskatalogen, container,
            false);

    // Activity
    final Activity activity = getActivity();

    // Context
    final Context context = activity.getApplicationContext();

    // Tools
    final MyTools mTools = new MyTools(context);

    // Arguments
    Bundle bundle = getArguments();

    final String pageUri = bundle.getString("uri");

    // Progress bar
    final ProgressBar progressBar = (ProgressBar) activity
            .findViewById(R.id.medication_toolbar_progressbar_horizontal);

    // Toolbar
    final LinearLayout toolbarSearchLayout = (LinearLayout) activity
            .findViewById(R.id.medication_toolbar_search_layout);
    final EditText toolbarSearchEditText = (EditText) activity.findViewById(R.id.medication_toolbar_search);

    // Web view
    WEBVIEW = (WebView) viewGroup.findViewById(R.id.medication_felleskatalogen_content);

    WebSettings webSettings = WEBVIEW.getSettings();
    webSettings.setJavaScriptEnabled(true);

    WEBVIEW.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!mTools.isDeviceConnected()) {
                mTools.showToast(getString(R.string.device_not_connected), 0);
                return true;
            } else if (url.matches("^https?://.*?\\.pdf$")) {
                mTools.downloadFile(view.getTitle(), url);
                return true;
            }

            return false;
        }
    });

    WEBVIEW.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressBar.setVisibility(View.INVISIBLE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);

                toolbarSearchLayout.setVisibility(View.GONE);
                toolbarSearchEditText.setText("");
            }
        }
    });

    if (savedInstanceState == null) {
        WEBVIEW.loadUrl(pageUri);
    } else {
        WEBVIEW.restoreState(savedInstanceState);
    }

    return viewGroup;
}

From source file:com.goliathonline.android.kegbot.ui.WhatsOnFragment.java

private void onTapQueryComplete(Cursor cursor) {
    if (cursor == null)
        return;/*from  w w  w. jav a 2  s . com*/
    else if (cursor.getCount() == 0)
        return;

    final LayoutInflater inflater = getActivity().getLayoutInflater();

    final View onTapView = inflater.inflate(R.layout.whats_on_tap, mRootView, false);
    final TextView onTapTitleView = (TextView) onTapView.findViewById(R.id.on_tap);
    final TextView onTapSubTitleView = (TextView) onTapView.findViewById(R.id.whats_on_subtitle);
    final ProgressBar kegProgress = (ProgressBar) onTapView.findViewById(R.id.kegProgress);
    final ImageView tapImage = (ImageView) onTapView.findViewById(R.id.tap_image);
    final TextView degreesText = (TextView) onTapView.findViewById(R.id.temperature);

    cursor.moveToFirst();
    final String tapImageUrl = cursor.getString(TapsQuery.IMAGE_URL);

    if (!TextUtils.isEmpty(tapImageUrl)) {
        BitmapUtils.fetchImage(getActivity(), tapImageUrl, null, null,
                new BitmapUtils.OnFetchCompleteListener() {
                    public void onFetchComplete(Object cookie, Bitmap result) {
                        if (result != null) {
                            tapImage.setImageBitmap(result);
                        }
                    }
                });
    }

    onTapTitleView.setText(cursor.getString(TapsQuery.BEER_NAME));

    final Double mlRemain = cursor.getDouble(TapsQuery.VOL_REMAIN);
    final String pintsRemain = UnitUtils.mlToPint(Double.toString(mlRemain));
    final Double mlTotal = cursor.getDouble(TapsQuery.VOL_SIZE);
    final Double mlPoured = mlTotal - mlRemain;
    final String pintsPoured = UnitUtils.mlToPint(Double.toString(mlPoured));
    final Double lastTemp = cursor.getDouble(TapsQuery.LAST_TEMP);
    final String temperature = UnitUtils.cToF(Double.toString(lastTemp));

    onTapSubTitleView.setText("Pints Poured: " + pintsPoured + " (" + pintsRemain + " remain)");

    kegProgress.setProgressDrawable(getResources().getDrawable(R.drawable.progress));
    kegProgress.setProgress((int) cursor.getDouble(TapsQuery.PERCENT_FULL));

    degreesText.setText(temperature + DEGREES);

    cursor.close();
    mRootView.addView(onTapView);

}

From source file:com.money.manager.ex.fragment.HomeFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    MainActivity mainActivity = null;/*from   w ww  .  j  a  va 2s.  c  om*/
    if (getActivity() != null && getActivity() instanceof MainActivity)
        mainActivity = (MainActivity) getActivity();

    switch (loader.getId()) {
    case ID_LOADER_USER_NAME:
        if (data != null && data.moveToFirst()) {
            while (data.isAfterLast() == false) {
                String infoValue = data.getString(data.getColumnIndex(infoTable.INFONAME));
                // save into preferences username and basecurrency id
                if (Constants.INFOTABLE_USERNAME.equalsIgnoreCase(infoValue)) {
                    application.setUserName(data.getString(data.getColumnIndex(infoTable.INFOVALUE)));
                } else if (Constants.INFOTABLE_BASECURRENCYID.equalsIgnoreCase(infoValue)) {
                    //application.setBaseCurrencyId(data.getInt(data.getColumnIndex(infoTable.INFOVALUE)));
                }
                data.moveToNext();
            }
        }
        // show username
        if (!TextUtils.isEmpty(application.getUserName()))
            ((SherlockFragmentActivity) getActivity()).getSupportActionBar()
                    .setSubtitle(application.getUserName());
        // set user name on drawer
        if (mainActivity != null)
            mainActivity.setDrawableUserName(application.getUserName());

        break;

    case ID_LOADER_ACCOUNT_BILLS:
        double curTotal = 0, curReconciled = 0;
        AccountBillsAdapter adapter = null;

        linearHome.setVisibility(data != null && data.getCount() > 0 ? View.VISIBLE : View.GONE);
        linearWelcome.setVisibility(linearHome.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);

        // cycle cursor
        if (data != null && data.moveToFirst()) {
            while (data.isAfterLast() == false) {
                curTotal += data.getDouble(data.getColumnIndex(QueryAccountBills.TOTALBASECONVRATE));
                curReconciled += data.getDouble(data.getColumnIndex(QueryAccountBills.RECONCILEDBASECONVRATE));
                data.moveToNext();
            }
            // create adapter
            adapter = new AccountBillsAdapter(getActivity(), data);
        }
        // write accounts total
        txtTotalAccounts.setText(currencyUtils.getBaseCurrencyFormatted(curTotal));
        // manage footer listview
        if (linearFooter == null) {
            linearFooter = (LinearLayout) getActivity().getLayoutInflater().inflate(R.layout.item_account_bills,
                    null);
            // textview into layout
            txtFooterSummary = (TextView) linearFooter.findViewById(R.id.textVievItemAccountTotal);
            txtFooterSummaryReconciled = (TextView) linearFooter
                    .findViewById(R.id.textVievItemAccountTotalReconciled);
            // set text
            TextView txtTextSummary = (TextView) linearFooter.findViewById(R.id.textVievItemAccountName);
            txtTextSummary.setText(R.string.summary);
            // invisibile image
            ImageView imgSummary = (ImageView) linearFooter.findViewById(R.id.imageViewAccountType);
            imgSummary.setVisibility(View.INVISIBLE);
            // set color textview
            txtTextSummary.setTextColor(Color.GRAY);
            txtFooterSummary.setTextColor(Color.GRAY);
            txtFooterSummaryReconciled.setTextColor(Color.GRAY);
        }
        // remove footer
        lstAccountBills.removeFooterView(linearFooter);
        // set text
        txtFooterSummary.setText(txtTotalAccounts.getText());
        txtFooterSummaryReconciled.setText(currencyUtils.getBaseCurrencyFormatted(curReconciled));
        // add footer
        lstAccountBills.addFooterView(linearFooter, null, false);
        // set adapter and shown
        lstAccountBills.setAdapter(adapter);
        setListViewAccountBillsVisible(true);
        // set total accounts in drawer
        if (mainActivity != null) {
            mainActivity.setDrawableTotalAccounts(txtTotalAccounts.getText().toString());
        }
        break;

    case ID_LOADER_BILL_DEPOSITS:
        mainActivity.setDrawableRepeatingTransactions(data != null ? data.getCount() : 0);
        break;

    case ID_LOADER_INCOME_EXPENSES:
        double income = 0, expenses = 0;
        if (data != null && data.moveToFirst()) {
            while (!data.isAfterLast()) {
                expenses = data.getDouble(data.getColumnIndex(QueryReportIncomeVsExpenses.Expenses));
                income = data.getDouble(data.getColumnIndex(QueryReportIncomeVsExpenses.Income));
                //move to next record
                data.moveToNext();
            }
        }
        TextView txtIncome = (TextView) getActivity().findViewById(R.id.textViewIncome);
        TextView txtExpenses = (TextView) getActivity().findViewById(R.id.textViewExpenses);
        TextView txtDifference = (TextView) getActivity().findViewById(R.id.textViewDifference);
        // set value
        if (txtIncome != null)
            txtIncome.setText(currencyUtils.getCurrencyFormatted(currencyUtils.getBaseCurrencyId(), income));
        if (txtExpenses != null)
            txtExpenses.setText(
                    currencyUtils.getCurrencyFormatted(currencyUtils.getBaseCurrencyId(), Math.abs(expenses)));
        if (txtDifference != null)
            txtDifference.setText(currencyUtils.getCurrencyFormatted(currencyUtils.getBaseCurrencyId(),
                    income - Math.abs(expenses)));
        // manage progressbar
        final ProgressBar barIncome = (ProgressBar) getActivity().findViewById(R.id.progressBarIncome);
        final ProgressBar barExpenses = (ProgressBar) getActivity().findViewById(R.id.progressBarExpenses);

        if (barIncome != null && barExpenses != null) {
            barIncome.setMax((int) (Math.abs(income) + Math.abs(expenses)));
            barExpenses.setMax((int) (Math.abs(income) + Math.abs(expenses)));

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
                ObjectAnimator animationIncome = ObjectAnimator.ofInt(barIncome, "progress",
                        (int) Math.abs(income));
                animationIncome.setDuration(1000); // 0.5 second
                animationIncome.setInterpolator(new DecelerateInterpolator());
                animationIncome.start();

                ObjectAnimator animationExpenses = ObjectAnimator.ofInt(barExpenses, "progress",
                        (int) Math.abs(expenses));
                animationExpenses.setDuration(1000); // 0.5 second
                animationExpenses.setInterpolator(new DecelerateInterpolator());
                animationExpenses.start();
            } else {
                barIncome.setProgress((int) Math.abs(income));
                barExpenses.setProgress((int) Math.abs(expenses));
            }
        }
    }
}

From source file:net.olejon.mdapp.MedicationNlhFragment.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*from w w  w  . j  a v  a  2  s . c  o  m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
    ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_medication_nlh, container, false);

    // Activity
    final Activity activity = getActivity();

    // Context
    final Context context = activity.getApplicationContext();

    // Tools
    final MyTools mTools = new MyTools(context);

    // Arguments
    Bundle bundle = getArguments();

    final String pageUri = bundle.getString("uri");

    // Progress bar
    final ProgressBar progressBar = (ProgressBar) activity
            .findViewById(R.id.medication_toolbar_progressbar_horizontal);

    // Toolbar
    final LinearLayout toolbarSearchLayout = (LinearLayout) activity
            .findViewById(R.id.medication_toolbar_search_layout);
    final EditText toolbarSearchEditText = (EditText) activity.findViewById(R.id.medication_toolbar_search);

    // Web view
    WEBVIEW = (WebView) viewGroup.findViewById(R.id.medication_nlh_content);

    WebSettings webSettings = WEBVIEW.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setAppCachePath(context.getCacheDir().getAbsolutePath());
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

    WEBVIEW.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!mTools.isDeviceConnected()) {
                mTools.showToast(getString(R.string.device_not_connected), 0);
                return true;
            } else if (url.matches(".*/[^#]+#[^/]+$")) {
                WEBVIEW.loadUrl(url.replaceAll("#[^/]+$", ""));
                return true;
            } else if (url.matches("^https?://.*?\\.pdf$")) {
                mTools.downloadFile(view.getTitle(), url);
                return true;
            }

            return false;
        }
    });

    WEBVIEW.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressBar.setVisibility(View.INVISIBLE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);

                toolbarSearchLayout.setVisibility(View.GONE);
                toolbarSearchEditText.setText("");
            }
        }
    });

    if (savedInstanceState == null) {
        WEBVIEW.loadUrl(pageUri);
    } else {
        WEBVIEW.restoreState(savedInstanceState);
    }

    return viewGroup;
}

From source file:org.anurag.compress.ExtractTarFile.java

public ExtractTarFile(final Context ctx, final Item zFile, final int width, String extractDir, final File file,
        final int mode) {
    // TODO Auto-generated constructor stub
    running = false;/*from   w  ww . j  a  va  2  s.  c o m*/
    errors = false;
    prog = 0;
    read = 0;
    final Dialog dialog = new Dialog(ctx, Constants.DIALOG_STYLE);
    dialog.setCancelable(true);
    dialog.setContentView(R.layout.extract_file);
    dialog.getWindow().getAttributes().width = width;
    DEST = extractDir;
    final ProgressBar progress = (ProgressBar) dialog.findViewById(R.id.zipProgressBar);
    final TextView to = (TextView) dialog.findViewById(R.id.zipFileName);
    final TextView from = (TextView) dialog.findViewById(R.id.zipLoc);
    final TextView cfile = (TextView) dialog.findViewById(R.id.zipSize);
    final TextView zsize = (TextView) dialog.findViewById(R.id.zipNoOfFiles);
    final TextView status = (TextView) dialog.findViewById(R.id.zipFileLocation);

    if (extractDir == null)
        to.setText(ctx.getString(R.string.extractingto) + " Cache directory");
    else
        to.setText(ctx.getString(R.string.extractingto) + " " + DEST);

    from.setText(ctx.getString(R.string.extractingfrom) + " " + file.getName());

    if (mode == 2) {
        //TAR ENTRY HAS TO BE SHARED VIA BLUETOOTH,ETC...
        TextView t = null;//= (TextView)dialog.findViewById(R.id.preparing);
        t.setText(ctx.getString(R.string.preparingtoshare));
    }

    try {
        if (file.getName().endsWith(".tar.gz"))
            tar = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(file)));
        else
            tar = new TarArchiveInputStream(new BufferedInputStream(new FileInputStream(file)));
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        tar = null;
    }

    final Handler handle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 0:

                progress.setProgress(0);
                cfile.setText(ctx.getString(R.string.extractingfile) + " " + name);
                break;

            case 1:
                status.setText(name);
                progress.setProgress((int) prog);
                break;
            case 2:
                try {
                    tar.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (running) {
                    dialog.dismiss();
                    if (mode == 0) {
                        //after extracting file ,it has to be opened....
                        new OpenFileDialog(ctx, Uri.parse(dest));
                    } else if (mode == 2) {
                        //FILE HAS TO BE SHARED....
                        new BluetoothChooser(ctx, new File(dest).getAbsolutePath(), null);
                    } else {
                        if (errors)
                            Toast.makeText(ctx, ctx.getString(R.string.errorinext), Toast.LENGTH_SHORT).show();
                        Toast.makeText(ctx, ctx.getString(R.string.fileextracted), Toast.LENGTH_SHORT).show();
                    }
                }

                break;
            case 3:
                zsize.setText(size);
                progress.setMax((int) max);
                break;
            case 4:
                status.setText(ctx.getString(R.string.preparing));
                break;
            case 5:
                running = false;
                Toast.makeText(ctx, ctx.getString(R.string.extaborted), Toast.LENGTH_SHORT).show();
            }
        }
    };

    final Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (running) {
                if (DEST == null) {
                    DEST = Environment.getExternalStorageDirectory() + "/Android/data/org.anurag.file.quest";
                    new File(DEST).mkdirs();
                }

                TarArchiveEntry ze;
                try {
                    while ((ze = tar.getNextTarEntry()) != null) {
                        if (ze.isDirectory())
                            continue;
                        handle.sendEmptyMessage(4);
                        if (!zFile.isDirectory()) {
                            //EXTRACTING A SINGLE FILE FROM AN ARCHIVE....
                            if (ze.getName().equalsIgnoreCase(zFile.t_getEntryName())) {
                                try {

                                    //SENDING CURRENT FILE NAME....
                                    try {
                                        name = zFile.getName();
                                    } catch (Exception e) {
                                        name = zFile.t_getEntryName();
                                    }
                                    handle.sendEmptyMessage(0);
                                    dest = DEST;
                                    dest = dest + "/" + name;
                                    FileOutputStream out = new FileOutputStream((dest));
                                    max = ze.getSize();
                                    size = AppBackup.size(max, ctx);
                                    handle.sendEmptyMessage(3);
                                    InputStream fin = tar;
                                    while ((read = fin.read(data)) != -1 && running) {
                                        out.write(data, 0, read);
                                        prog += read;
                                        name = AppBackup.status(prog, ctx);
                                        handle.sendEmptyMessage(1);
                                    }
                                    out.flush();
                                    out.close();
                                    fin.close();
                                    break;
                                } catch (FileNotFoundException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                    //errors = true;
                                } catch (IOException e) {
                                    errors = true;
                                }
                            }
                        } else {
                            //EXTRACTING A DIRECTORY FROM TAR ARCHIVE....
                            String p = zFile.getPath();
                            if (p.startsWith("/"))
                                p = p.substring(1, p.length());
                            if (ze.getName().startsWith(p)) {
                                prog = 0;
                                dest = DEST;
                                name = ze.getName();
                                String path = name;
                                name = name.substring(name.lastIndexOf("/") + 1, name.length());
                                handle.sendEmptyMessage(0);

                                String foname = zFile.getPath();
                                if (!foname.startsWith("/"))
                                    foname = "/" + foname;

                                if (!path.startsWith("/"))
                                    path = "/" + path;
                                path = path.substring(foname.lastIndexOf("/"), path.lastIndexOf("/"));
                                if (!path.startsWith("/"))
                                    path = "/" + path;
                                dest = dest + path;
                                new File(dest).mkdirs();
                                dest = dest + "/" + name;

                                FileOutputStream out;
                                try {
                                    max = ze.getSize();
                                    out = new FileOutputStream((dest));
                                    size = AppBackup.size(max, ctx);
                                    handle.sendEmptyMessage(3);

                                    //   InputStream fin = tar;
                                    while ((read = tar.read(data)) != -1 && running) {
                                        out.write(data, 0, read);
                                        prog += read;
                                        name = AppBackup.status(prog, ctx);
                                        handle.sendEmptyMessage(1);
                                    }
                                    out.flush();
                                    out.close();
                                    //fin.close();
                                } catch (FileNotFoundException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                    //   errors = true;
                                } catch (IOException e) {
                                    errors = true;
                                } catch (Exception e) {
                                    //errors = true;
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    errors = true;
                }
                handle.sendEmptyMessage(2);
            }
        }
    });
    /*
    Button cancel = (Button)dialog.findViewById(R.id.calcelButton);
    cancel.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View arg0) {
    // TODO Auto-generated method stub
    dialog.dismiss();
    handle.sendEmptyMessage(5);
       }
    });
    Button st = (Button)dialog.findViewById(R.id.extractButton);
    st.setVisibility(View.GONE);*/

    dialog.show();
    running = true;
    thread.start();
    dialog.setCancelable(false);
    progress.setVisibility(View.VISIBLE);
}

From source file:com.money.manager.ex.home.HomeFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    switch (loader.getId()) {
    case LOADER_ACCOUNT_BILLS:
        try {/*  ww  w. ja v  a 2 s  .  com*/
            renderAccountsList(data);
        } catch (Exception e) {
            Timber.e(e, "rendering account list");
        }

        // set total for accounts in the main Drawer.
        EventBus.getDefault().post(new AccountsTotalLoadedEvent(txtTotalAccounts.getText().toString()));
        break;

    case LOADER_INCOME_EXPENSES:
        double income = 0, expenses = 0;
        if (data != null) {
            while (data.moveToNext()) {
                expenses = data.getDouble(data.getColumnIndex(IncomeVsExpenseReportEntity.Expenses));
                income = data.getDouble(data.getColumnIndex(IncomeVsExpenseReportEntity.Income));
            }
        }
        TextView txtIncome = (TextView) getActivity().findViewById(R.id.textViewIncome);
        TextView txtExpenses = (TextView) getActivity().findViewById(R.id.textViewExpenses);
        TextView txtDifference = (TextView) getActivity().findViewById(R.id.textViewDifference);
        // set value
        if (txtIncome != null)
            txtIncome.setText(mCurrencyService.getCurrencyFormatted(mCurrencyService.getBaseCurrencyId(),
                    MoneyFactory.fromDouble(income)));
        if (txtExpenses != null)
            txtExpenses.setText(mCurrencyService.getCurrencyFormatted(mCurrencyService.getBaseCurrencyId(),
                    MoneyFactory.fromDouble(Math.abs(expenses))));
        if (txtDifference != null)
            txtDifference.setText(mCurrencyService.getCurrencyFormatted(mCurrencyService.getBaseCurrencyId(),
                    MoneyFactory.fromDouble(income - Math.abs(expenses))));
        // manage progressbar
        final ProgressBar barIncome = (ProgressBar) getActivity().findViewById(R.id.progressBarIncome);
        final ProgressBar barExpenses = (ProgressBar) getActivity().findViewById(R.id.progressBarExpenses);

        if (barIncome != null && barExpenses != null) {
            barIncome.setMax((int) (Math.abs(income) + Math.abs(expenses)));
            barExpenses.setMax((int) (Math.abs(income) + Math.abs(expenses)));

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
                ObjectAnimator animationIncome = ObjectAnimator.ofInt(barIncome, "progress",
                        (int) Math.abs(income));
                animationIncome.setDuration(1000); // 0.5 second
                animationIncome.setInterpolator(new DecelerateInterpolator());
                animationIncome.start();

                ObjectAnimator animationExpenses = ObjectAnimator.ofInt(barExpenses, "progress",
                        (int) Math.abs(expenses));
                animationExpenses.setDuration(1000); // 0.5 second
                animationExpenses.setInterpolator(new DecelerateInterpolator());
                animationExpenses.start();
            } else {
                barIncome.setProgress((int) Math.abs(income));
                barExpenses.setProgress((int) Math.abs(expenses));
            }
        }
        break;
    }

    // Close the cursor.
    MmxDatabaseUtils.closeCursor(data);
}

From source file:im.vector.util.BugReporter.java

/**
 * Send a bug report either with email or with Vector.
 */// ww w.j av a  2 s.  c  o m
public static void sendBugReport() {
    final Activity currentActivity = VectorApp.getCurrentActivity();

    // no current activity so cannot display an alert
    if (null == currentActivity) {
        sendBugReport(VectorApp.getInstance().getApplicationContext(), true, true, "", null);
        return;
    }

    final Context appContext = currentActivity.getApplicationContext();
    LayoutInflater inflater = currentActivity.getLayoutInflater();
    View dialogLayout = inflater.inflate(R.layout.dialog_bug_report, null);

    final AlertDialog.Builder dialog = new AlertDialog.Builder(currentActivity);
    dialog.setTitle(R.string.send_bug_report);
    dialog.setView(dialogLayout);

    final EditText bugReportText = (EditText) dialogLayout.findViewById(R.id.bug_report_edit_text);
    final CheckBox includeLogsButton = (CheckBox) dialogLayout
            .findViewById(R.id.bug_report_button_include_logs);
    final CheckBox includeCrashLogsButton = (CheckBox) dialogLayout
            .findViewById(R.id.bug_report_button_include_crash_logs);

    final ProgressBar progressBar = (ProgressBar) dialogLayout.findViewById(R.id.bug_report_progress_view);
    final TextView progressTextView = (TextView) dialogLayout.findViewById(R.id.bug_report_progress_text_view);

    dialog.setPositiveButton(R.string.send, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // will be overridden to avoid dismissing the dialog while displaying the progress
        }
    });

    dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // will be overridden to avoid dismissing the dialog while displaying the progress
        }
    });

    //
    final AlertDialog bugReportDialog = dialog.show();
    final Button cancelButton = bugReportDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
    final Button sendButton = bugReportDialog.getButton(AlertDialog.BUTTON_POSITIVE);

    if (null != cancelButton) {
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // check if there is no upload in progress
                if (includeLogsButton.isEnabled()) {
                    bugReportDialog.dismiss();
                } else {
                    mIsCancelled = true;
                    cancelButton.setEnabled(false);
                }
            }
        });
    }

    if (null != sendButton) {
        sendButton.setEnabled(false);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // disable the active area while uploading the bug report
                bugReportText.setEnabled(false);
                sendButton.setEnabled(false);
                includeLogsButton.setEnabled(false);
                includeCrashLogsButton.setEnabled(false);

                progressTextView.setVisibility(View.VISIBLE);
                progressTextView.setText(appContext.getString(R.string.send_bug_report_progress, 0 + ""));

                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(0);

                sendBugReport(VectorApp.getInstance(), includeLogsButton.isChecked(),
                        includeCrashLogsButton.isChecked(), bugReportText.getText().toString(),
                        new IMXBugReportListener() {
                            @Override
                            public void onUploadFailed(String reason) {
                                try {
                                    if (null != VectorApp.getInstance() && !TextUtils.isEmpty(reason)) {
                                        Toast.makeText(VectorApp.getInstance(),
                                                VectorApp.getInstance()
                                                        .getString(R.string.send_bug_report_failed, reason),
                                                Toast.LENGTH_LONG).show();
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "## onUploadFailed() : failed to display the toast "
                                            + e.getMessage());
                                }

                                try {
                                    // restore the dialog if the upload failed
                                    bugReportText.setEnabled(true);
                                    sendButton.setEnabled(true);
                                    includeLogsButton.setEnabled(true);
                                    includeCrashLogsButton.setEnabled(true);
                                    cancelButton.setEnabled(true);

                                    progressTextView.setVisibility(View.GONE);
                                    progressBar.setVisibility(View.GONE);
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "## onUploadFailed() : failed to restore the dialog button "
                                            + e.getMessage());

                                    try {
                                        bugReportDialog.dismiss();
                                    } catch (Exception e2) {
                                        Log.e(LOG_TAG, "## onUploadFailed() : failed to dismiss the dialog "
                                                + e2.getMessage());
                                    }
                                }

                                mIsCancelled = false;
                            }

                            @Override
                            public void onUploadCancelled() {
                                onUploadFailed(null);
                            }

                            @Override
                            public void onProgress(int progress) {
                                if (progress > 100) {
                                    Log.e(LOG_TAG, "## onProgress() : progress > 100");
                                    progress = 100;
                                } else if (progress < 0) {
                                    Log.e(LOG_TAG, "## onProgress() : progress < 0");
                                    progress = 0;
                                }

                                progressBar.setProgress(progress);
                                progressTextView.setText(
                                        appContext.getString(R.string.send_bug_report_progress, progress + ""));
                            }

                            @Override
                            public void onUploadSucceed() {
                                try {
                                    if (null != VectorApp.getInstance()) {
                                        Toast.makeText(VectorApp.getInstance(),
                                                VectorApp.getInstance().getString(
                                                        R.string.send_bug_report_sent),
                                                Toast.LENGTH_LONG).show();
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "## onUploadSucceed() : failed to dismiss the toast "
                                            + e.getMessage());
                                }

                                try {
                                    bugReportDialog.dismiss();
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "## onUploadSucceed() : failed to dismiss the dialog "
                                            + e.getMessage());
                                }
                            }
                        });
            }
        });
    }

    bugReportText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (null != sendButton) {
                sendButton.setEnabled(bugReportText.getText().toString().length() > 10);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
}

From source file:io.github.trulyfree.easyaspi.MainActivity.java

@Override
public boolean setup() {
    downloadHandler = new DownloadHandler(this);
    fileHandler = new FileHandler(this);
    moduleHandler = new ModuleHandler(this);
    executorService = Executors.newCachedThreadPool();

    setContentView(R.layout.activity_main);
    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override// w  w  w.  j av a 2s . co m
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            ViewSwitcher viewGroup = (ViewSwitcher) findViewById(R.id.content);
            int id = item.getItemId();
            if ((id == R.id.navigation_home || id == R.id.navigation_modules) && id != currentID) {
                currentID = item.getItemId();
                viewGroup.showNext();
                return true;
            }
            return false;
        }

    });

    ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.content);
    Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
    Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
    viewSwitcher.setInAnimation(in);
    viewSwitcher.setOutAnimation(out);

    resetConfigReturned();

    Button getNewModule = (Button) findViewById(R.id.new_module_config_confirm);
    getNewModule.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            EditText editText = (EditText) findViewById(R.id.new_module_config_configurl);
            final String url = editText.getText().toString();
            Toast.makeText(MainActivity.this, "Requested config from: " + url, Toast.LENGTH_SHORT).show();
            executorService.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() {
                    ModuleConfig config;
                    try {
                        config = moduleHandler.getModuleConfig(url);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "Invalid URL. :(", Toast.LENGTH_LONG).show();
                            }
                        });
                        return false;
                    } catch (IOException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "Failed to get module config. :(",
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                        return false;
                    } catch (JsonParseException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "Config loaded was invalid. :(",
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                        return false;
                    }

                    final ModuleConfig finalConfig = config;
                    final ImageView configResponseBlock = (ImageView) findViewById(R.id.block_module_returned);
                    final int colorFrom = ContextCompat.getColor(MainActivity.this, R.color.colorFillingTint);
                    final int colorTo = ContextCompat.getColor(MainActivity.this, R.color.colorClear);
                    final ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom,
                            colorTo);
                    colorAnimation.setDuration(ANIMATION_DURATION);
                    colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animator) {
                            configResponseBlock.setBackgroundColor((Integer) animator.getAnimatedValue());
                        }
                    });
                    colorAnimation.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animator) {
                        }

                        @Override
                        public void onAnimationEnd(Animator animator) {
                            LinearLayout layout = (LinearLayout) findViewById(R.id.module_returned_config);
                            EditText moduleName = (EditText) findViewById(R.id.module_returned_configname);
                            EditText moduleVersion = (EditText) findViewById(
                                    R.id.module_returned_configversion);
                            EditText moduleConfigUrl = (EditText) findViewById(R.id.module_returned_configurl);
                            EditText moduleJarUrl = (EditText) findViewById(R.id.module_returned_jarurl);
                            LinearLayout moduleDependencies = (LinearLayout) findViewById(
                                    R.id.module_returned_dependencies);
                            moduleDependencies.removeAllViewsInLayout();
                            try {
                                configResponseBlock.setVisibility(View.GONE);
                                moduleName.setText(finalConfig.getName());
                                moduleVersion.setText(finalConfig.getVersion());
                                moduleConfigUrl.setText(finalConfig.getConfUrl());
                                moduleJarUrl.setText(finalConfig.getJarUrl());
                                Config[] dependencies = finalConfig.getDependencies();
                                for (Config dependency : dependencies) {
                                    LinearLayout dependencyLayout = new LinearLayout(MainActivity.this);
                                    dependencyLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                                            LayoutParams.WRAP_CONTENT));
                                    dependencyLayout.setOrientation(LinearLayout.HORIZONTAL);
                                    EditText name = new EditText(MainActivity.this);
                                    EditText jarUrl = new EditText(MainActivity.this);
                                    EditText[] loopThrough = { name, jarUrl };
                                    LayoutParams params = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f);
                                    for (EditText item : loopThrough) {
                                        item.setLayoutParams(params);
                                        item.setClickable(false);
                                        item.setInputType(InputType.TYPE_NULL);
                                        item.setCursorVisible(false);
                                        item.setFocusable(false);
                                        item.setFocusableInTouchMode(false);
                                    }
                                    name.setText(dependency.getName());
                                    jarUrl.setText(dependency.getJarUrl());
                                    dependencyLayout.addView(name);
                                    dependencyLayout.addView(jarUrl);
                                    moduleDependencies.addView(dependencyLayout);
                                }
                                layout.setClickable(true);
                                Button validate = (Button) findViewById(R.id.module_returned_validate);
                                Button cancel = (Button) findViewById(R.id.module_returned_cancel);
                                validate.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Toast.makeText(MainActivity.this, "Requesting jars...",
                                                Toast.LENGTH_SHORT).show();
                                        executorService.submit(new Callable<Boolean>() {
                                            @Override
                                            public Boolean call() {
                                                try {
                                                    boolean success = true, refreshAllModification = true;
                                                    Button refreshAll = null,
                                                            getNewModule = (Button) findViewById(
                                                                    R.id.new_module_config_confirm);
                                                    try {
                                                        refreshAll = (Button) findViewById(R.id.refresh_all);
                                                        refreshAll.setClickable(false);
                                                    } catch (Throwable e) {
                                                        refreshAllModification = false;
                                                    }
                                                    getNewModule.setClickable(false);
                                                    final TextView stager = (TextView) findViewById(
                                                            R.id.new_module_config_downloadstage);
                                                    final ProgressBar progressBar = (ProgressBar) findViewById(
                                                            R.id.new_module_config_downloadprogress);
                                                    try {
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                resetConfigReturned();
                                                            }
                                                        });
                                                        moduleHandler.getNewModule(
                                                                makeModuleCallback(stager, progressBar),
                                                                finalConfig, null, true);
                                                    } catch (IOException e) {
                                                        e.printStackTrace();
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                stager.setText("");
                                                                progressBar.setProgress(0);
                                                            }
                                                        });
                                                        success = false;
                                                    }
                                                    getNewModule.setClickable(true);
                                                    if (refreshAllModification) {
                                                        refreshAll.setClickable(true);
                                                    }
                                                    return success;
                                                } catch (Throwable throwable) {
                                                    throwable.printStackTrace();
                                                    return false;
                                                }
                                            }
                                        });
                                    }
                                });
                                cancel.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Toast.makeText(MainActivity.this, "Cancelling request...",
                                                Toast.LENGTH_SHORT).show();
                                        resetConfigReturned();
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(MainActivity.this, "Module config invalid. :(",
                                        Toast.LENGTH_LONG).show();
                                layout.setClickable(false);
                                final int colorFrom = ContextCompat.getColor(MainActivity.this,
                                        R.color.colorClear);
                                final int colorTo = ContextCompat.getColor(MainActivity.this,
                                        R.color.colorFillingTint);
                                ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(),
                                        colorFrom, colorTo);
                                colorAnimation.setDuration(ANIMATION_DURATION);
                                colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                    @Override
                                    public void onAnimationUpdate(ValueAnimator animator) {
                                        configResponseBlock
                                                .setBackgroundColor((Integer) animator.getAnimatedValue());
                                    }
                                });
                            }
                        }

                        @Override
                        public void onAnimationCancel(Animator animator) {
                        }

                        @Override
                        public void onAnimationRepeat(Animator animator) {
                        }
                    });
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            colorAnimation.start();
                        }
                    });
                    return true;
                }
            });
        }
    });

    moduleHandler.setup();
    refreshFilling();
    return true;
}