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:es.usc.citius.servando.calendula.activities.ConfirmSchedulesActivity.java

private void saveSchedules() {

    final ProgressDialog progress = ProgressDialog.show(this, "Calendula", "Actualizando pautas...", true);

    AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
        @Override//from w w w.  j a  va  2  s .c o m
        protected Boolean doInBackground(Void... arg0) {
            try {
                TransactionManager.callInTransaction(DB.helper().getConnectionSource(), new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {

                        for (int i = 0; i < scheduleCount; i++) {

                            Log.d("PRESCRIPTION", "Item " + i);

                            Fragment f = getViewPagerFragment(i + 1);

                            if (f instanceof ScheduleImportFragment) {

                                Log.d("PRESCRIPTION", "Fragment " + i);

                                ScheduleImportFragment c = (ScheduleImportFragment) f;

                                if (c.validate()) {
                                    PrescriptionWrapper w = prescriptionList.get(i);
                                    Log.d("PRESCRIPTION", "Validate!");
                                    String cn = w.cn;
                                    Medicine m = null;
                                    if (cn != null) {
                                        m = DB.medicines().findByCnAndPatient(cn, patient);
                                        if (m == null) {
                                            Log.d("PRESCRIPTION", "Saving medicine!");
                                            m = Medicine.fromPrescription(Prescription.findByCn(cn));
                                            m.setPatient(patient);
                                            m.save();
                                        }
                                    } else if (w.isGroup) {
                                        m = DB.medicines().findByGroupAndPatient(w.group.getId(), patient);
                                        if (m == null) {
                                            m = new Medicine(Strings.firstPart(w.group.name));
                                            m.setHomogeneousGroup(w.group.getId());
                                            Presentation pres = Presentation.expected(w.group.name,
                                                    w.group.name);
                                            m.setPresentation(pres != null ? pres : Presentation.PILLS);
                                            m.setPatient(patient);
                                            m.save();
                                        }
                                    } else {
                                        throw new RuntimeException(
                                                " Prescription must have a cn or group reference");
                                    }

                                    Schedule s = c.getSchedule();
                                    Schedule prev = DB.schedules().findByMedicineAndPatient(m, patient);
                                    // TODO: find by med and patient
                                    if (prev != null) {
                                        Log.d("PRESCRIPTION", "Found previous schedule for med " + m.getId());
                                        updateSchedule(prev, s, c.getScheduleItems());
                                    } else {
                                        Log.d("PRESCRIPTION",
                                                "Not found previous schedule for med " + m.getId());
                                        createSchedule(s, c.getScheduleItems(), m);
                                    }

                                    if (m != null) {
                                        // remove old pickups before inserting the new ones
                                        DB.pickups().removeByMed(m);
                                    }

                                    if (m != null && w.pk != null && w.pk.size() > 0) {

                                        for (PickupWrapper pkw : w.pk) {
                                            PickupInfo pickupInfo = new PickupInfo();
                                            pickupInfo.setTo(df.parseLocalDate(pkw.t).plusMonths(19));
                                            pickupInfo.setFrom(df.parseLocalDate(pkw.f).plusMonths(19));
                                            pickupInfo.taken(pkw.tk == 1 ? true : false);
                                            pickupInfo.setMedicine(m);
                                            DB.pickups().save(pickupInfo);
                                        }
                                    }
                                } else {
                                    mViewPager.setCurrentItem(i + 1);
                                    Snack.show("Hmmmmmm....", ConfirmSchedulesActivity.this);
                                }
                            }
                        }
                        CalendulaApp.eventBus().post(PersistenceEvents.SCHEDULE_EVENT);
                        AlarmScheduler.instance().updateAllAlarms(ConfirmSchedulesActivity.this);
                        return null;
                    }
                });

                return true;

            } catch (Exception e) {
                Log.e("ConfirmSchedulesAct", "Error saving prescriptions", e);
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (progress != null) {
                progress.dismiss();
            }
            if (result) {
                finish();
            }
        }
    };

    task.execute((Void[]) null);
}

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

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

    final ProgressDialog ringProgressDialog = ProgressDialog.show(getActivity(),
            getResources().getString(R.string.please_wait), getResources().getString(R.string.populating_data),
            true);//ww  w . j  ava  2s  . com
    ringProgressDialog.setCancelable(true);
    new Thread(new Runnable() {

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

                getActivity().runOnUiThread(new Runnable() {

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

                    }
                });

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

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

                final XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
                CategorySeries seriesProtein = new CategorySeries("Protein");
                CategorySeries seriesFat = new CategorySeries("Fat");
                CategorySeries seriesCarbs = new CategorySeries("Carbs");

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

                    // init "average" data
                    double totalProtein = 0, totalFat = 0, totalCarbs = 0, totalCallories = 0;
                    for (Ingridient ingridient : list) {
                        totalProtein += ingridient.protein;
                        totalFat += ingridient.fat;
                        totalCarbs += ingridient.carbohydrates;
                        totalCallories += ingridient.kkal;
                    }

                    seriesProtein.add((double) Math.round(totalProtein * 100) / 100);
                    seriesFat.add((double) Math.round(totalFat * 100) / 100);
                    seriesCarbs.add((double) Math.round(totalCarbs * 100) / 100);

                    // calculate maximum Y axis values
                    yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalProtein);
                    yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalFat);
                    yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalCarbs);

                    // increment month
                    dt = DateUtils.addMonths(dt, 1);
                }

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

                renderer.getSeriesRendererAt(0).setDisplayChartValues(true);
                renderer.getSeriesRendererAt(1).setDisplayChartValues(true);
                renderer.getSeriesRendererAt(2).setDisplayChartValues(true);

                renderer.getSeriesRendererAt(0).setChartValuesTextSize(15f);
                renderer.getSeriesRendererAt(1).setChartValuesTextSize(15f);
                renderer.getSeriesRendererAt(2).setChartValuesTextSize(15f);

                // renderer.getSeriesRendererAt(0).setChartValuesTextAlign(Align.CENTER);
                // renderer.getSeriesRendererAt(1).setChartValuesTextAlign(Align.LEFT);
                // renderer.getSeriesRendererAt(2).setChartValuesTextAlign(Align.RIGHT);

                renderer.setXLabels(0);
                // renderer.setYLabels(10);
                // renderer.setXLabelsAlign(Align.LEFT);
                // renderer.setYLabelsAlign(Align.LEFT);
                // renderer.setPanEnabled(true, false);
                renderer.setClickEnabled(false);
                renderer.setZoomEnabled(false);
                renderer.setPanEnabled(false, false);
                renderer.setZoomButtonsVisible(false);
                renderer.setPanLimits(new double[] { 1, 11 });
                // renderer.setZoomEnabled(false);
                // renderer.setZoomRate(1.1f);
                renderer.setShowGrid(true);
                renderer.setShowLegend(true);
                renderer.setFitLegend(true);

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

                }

                dataset.addSeries(seriesProtein.toXYSeries());
                dataset.addSeries(seriesFat.toXYSeries());
                dataset.addSeries(seriesCarbs.toXYSeries());

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            viewChart = ChartFactory.getLineChartView(getActivity(), dataset,
                                    renderer/* , Type.STACKED */);
                            rlRootGraphLayout.addView(viewChart, 0);
                            if (isLeftIn) {
                                rightIn.setDuration(1000);
                                viewChart.startAnimation(rightIn);
                            } else {
                                leftIn.setDuration(1000);
                                viewChart.startAnimation(leftIn);
                            }
                        } catch (Exception edsx) {
                            edsx.printStackTrace();
                        }

                    }
                });

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

}

From source file:com.progym.custom.fragments.WaterProgressYearlyLineFragment.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);// w  w w .ja va 2  s  .c om
    ringProgressDialog.setCancelable(true);

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {

                int yMaxAxisValue = 0;
                getActivity().runOnUiThread(new Runnable() {

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

                DATE = date;
                // 31 - Amount of days in a month
                int daysInMonth = Utils.getDaysInMonth(date.getMonth(),
                        Integer.valueOf(Utils.formatDate(date, DataBaseUtils.DATE_PATTERN_YYYY)));
                // set January as first month
                date.setMonth(0);
                date.setDate(1);

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

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

                List<WaterConsumed> list;
                // int userShouldConsume = (int) DataBaseUtils.getWaterUserShouldConsumePerDay();
                Date dt = date; // *
                // Adding data to Income and Expense Series
                for (int i = 0; i < x.length; i++) {
                    // get all water records consumed per this month
                    list = DataBaseUtils.getAllWaterConsumedInMonth(
                            Utils.formatDate(dt, DataBaseUtils.DATE_PATTERN_YYYY_MM));
                    // init "average" data
                    int averageWaterConsumedOnYaxis = 0;
                    for (int j = 0; j < list.size(); j++) {
                        // calculate sum of all water consumed by user in a month
                        averageWaterConsumedOnYaxis += list.get(j).volumeConsumed;
                    }
                    averageWaterConsumedOnYaxis = averageWaterConsumedOnYaxis / daysInMonth;
                    consumedSeries.add(i, averageWaterConsumedOnYaxis);
                    // normaSeries.add(i, userShouldConsume);
                    dt = DateUtils.addMonths(dt, 1);
                    yMaxAxisValue = Math.max(yMaxAxisValue, averageWaterConsumedOnYaxis);
                }

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

                // Creating XYSeriesRenderer to customize incomeSeries
                XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
                incomeRenderer.setColor(Color.rgb(50, 255, 50));
                incomeRenderer.setFillPoints(true);
                incomeRenderer.setLineWidth(2);
                incomeRenderer.setDisplayChartValues(true);

                /*
                 * // Creating XYSeriesRenderer to customize expenseSeries
                 * XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
                 * expenseRenderer.setColor(Color.rgb(80, 220, 80));
                 * expenseRenderer.setFillPoints(true);
                 * expenseRenderer.setLineWidth(2);
                 * expenseRenderer.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, ActivityWaterProgress.months_short[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("Water statistic for %s year",
                        Utils.formatDate(DATE, DataBaseUtils.DATE_PATTERN_YYYY)));
                multiRenderer.setXTitle("Months");
                multiRenderer.setYTitle("Water volume (ml)");
                multiRenderer.setAxesColor(Color.WHITE);
                multiRenderer.setShowLegend(true);
                multiRenderer.addSeriesRenderer(incomeRenderer);
                multiRenderer.setShowGrid(true);
                multiRenderer.setClickEnabled(true);
                // multiRenderer.addSeriesRenderer(expenseRenderer);
                multiRenderer.setXLabelsAngle(30);
                // multiRenderer.setBackgroundColor(Color.parseColor("#B3FFFFFF"));
                // multiRenderer.setApplyBackgroundColor(true);
                multiRenderer.setXLabelsColor(Color.WHITE);
                multiRenderer.setZoomButtonsVisible(false);
                // configure visible area
                multiRenderer.setXAxisMax(11.5);
                multiRenderer.setXAxisMin(-0.5);
                multiRenderer.setYAxisMax(yMaxAxisValue + (yMaxAxisValue / 5));
                multiRenderer.setYAxisMin(-0.1);

                multiRenderer.setAxisTitleTextSize(15);
                multiRenderer.setBarSpacing(0.1);
                multiRenderer.setZoomEnabled(true);

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        mChartView = ChartFactory.getBarChartView(getActivity(), dataset, multiRenderer,
                                Type.DEFAULT);

                        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:com.progym.custom.fragments.FoodProgressMonthlyLineFragment.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);//w  ww.j a v  a 2s .  c o  m
    ringProgressDialog.setCancelable(true);
    new Thread(new Runnable() {

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

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            rlRootGraphLayout.removeView(graphView);
                        } 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 protein = new XYSeries("Protein");
                XYSeries fat = new XYSeries("Fat");
                XYSeries carbs = new XYSeries("Carbs");

                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
                    double totalProtein = 0, totalFat = 0, totalCarbs = 0;
                    if (null != list) {
                        for (Ingridient ingridient : list) {
                            totalProtein += ingridient.protein;
                            totalFat += ingridient.fat;
                            totalCarbs += ingridient.carbohydrates;
                        }
                    }

                    protein.add(i, (double) Math.round(totalProtein * 100) / 100);
                    fat.add(i, (double) Math.round(totalFat * 100) / 100);
                    carbs.add(i, (double) Math.round(totalCarbs * 100) / 100);
                    // calories.add(i, totalCallories);
                    dt = DateUtils.addDays(dt, 1);

                    yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalProtein);
                    yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalFat);
                    yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalCarbs);
                }

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

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

                // Creating XYSeriesRenderer to customize protein series
                XYSeriesRenderer fatRenderer = new XYSeriesRenderer();
                fatRenderer.setColor(Color.rgb(123, 111, 00));
                fatRenderer.setFillPoints(true);
                fatRenderer.setLineWidth(3);
                fatRenderer.setDisplayChartValues(true);

                // Creating XYSeriesRenderer to customize protein series
                XYSeriesRenderer carbsRenderer = new XYSeriesRenderer();
                carbsRenderer.setColor(Color.rgb(222, 13, 11));
                carbsRenderer.setFillPoints(true);
                carbsRenderer.setLineWidth(3);
                carbsRenderer.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("Protein/Carbs/Fat statistic "));
                multiRenderer.setXTitle(Utils.getSpecificDateValue(DATE, "MMM") + " of "
                        + Utils.formatDate(DATE, DataBaseUtils.DATE_PATTERN_YYYY));
                multiRenderer.setYTitle("Amount (g)          ");
                multiRenderer.setAxesColor(Color.WHITE);
                multiRenderer.setShowLegend(true);
                multiRenderer.addSeriesRenderer(proteinRenderer);
                multiRenderer.addSeriesRenderer(carbsRenderer);
                multiRenderer.addSeriesRenderer(fatRenderer);

                multiRenderer.setShowGrid(true);
                multiRenderer.setClickEnabled(true);
                multiRenderer.setXLabelsAngle(20);
                multiRenderer.setXLabelsColor(Color.WHITE);
                multiRenderer.setZoomButtonsVisible(false);
                // configure visible area
                multiRenderer.setXAxisMax(31);
                multiRenderer.setXAxisMin(1);
                multiRenderer.setYAxisMax(yMaxAxisValue + 30);
                multiRenderer.setAxisTitleTextSize(15);
                multiRenderer.setZoomEnabled(true);

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            graphView = ChartFactory.getLineChartView(getActivity(), dataset, multiRenderer);
                            rlRootGraphLayout.addView(graphView, 0);

                            if (isLeftIn) {
                                rightIn.setDuration(1000);
                                graphView.startAnimation(rightIn);
                            } else {
                                leftIn.setDuration(1000);
                                graphView.startAnimation(leftIn);
                            }
                        } catch (Exception edsx) {
                            edsx.printStackTrace();
                        }

                    }
                });

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

}

From source file:com.piusvelte.sonet.core.SelectFriends.java

protected void loadFriends() {
    mFriends.clear();//  w ww .ja v  a2  s  .c o m
    //      SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected});
    SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
            new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected });
    setListAdapter(sa);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() {
        @Override
        protected Boolean doInBackground(Long... params) {
            boolean loadList = false;
            SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext());
            // load the session
            Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this),
                    new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?",
                    new String[] { Long.toString(params[0]) }, null);
            if (account.moveToFirst()) {
                mToken = sonetCrypto.Decrypt(account.getString(0));
                mSecret = sonetCrypto.Decrypt(account.getString(1));
                mService = account.getInt(2);
            }
            account.close();
            String response;
            switch (mService) {
            case TWITTER:
                break;
            case FACEBOOK:
                if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(
                        String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) {
                    try {
                        JSONArray friends = new JSONObject(response).getJSONArray(Sdata);
                        for (int i = 0, l = friends.length(); i < l; i++) {
                            JSONObject f = friends.getJSONObject(i);
                            HashMap<String, String> newFriend = new HashMap<String, String>();
                            newFriend.put(Entities.ESID, f.getString(Sid));
                            newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid)));
                            newFriend.put(Entities.FRIEND, f.getString(Sname));
                            // need to alphabetize
                            if (mFriends.isEmpty())
                                mFriends.add(newFriend);
                            else {
                                String fullName = f.getString(Sname);
                                int spaceIdx = fullName.lastIndexOf(" ");
                                String newFirstName = null;
                                String newLastName = null;
                                if (spaceIdx == -1)
                                    newFirstName = fullName;
                                else {
                                    newFirstName = fullName.substring(0, spaceIdx++);
                                    newLastName = fullName.substring(spaceIdx);
                                }
                                List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>();
                                for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) {
                                    HashMap<String, String> oldFriend = mFriends.get(i2);
                                    if (newFriend == null) {
                                        newFriends.add(oldFriend);
                                    } else {
                                        fullName = oldFriend.get(Entities.FRIEND);
                                        spaceIdx = fullName.lastIndexOf(" ");
                                        String oldFirstName = null;
                                        String oldLastName = null;
                                        if (spaceIdx == -1)
                                            oldFirstName = fullName;
                                        else {
                                            oldFirstName = fullName.substring(0, spaceIdx++);
                                            oldLastName = fullName.substring(spaceIdx);
                                        }
                                        if (newFirstName == null) {
                                            newFriends.add(newFriend);
                                            newFriend = null;
                                        } else {
                                            int comparison = oldFirstName.compareToIgnoreCase(newFirstName);
                                            if (comparison == 0) {
                                                // compare firstnames
                                                if (newLastName == null) {
                                                    newFriends.add(newFriend);
                                                    newFriend = null;
                                                } else if (oldLastName != null) {
                                                    comparison = oldLastName.compareToIgnoreCase(newLastName);
                                                    if (comparison == 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    } else if (comparison > 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    }
                                                }
                                            } else if (comparison > 0) {
                                                newFriends.add(newFriend);
                                                newFriend = null;
                                            }
                                        }
                                        newFriends.add(oldFriend);
                                    }
                                }
                                if (newFriend != null)
                                    newFriends.add(newFriend);
                                mFriends = newFriends;
                            }
                        }
                        loadList = true;
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                }
                break;
            case MYSPACE:
                break;
            case LINKEDIN:
                break;
            case FOURSQUARE:
                break;
            case IDENTICA:
                break;
            case GOOGLEPLUS:
                break;
            case CHATTER:
                break;
            }
            return loadList;
        }

        @Override
        protected void onPostExecute(Boolean loadList) {
            if (loadList) {
                //               SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name});
                SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
                        new String[] { Entities.FRIEND, Entities.ESID },
                        new int[] { R.id.name, R.id.selected });
                sa.setViewBinder(mViewBinder);
                setListAdapter(sa);
            }
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }
    };
    loadingDialog.setMessage(getString(R.string.loading));
    loadingDialog.setCancelable(true);
    loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (!asyncTask.isCancelled())
                asyncTask.cancel(true);
        }
    });
    loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    loadingDialog.show();
    asyncTask.execute(mAccountId);
}

From source file:com.shafiq.myfeedle.core.SelectFriends.java

protected void loadFriends() {
    mFriends.clear();/*w  w w  .j  a v  a 2 s  .  co m*/
    //      SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected});
    SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
            new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected });
    setListAdapter(sa);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() {
        @Override
        protected Boolean doInBackground(Long... params) {
            boolean loadList = false;
            MyfeedleCrypto myfeedleCrypto = MyfeedleCrypto.getInstance(getApplicationContext());
            // load the session
            Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this),
                    new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?",
                    new String[] { Long.toString(params[0]) }, null);
            if (account.moveToFirst()) {
                mToken = myfeedleCrypto.Decrypt(account.getString(0));
                mSecret = myfeedleCrypto.Decrypt(account.getString(1));
                mService = account.getInt(2);
            }
            account.close();
            String response;
            switch (mService) {
            case TWITTER:
                break;
            case FACEBOOK:
                if ((response = MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(
                        String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) {
                    try {
                        JSONArray friends = new JSONObject(response).getJSONArray(Sdata);
                        for (int i = 0, l = friends.length(); i < l; i++) {
                            JSONObject f = friends.getJSONObject(i);
                            HashMap<String, String> newFriend = new HashMap<String, String>();
                            newFriend.put(Entities.ESID, f.getString(Sid));
                            newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid)));
                            newFriend.put(Entities.FRIEND, f.getString(Sname));
                            // need to alphabetize
                            if (mFriends.isEmpty())
                                mFriends.add(newFriend);
                            else {
                                String fullName = f.getString(Sname);
                                int spaceIdx = fullName.lastIndexOf(" ");
                                String newFirstName = null;
                                String newLastName = null;
                                if (spaceIdx == -1)
                                    newFirstName = fullName;
                                else {
                                    newFirstName = fullName.substring(0, spaceIdx++);
                                    newLastName = fullName.substring(spaceIdx);
                                }
                                List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>();
                                for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) {
                                    HashMap<String, String> oldFriend = mFriends.get(i2);
                                    if (newFriend == null) {
                                        newFriends.add(oldFriend);
                                    } else {
                                        fullName = oldFriend.get(Entities.FRIEND);
                                        spaceIdx = fullName.lastIndexOf(" ");
                                        String oldFirstName = null;
                                        String oldLastName = null;
                                        if (spaceIdx == -1)
                                            oldFirstName = fullName;
                                        else {
                                            oldFirstName = fullName.substring(0, spaceIdx++);
                                            oldLastName = fullName.substring(spaceIdx);
                                        }
                                        if (newFirstName == null) {
                                            newFriends.add(newFriend);
                                            newFriend = null;
                                        } else {
                                            int comparison = oldFirstName.compareToIgnoreCase(newFirstName);
                                            if (comparison == 0) {
                                                // compare firstnames
                                                if (newLastName == null) {
                                                    newFriends.add(newFriend);
                                                    newFriend = null;
                                                } else if (oldLastName != null) {
                                                    comparison = oldLastName.compareToIgnoreCase(newLastName);
                                                    if (comparison == 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    } else if (comparison > 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    }
                                                }
                                            } else if (comparison > 0) {
                                                newFriends.add(newFriend);
                                                newFriend = null;
                                            }
                                        }
                                        newFriends.add(oldFriend);
                                    }
                                }
                                if (newFriend != null)
                                    newFriends.add(newFriend);
                                mFriends = newFriends;
                            }
                        }
                        loadList = true;
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                }
                break;
            case MYSPACE:
                break;
            case LINKEDIN:
                break;
            case FOURSQUARE:
                break;
            case IDENTICA:
                break;
            case GOOGLEPLUS:
                break;
            case CHATTER:
                break;
            }
            return loadList;
        }

        @Override
        protected void onPostExecute(Boolean loadList) {
            if (loadList) {
                //               SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name});
                SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
                        new String[] { Entities.FRIEND, Entities.ESID },
                        new int[] { R.id.name, R.id.selected });
                sa.setViewBinder(mViewBinder);
                setListAdapter(sa);
            }
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }
    };
    loadingDialog.setMessage(getString(R.string.loading));
    loadingDialog.setCancelable(true);
    loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (!asyncTask.isCancelled())
                asyncTask.cancel(true);
        }
    });
    loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    loadingDialog.show();
    asyncTask.execute(mAccountId);
}

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

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("CacheSettings", R.string.CacheSettings));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override/*  w  w w  .jav  a2  s. c om*/
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            }
        }
    });

    listAdapter = new ListAdapter(context);

    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background));

    ListView listView = new ListView(context);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setVerticalScrollBarEnabled(false);
    listView.setDrawSelectorOnTop(true);
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> adapterView, View view, final int i, long l) {
            if (getParentActivity() == null) {
                return;
            }
            if (i == keepMediaRow) {
                BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                builder.setItems(
                        new CharSequence[] { LocaleController.formatPluralString("Weeks", 1),
                                LocaleController.formatPluralString("Months", 1),
                                LocaleController.getString("KeepMediaForever", R.string.KeepMediaForever) },
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, final int which) {
                                SharedPreferences.Editor editor = ApplicationLoader.applicationContext
                                        .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit();
                                editor.putInt("keep_media", which).commit();
                                if (listAdapter != null) {
                                    listAdapter.notifyDataSetChanged();
                                }
                                PendingIntent pintent = PendingIntent.getService(
                                        ApplicationLoader.applicationContext, 0,
                                        new Intent(ApplicationLoader.applicationContext,
                                                ClearCacheService.class),
                                        0);
                                AlarmManager alarmManager = (AlarmManager) ApplicationLoader.applicationContext
                                        .getSystemService(Context.ALARM_SERVICE);
                                if (which == 2) {
                                    alarmManager.cancel(pintent);
                                } else {
                                    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                                            AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pintent);
                                }
                            }
                        });
                showDialog(builder.create());
            } else if (i == databaseRow) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                builder.setMessage(
                        LocaleController.getString("LocalDatabaseClear", R.string.LocalDatabaseClear));
                builder.setPositiveButton(LocaleController.getString("CacheClear", R.string.CacheClear),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                final ProgressDialog progressDialog = new ProgressDialog(getParentActivity());
                                progressDialog
                                        .setMessage(LocaleController.getString("Loading", R.string.Loading));
                                progressDialog.setCanceledOnTouchOutside(false);
                                progressDialog.setCancelable(false);
                                progressDialog.show();
                                MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            SQLiteDatabase database = MessagesStorage.getInstance()
                                                    .getDatabase();
                                            ArrayList<Long> dialogsToCleanup = new ArrayList<>();
                                            SQLiteCursor cursor = database
                                                    .queryFinalized("SELECT did FROM dialogs WHERE 1");
                                            StringBuilder ids = new StringBuilder();
                                            while (cursor.next()) {
                                                long did = cursor.longValue(0);
                                                int lower_id = (int) did;
                                                int high_id = (int) (did >> 32);
                                                if (lower_id != 0 && high_id != 1) {
                                                    dialogsToCleanup.add(did);
                                                }
                                            }
                                            cursor.dispose();

                                            SQLitePreparedStatement state5 = database
                                                    .executeFast("REPLACE INTO messages_holes VALUES(?, ?, ?)");
                                            SQLitePreparedStatement state6 = database.executeFast(
                                                    "REPLACE INTO media_holes_v2 VALUES(?, ?, ?, ?)");

                                            database.beginTransaction();
                                            for (int a = 0; a < dialogsToCleanup.size(); a++) {
                                                Long did = dialogsToCleanup.get(a);
                                                int messagesCount = 0;
                                                cursor = database.queryFinalized(
                                                        "SELECT COUNT(mid) FROM messages WHERE uid = " + did);
                                                if (cursor.next()) {
                                                    messagesCount = cursor.intValue(0);
                                                }
                                                cursor.dispose();
                                                if (messagesCount <= 2) {
                                                    continue;
                                                }

                                                cursor = database.queryFinalized(
                                                        "SELECT last_mid_i, last_mid FROM dialogs WHERE did = "
                                                                + did);
                                                int messageId = -1;
                                                if (cursor.next()) {
                                                    long last_mid_i = cursor.longValue(0);
                                                    long last_mid = cursor.longValue(1);
                                                    SQLiteCursor cursor2 = database.queryFinalized(
                                                            "SELECT data FROM messages WHERE uid = " + did
                                                                    + " AND mid IN (" + last_mid_i + ","
                                                                    + last_mid + ")");
                                                    try {
                                                        while (cursor2.next()) {
                                                            NativeByteBuffer data = cursor2.byteBufferValue(0);
                                                            if (data != null) {
                                                                TLRPC.Message message = TLRPC.Message
                                                                        .TLdeserialize(data,
                                                                                data.readInt32(false), false);
                                                                data.reuse();
                                                                if (message != null) {
                                                                    messageId = message.id;
                                                                }
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        FileLog.e("tmessages", e);
                                                    }
                                                    cursor2.dispose();

                                                    database.executeFast("DELETE FROM messages WHERE uid = "
                                                            + did + " AND mid != " + last_mid_i + " AND mid != "
                                                            + last_mid).stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM messages_holes WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM bot_keyboard WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_counts_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_holes_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    BotQuery.clearBotKeyboard(did, null);
                                                    if (messageId != -1) {
                                                        MessagesStorage.createFirstHoles(did, state5, state6,
                                                                messageId);
                                                    }
                                                }
                                                cursor.dispose();
                                            }
                                            state5.dispose();
                                            state6.dispose();
                                            database.commitTransaction();
                                            database.executeFast("VACUUM").stepThis().dispose();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        } finally {
                                            AndroidUtilities.runOnUIThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        progressDialog.dismiss();
                                                    } catch (Exception e) {
                                                        FileLog.e("tmessages", e);
                                                    }
                                                    if (listAdapter != null) {
                                                        File file = new File(
                                                                ApplicationLoader.getFilesDirFixed(),
                                                                "cache4.db");
                                                        databaseSize = file.length();
                                                        listAdapter.notifyDataSetChanged();
                                                    }
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        });
                showDialog(builder.create());
            } else if (i == cacheRow) {
                if (totalSize <= 0 || getParentActivity() == null) {
                    return;
                }
                BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                builder.setApplyTopPadding(false);
                builder.setApplyBottomPadding(false);
                LinearLayout linearLayout = new LinearLayout(getParentActivity());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                for (int a = 0; a < 6; a++) {
                    long size = 0;
                    String name = null;
                    if (a == 0) {
                        size = photoSize;
                        name = LocaleController.getString("LocalPhotoCache", R.string.LocalPhotoCache);
                    } else if (a == 1) {
                        size = videoSize;
                        name = LocaleController.getString("LocalVideoCache", R.string.LocalVideoCache);
                    } else if (a == 2) {
                        size = documentsSize;
                        name = LocaleController.getString("LocalDocumentCache", R.string.LocalDocumentCache);
                    } else if (a == 3) {
                        size = musicSize;
                        name = LocaleController.getString("LocalMusicCache", R.string.LocalMusicCache);
                    } else if (a == 4) {
                        size = audioSize;
                        name = LocaleController.getString("LocalAudioCache", R.string.LocalAudioCache);
                    } else if (a == 5) {
                        size = cacheSize;
                        name = LocaleController.getString("LocalCache", R.string.LocalCache);
                    }
                    if (size > 0) {
                        clear[a] = true;
                        CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity());
                        checkBoxCell.setTag(a);
                        checkBoxCell.setBackgroundResource(R.drawable.list_selector);
                        linearLayout.addView(checkBoxCell,
                                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
                        checkBoxCell.setText(name, AndroidUtilities.formatFileSize(size), true, true);
                        checkBoxCell.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                CheckBoxCell cell = (CheckBoxCell) v;
                                int num = (Integer) cell.getTag();
                                clear[num] = !clear[num];
                                cell.setChecked(clear[num], true);
                            }
                        });
                    } else {
                        clear[a] = false;
                    }
                }
                BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1);
                cell.setBackgroundResource(R.drawable.list_selector);
                cell.setTextAndIcon(
                        LocaleController.getString("ClearMediaCache", R.string.ClearMediaCache).toUpperCase(),
                        0);
                cell.setTextColor(Theme.STICKERS_SHEET_REMOVE_TEXT_COLOR);
                cell.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            if (visibleDialog != null) {
                                visibleDialog.dismiss();
                            }
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                        cleanupFolders();
                    }
                });
                linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
                builder.setCustomView(linearLayout);
                showDialog(builder.create());
            }
        }
    });

    return fragmentView;
}

From source file:net.gerosyab.dailylog.activity.MainActivity.java

private void importCategory() {
    DialogProperties properties = new DialogProperties();
    properties.selection_mode = DialogConfigs.SINGLE_MODE;
    properties.selection_type = DialogConfigs.FILE_SELECT;
    properties.root = new File(DialogConfigs.DEFAULT_DIR);
    properties.extensions = null;//from   w w w .j a v a 2 s  .  c o  m

    dialog = new FilePickerDialog(MainActivity.this, properties);

    dialog.setDialogSelectionListener(new DialogSelectionListener() {
        @Override
        public void onSelectedFilePaths(String[] files) {

            ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setTitle("Importing data [" + files[0] + "]");
            progressDialog.show();

            //files is the array of the paths of files selected by the Application User.
            try {
                String newCategoryUUID = UUID.randomUUID().toString();
                //                    CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(files[0]), "UTF-8"), '\t');
                CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(files[0]), "UTF-8"),
                        ',');
                String[] nextLine;
                long lineNum = 0;

                boolean dbVersionCheck = false, categoryNameCheck = false, categoryUnitCheck = false;
                boolean categoryTypeCheck = false, defaultValueCheck = false, headerCheck = false;
                boolean isCategoryNameExists = false, rowDataCheck = false, dataCheck = false;
                String dbVersion = null, categoryName = null, categoryUnit = null;
                long categoryType = -1, defaultValue = -1;

                //                    Category category = null;
                List<Record> records = new ArrayList<Record>();

                while ((nextLine = reader.readNext()) != null) {
                    // nextLine[] is an array of values from the line
                    String temp2 = "";
                    for (int i = 0; i < nextLine.length; i++) {
                        temp2 += nextLine[i] + ", ";
                    }
                    MyLog.d("opencsv", temp2);

                    if (lineNum == 0) {
                        //header
                        MyLog.d("opencsv", "nextLine.length : " + nextLine.length);
                        for (int i = 0; i < nextLine.length; i++) {
                            String[] split2 = nextLine[i].split(":");
                            MyLog.d("opencsv", "split2.length : " + split2.length);
                            MyLog.d("opencsv", "split2[0] : " + split2[0]);
                            if (split2[0].replaceAll("\\s+", "").equals("Version")) {
                                if (split2[1] != null && !split2[1].equals("")) {
                                    dbVersion = split2[1];
                                    dbVersionCheck = true;
                                }
                            } else if (split2[0].replaceAll("\\s+", "").equals("Name")) {
                                if (split2[1] != null && !split2[1].equals("")) {
                                    categoryName = split2[1];
                                    if (categoryName.length() <= Category.getMaxCategoryNameLength()) {
                                        categoryNameCheck = true;
                                    }
                                }
                            } else if (split2[0].replaceAll("\\s+", "").equals("Unit")) {
                                if (split2.length == 1) {
                                    categoryUnitCheck = true;
                                } else if (split2[1] != null && !split2[1].equals("")) {
                                    categoryUnit = split2[1];
                                    categoryUnitCheck = true;
                                }
                            } else if (split2[0].replaceAll("\\s+", "").equals("Type")) {
                                if (split2[1] != null && !split2[1].equals("")) {
                                    if (split2[1].equals("0") || split2[1].equals("1")
                                            || split2[1].equals("2")) {
                                        categoryType = Long.parseLong(split2[1]);
                                        categoryTypeCheck = true;
                                    }
                                }
                            } else if (split2[0].replaceAll("\\s+", "").equals("DefaultValue")) {
                                if (split2.length == 1) {
                                    defaultValueCheck = true;
                                } else if (split2[1] != null && !split2[1].equals("")) {
                                    if (NumberUtils.isDigits(split2[1]) && NumberUtils.isNumber(split2[1])) {
                                        defaultValue = Long.parseLong(split2[1]);
                                        MyLog.d("opencsv", "split2[1] : " + split2[1]);
                                        if (defaultValue >= 0) {
                                            defaultValueCheck = true;
                                        }
                                    }
                                }
                            }
                        }

                        if (dbVersionCheck && categoryNameCheck && categoryTypeCheck) {
                            if (categoryType == 1) {
                                //number
                                if (categoryUnitCheck && defaultValueCheck) {
                                    headerCheck = true;
                                }
                            } else {
                                //boolean, string
                                headerCheck = true;
                            }
                        }

                        if (!headerCheck) {
                            break; //header parsing, data checking failed
                        } else if (Category.isCategoryNameExists(realm, categoryName)) {
                            isCategoryNameExists = true;
                            break;
                        } else {
                            //                                category = new Category(categoryName, categoryUnit, Category.getLastOrderNum(realm), categoryType);
                        }
                    } else {
                        //data
                        Record record;
                        rowDataCheck = true;
                        if (nextLine.length != 2) {
                            rowDataCheck = false;
                            break;
                        } else {
                            record = new Record();
                            record.setRecordType(categoryType);
                            DateTime dateTime = StaticData.fmtForBackup.parseDateTime(nextLine[0]);
                            if (dateTime != null) {
                                record.setDate(new java.sql.Date(dateTime.toDate().getTime()));
                            } else {
                                rowDataCheck = false;
                                break;
                            }

                            if (categoryType == StaticData.RECORD_TYPE_BOOLEAN) {
                                if (nextLine[1].equals("true")) {
                                    record.setBool(true);
                                } else {
                                    rowDataCheck = false;
                                    break;
                                }
                            } else if (categoryType == StaticData.RECORD_TYPE_NUMBER) {
                                if (NumberUtils.isNumber(nextLine[1]) && NumberUtils.isDigits(nextLine[1])) {
                                    long value = Long.parseLong(nextLine[1]);
                                    if (value > Category.getMaxValue()) {
                                        rowDataCheck = false;
                                        break;
                                    } else {
                                        record.setNumber(value);
                                    }
                                } else {
                                    dataCheck = false;
                                    break;
                                }

                            } else if (categoryType == StaticData.RECORD_TYPE_MEMO) {
                                String value = nextLine[1];
                                if (value.length() > Category.getMaxMemoLength()) {
                                    rowDataCheck = false;
                                    break;
                                } else {
                                    record.setString(nextLine[1]);
                                }
                            }
                        }
                        if (record != null && rowDataCheck == true) {
                            record.setCategoryId(newCategoryUUID);
                            record.setRecordId(UUID.randomUUID().toString());
                            records.add(record);
                        }
                    }
                    lineNum++;
                }

                if (!headerCheck) {
                    Toast.makeText(context, "Data file's header context/value is not correct",
                            Toast.LENGTH_LONG).show();
                } else if (isCategoryNameExists) {
                    Toast.makeText(context, "Category Name [" + categoryName + "] is already exists",
                            Toast.LENGTH_LONG).show();
                } else if (!rowDataCheck) {
                    Toast.makeText(context, "Data file's record data is not correct", Toast.LENGTH_LONG).show();
                } else {
                    long newOrder = Category.getNewOrderNum(realm);
                    realm.beginTransaction();
                    Category category = realm.createObject(Category.class, newCategoryUUID);
                    category.setName(categoryName);
                    category.setUnit(categoryUnit);
                    category.setOrder(newOrder);
                    category.setRecordType(categoryType);
                    realm.insert(category);
                    realm.insertOrUpdate(records);
                    realm.commitTransaction();
                    Toast.makeText(context, "Data import [ " + categoryName + " ] is completed!!",
                            Toast.LENGTH_LONG).show();
                    //                        refreshList();
                    //                        categoryHolderList.add(getHolderFromCategory(category));
                    //                        mDragListView.getAdapter().notifyDataSetChanged();
                    //                        mDragListView.getAdapter().notifyItemInserted((int) newOrder);
                    //                        setCategoryHolderList();
                    //                        mDragListView.getAdapter().setItemList(categoryHolderList);
                    adapter.notifyDataSetChanged();
                }
            } catch (FileNotFoundException e) {
                Toast.makeText(context, "Selected file is not found", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            } catch (IOException e) {
                Toast.makeText(context, "File I/O exception occured", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            } finally {
                progressDialog.dismiss();
            }
        }
    });

    dialog.show();
}

From source file:com.piusvelte.sonet.core.SonetComments.java

@Override
public void onClick(View v) {
    if (v == mSend) {
        if ((mMessage.getText().toString() != null) && (mMessage.getText().toString().length() > 0)
                && (mSid != null) && (mEsid != null)) {
            mMessage.setEnabled(false);// w  w  w  .j  a  va  2  s. c  om
            mSend.setEnabled(false);
            // post or comment!
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() {
                @Override
                protected String doInBackground(Void... arg0) {
                    List<NameValuePair> params;
                    String message;
                    String response = null;
                    HttpPost httpPost;
                    SonetOAuth sonetOAuth;
                    String serviceName = Sonet.getServiceName(getResources(), mService);
                    publishProgress(serviceName);
                    switch (mService) {
                    case TWITTER:
                        // limit tweets to 140, breaking up the message if necessary
                        sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, mToken, mSecret);
                        message = mMessage.getText().toString();
                        while (message.length() > 0) {
                            final String send;
                            if (message.length() > 140) {
                                // need to break on a word
                                int end = 0;
                                int nextSpace = 0;
                                for (int i = 0, i2 = message.length(); i < i2; i++) {
                                    end = nextSpace;
                                    if (message.substring(i, i + 1).equals(" ")) {
                                        nextSpace = i;
                                    }
                                }
                                // in case there are no spaces, just break on 140
                                if (end == 0) {
                                    end = 140;
                                }
                                send = message.substring(0, end);
                                message = message.substring(end + 1);
                            } else {
                                send = message;
                                message = "";
                            }
                            httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL));
                            // resolve Error 417 Expectation by Twitter
                            httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                            params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair(Sstatus, send));
                            params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid));
                            try {
                                httpPost.setEntity(new UrlEncodedFormEntity(params));
                                response = SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        break;
                    case FACEBOOK:
                        httpPost = new HttpPost(String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid,
                                Saccess_token, mToken));
                        params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                        try {
                            httpPost.setEntity(new UrlEncodedFormEntity(params));
                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case MYSPACE:
                        sonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET, mToken, mSecret);
                        try {
                            httpPost = new HttpPost(String.format(MYSPACE_URL_STATUSMOODCOMMENTS,
                                    MYSPACE_BASE_URL, mEsid, mSid));
                            httpPost.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOODCOMMENTS_BODY,
                                    mMessage.getText().toString())));
                            response = SonetHttpClient.httpResponse(mHttpClient,
                                    sonetOAuth.getSignedRequest(httpPost));
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case FOURSQUARE:
                        try {
                            message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                            httpPost = new HttpPost(String.format(FOURSQUARE_ADDCOMMENT, FOURSQUARE_BASE_URL,
                                    mSid, message, mToken));
                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case LINKEDIN:
                        sonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, mToken, mSecret);
                        try {
                            httpPost = new HttpPost(
                                    String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid));
                            httpPost.setEntity(new StringEntity(
                                    String.format(LINKEDIN_COMMENT_BODY, mMessage.getText().toString())));
                            httpPost.addHeader(new BasicHeader("Content-Type", "application/xml"));
                            response = SonetHttpClient.httpResponse(mHttpClient,
                                    sonetOAuth.getSignedRequest(httpPost));
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case IDENTICA:
                        // limit tweets to 140, breaking up the message if necessary
                        sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET, mToken, mSecret);
                        message = mMessage.getText().toString();
                        while (message.length() > 0) {
                            final String send;
                            if (message.length() > 140) {
                                // need to break on a word
                                int end = 0;
                                int nextSpace = 0;
                                for (int i = 0, i2 = message.length(); i < i2; i++) {
                                    end = nextSpace;
                                    if (message.substring(i, i + 1).equals(" ")) {
                                        nextSpace = i;
                                    }
                                }
                                // in case there are no spaces, just break on 140
                                if (end == 0) {
                                    end = 140;
                                }
                                send = message.substring(0, end);
                                message = message.substring(end + 1);
                            } else {
                                send = message;
                                message = "";
                            }
                            httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL));
                            // resolve Error 417 Expectation by Twitter
                            httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                            params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair(Sstatus, send));
                            params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid));
                            try {
                                httpPost.setEntity(new UrlEncodedFormEntity(params));
                                response = SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        break;
                    case GOOGLEPLUS:
                        break;
                    case CHATTER:
                        httpPost = new HttpPost(String.format(CHATTER_URL_COMMENT, mChatterInstance, mSid,
                                Uri.encode(mMessage.getText().toString())));
                        httpPost.setHeader("Authorization", "OAuth " + mChatterToken);
                        response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        break;
                    }
                    return ((response == null) && (mService == MYSPACE)) ? null
                            : serviceName + " "
                                    + getString(response != null ? R.string.success : R.string.failure);
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                }

                @Override
                protected void onPostExecute(String result) {
                    if (result != null) {
                        (Toast.makeText(SonetComments.this, result, Toast.LENGTH_LONG)).show();
                    } else if (mService == MYSPACE) {
                        // myspace permissions
                        (Toast.makeText(SonetComments.this,
                                SonetComments.this.getResources()
                                        .getStringArray(R.array.service_entries)[MYSPACE]
                                        + getString(R.string.failure) + " "
                                        + getString(R.string.myspace_permissions_message),
                                Toast.LENGTH_LONG)).show();
                    }
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    finish();
                }

            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            loadingDialog.show();
            asyncTask.execute();
        } else {
            (Toast.makeText(SonetComments.this, "error parsing message body", Toast.LENGTH_LONG)).show();
            mMessage.setEnabled(true);
            mSend.setEnabled(true);
        }
    }
}