Example usage for android.app ProgressDialog setCancelable

List of usage examples for android.app ProgressDialog setCancelable

Introduction

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

Prototype

public void setCancelable(boolean flag) 

Source Link

Document

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

Usage

From source file:com.juick.android.MainActivity.java

private void obtainSavedMessagesURL(final boolean reset) {
    final ProgressDialog pd = new ProgressDialog(MainActivity.this);
    pd.setIndeterminate(true);//from ww  w  . j  a v  a  2  s .  c om
    pd.setTitle("Saved Messages");
    pd.setMessage("Waiting for server key");
    pd.setCancelable(true);
    pd.show();
    new Thread("obtainSavedMessagesURL") {
        @Override
        public void run() {

            final RESTResponse restResponse = DatabaseService.obtainSharingURL(MainActivity.this, reset);

            if (restResponse.getErrorText() == null)
                try {
                    new JSONObject(restResponse.getResult());
                } catch (JSONException e) {
                    restResponse.errorText = e.toString();
                }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pd.cancel();
                    if (restResponse.getErrorText() != null) {
                        Toast.makeText(MainActivity.this, restResponse.getErrorText(), Toast.LENGTH_LONG)
                                .show();
                    } else {
                        try {
                            final String url = (String) new JSONObject(restResponse.getResult()).get("url");
                            if (url.length() == 0) {
                                Toast.makeText(MainActivity.this,
                                        "You don't have key yet. Choose another option.", Toast.LENGTH_LONG)
                                        .show();
                            } else {
                                new AlertDialog.Builder(MainActivity.this).setTitle("You got key!")
                                        .setMessage(url)
                                        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        }).setNeutralButton("Share with..",
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        Intent share = new Intent(
                                                                android.content.Intent.ACTION_SEND);
                                                        share.setType("text/plain");
                                                        share.addFlags(
                                                                Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

                                                        share.putExtra(Intent.EXTRA_SUBJECT,
                                                                "My Saved messages on Juick Advanced");
                                                        share.putExtra(Intent.EXTRA_TEXT, url);

                                                        startActivity(
                                                                Intent.createChooser(share, "Share link"));
                                                    }
                                                })
                                        .setCancelable(true).show();
                            }
                        } catch (JSONException e) {
                            Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
        }
    }.start();

}

From source file:com.juick.android.UserCenterActivity.java

private void enableJAM(final Runnable then) {
    if (!MainActivity.isJAMServiceRunning(UserCenterActivity.this)) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);/*from ww  w  .  j  a v  a 2s. co m*/
        builder.setMessage(R.string.JAMNotEnabledEnable);
        builder.setTitle(getString(R.string.JuickAdvancedFunctionality));
        builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(UserCenterActivity.this);
                sp.edit().putBoolean("enableJAMessaging", true).commit();
                MainActivity.toggleJAMessaging(UserCenterActivity.this, true);
                final ProgressDialog pd = new ProgressDialog(UserCenterActivity.this);
                dialog.cancel();
                pd.setIndeterminate(true);
                pd.setMessage(getString(R.string.WaitingForService));
                final Thread thread = new Thread() {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                JAMService instance = JAMService.instance;
                                if (instance != null) {
                                    JAXMPPClient client = instance.client;
                                    if (client != null && client.loggedIn) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                pd.cancel();
                                                then.run();
                                            }
                                        });
                                    }
                                }
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                break;
                            }
                        }
                        super.run(); //To change body of overridden methods use File | Settings | File Templates.
                    }
                };
                thread.start();
                pd.setCancelable(true);
                pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        thread.interrupt();
                    }
                });
                pd.show();
            }
        });
        builder.setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    } else {
        then.run();
    }
    return;
}

From source file:nf.frex.android.FrexActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
        return;/*from  ww  w. ja  va 2s .c  o m*/
    }
    if (requestCode == R.id.manage_fractals && data.getAction().equals(Intent.ACTION_VIEW)) {
        final Uri imageUri = data.getData();
        if (imageUri != null) {
            File imageFile = new File(imageUri.getPath());
            String configName = FrexIO.getFilenameWithoutExt(imageFile);
            File paramFile = new File(imageFile.getParent(), configName + FrexIO.PARAM_FILE_EXT);
            try {
                FileInputStream fis = new FileInputStream(paramFile);
                try {
                    readFrexDoc(fis, configName);
                } finally {
                    fis.close();
                }
            } catch (IOException e) {
                Toast.makeText(FrexActivity.this, getString(R.string.error_msg, e.getLocalizedMessage()),
                        Toast.LENGTH_SHORT).show();
            }
        }
    } else if (requestCode == R.id.settings) {
        view.getGenerator().setNumTasks(SettingsActivity.getNumTasks(this));
    } else if (requestCode == SELECT_PICTURE_REQUEST_CODE) {
        final Uri imageUri = data.getData();
        final ColorQuantizer colorQuantizer = new ColorQuantizer();
        final ProgressDialog progressDialog = new ProgressDialog(FrexActivity.this);
        final DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                colorQuantizer.cancel();
            }
        };
        final ColorQuantizer.ProgressListener progressListener = new ColorQuantizer.ProgressListener() {
            @Override
            public void progress(final String msg, final int iter, final int maxIter) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.setMessage(msg);
                        progressDialog.setProgress(iter);
                    }
                });
            }
        };

        progressDialog.setTitle(getString(R.string.get_pal_from_img_title));
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(true);
        progressDialog.setOnCancelListener(cancelListener);
        progressDialog.setMax(colorQuantizer.getMaxIterCount());
        progressDialog.show();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap;
                try {
                    bitmap = FrexIO.readBitmap(getContentResolver(), imageUri, 256);
                } catch (IOException e) {
                    alert("I/O error: " + e.getLocalizedMessage());
                    return;
                }
                ColorScheme colorScheme = colorQuantizer.quantize(bitmap, progressListener);
                progressDialog.dismiss();
                if (colorScheme != null) {
                    Log.d(TAG, "SELECT_PICTURE_REQUEST_CODE: Got colorScheme");
                    String colorSchemeId = "$" + imageUri.toString();
                    colorSchemes.add(colorSchemeId, colorScheme);
                    view.setColorSchemeId(colorSchemeId);
                    view.setColorScheme(colorScheme);
                    view.recomputeColors();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, "SELECT_PICTURE_REQUEST_CODE: showDialog(R.id.colors)");
                            showDialog(R.id.colors);
                        }
                    });

                }
            }
        });
        thread.start();
    }
}

From source file:ac.robinson.mediaphone.MediaPhoneActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case R.id.dialog_importing_in_progress:
        ProgressDialog importDialog = new ProgressDialog(MediaPhoneActivity.this);
        importDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        importDialog.setMessage(getString(R.string.import_progress));
        importDialog.setCancelable(false);
        mImportFramesProgressDialog = importDialog;
        mImportFramesDialogShown = true;
        return importDialog;
    case R.id.dialog_export_narrative_in_progress:
        ProgressDialog exportDialog = new ProgressDialog(MediaPhoneActivity.this);
        exportDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        exportDialog.setMessage(getString(R.string.background_task_progress));
        exportDialog.setCancelable(false);
        exportDialog.setIndeterminate(true);
        mExportNarrativeDialogShown = true;
        return exportDialog;
    case R.id.dialog_mov_creator_in_progress:
        ProgressDialog movDialog = new ProgressDialog(MediaPhoneActivity.this);
        movDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        movDialog.setMessage(getString(R.string.mov_export_task_progress));
        movDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.mov_export_run_in_background),
                new DialogInterface.OnClickListener() {
                    @Override//w w  w  .ja  va 2  s .  c o  m
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        mExportVideoDialogShown = false;
                    }
                });
        movDialog.setCancelable(false);
        movDialog.setIndeterminate(true);
        mExportVideoDialogShown = true;
        return movDialog;
    case R.id.dialog_background_runner_in_progress:
        ProgressDialog runnerDialog = new ProgressDialog(MediaPhoneActivity.this);
        runnerDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        runnerDialog.setMessage(getString(R.string.background_task_progress));
        runnerDialog.setCancelable(false);
        runnerDialog.setIndeterminate(true);
        mBackgroundRunnerDialogShown = true;
        return runnerDialog;
    default:
        return super.onCreateDialog(id);
    }
}

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

protected void getPhoto(Uri uri) {
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Uri, Void, String> asyncTask = new AsyncTask<Uri, Void, String>() {
        @Override/* w w  w .j a  v a 2 s.  co  m*/
        protected String doInBackground(Uri... imgUri) {
            String[] projection = new String[] { MediaStore.Images.Media.DATA };
            String path = null;
            Cursor c = getContentResolver().query(imgUri[0], projection, null, null, null);
            if ((c != null) && c.moveToFirst()) {
                path = c.getString(c.getColumnIndex(projection[0]));
            } else {
                // some file manages send the path through the uri
                path = imgUri[0].getPath();
            }
            c.close();
            return path;
        }

        @Override
        protected void onPostExecute(String path) {
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
            if (path != null)
                setPhoto(path);
            else
                (Toast.makeText(SonetCreatePost.this, "error retrieving the photo path", Toast.LENGTH_LONG))
                        .show();
        }
    };
    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(uri);
}

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

protected void getPhoto(Uri uri) {
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Uri, Void, String> asyncTask = new AsyncTask<Uri, Void, String>() {
        @Override// w w w .  j a v a 2s. c o  m
        protected String doInBackground(Uri... imgUri) {
            String[] projection = new String[] { MediaStore.Images.Media.DATA };
            String path = null;
            Cursor c = getContentResolver().query(imgUri[0], projection, null, null, null);
            if ((c != null) && c.moveToFirst()) {
                path = c.getString(c.getColumnIndex(projection[0]));
            } else {
                // some file manages send the path through the uri
                path = imgUri[0].getPath();
            }
            c.close();
            return path;
        }

        @Override
        protected void onPostExecute(String path) {
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
            if (path != null)
                setPhoto(path);
            else
                (Toast.makeText(MyfeedleCreatePost.this, "error retrieving the photo path", Toast.LENGTH_LONG))
                        .show();
        }
    };
    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(uri);
}

From source file:com.juick.android.MainActivity.java

public void updateNavigation() {
    navigationItems = new ArrayList<NavigationItem>();

    List<MicroBlog> blogs = new ArrayList<MicroBlog>(microBlogs.values());
    Collections.<MicroBlog>sort(blogs, new Comparator<MicroBlog>() {
        @Override//w  ww.j  a v  a 2s  . com
        public int compare(MicroBlog microBlog, MicroBlog microBlog2) {
            return microBlog.getPiority() - microBlog2.getPiority();
        }
    });
    for (MicroBlog blog : blogs) {
        blog.addNavigationSources(navigationItems, this);
    }
    navigationItems.add(new NavigationItem(NAVITEM_UNREAD, R.string.navigationUnread,
            R.drawable.navicon_juickadvanced, "msrcUnread") {
        @Override
        public void action() {
            final NavigationItem thisNi = this;
            final ProgressDialog pd = new ProgressDialog(MainActivity.this);
            pd.setIndeterminate(true);
            pd.setTitle(R.string.navigationUnread);
            pd.setCancelable(true);
            pd.show();
            UnreadSegmentsView.loadPeriods(MainActivity.this,
                    new Utils.Function<Void, ArrayList<DatabaseService.Period>>() {
                        @Override
                        public Void apply(ArrayList<DatabaseService.Period> periods) {
                            if (pd.isShowing()) {
                                pd.cancel();
                                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                final AlertDialog alerDialog;
                                if (periods.size() == 0) {
                                    alerDialog = builder.setTitle(getString(R.string.UnreadSegments))
                                            .setMessage(getString(R.string.YouHaveNotEnabledForUnreadSegments))
                                            .setCancelable(true)
                                            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                    dialogInterface.dismiss();
                                                    restoreLastNavigationPosition();
                                                }
                                            }).create();
                                } else {
                                    UnreadSegmentsView unreadSegmentsView = new UnreadSegmentsView(
                                            MainActivity.this, periods);
                                    final int myIndex = navigationItems.indexOf(thisNi);
                                    alerDialog = builder.setTitle(getString(R.string.ChooseUnreadSegment))
                                            .setView(unreadSegmentsView).setCancelable(true)
                                            .setNegativeButton(android.R.string.cancel,
                                                    new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialogInterface,
                                                                int i) {
                                                            dialogInterface.dismiss();
                                                            restoreLastNavigationPosition();
                                                        }
                                                    })
                                            .create();
                                    unreadSegmentsView.setListener(new UnreadSegmentsView.PeriodListener() {
                                        @Override
                                        public void onPeriodClicked(DatabaseService.Period period) {
                                            alerDialog.dismiss();
                                            int beforeMid = period.beforeMid;
                                            Bundle args = new Bundle();
                                            args.putSerializable("messagesSource",
                                                    new UnreadSegmentMessagesSource(
                                                            getString(R.string.navigationUnread),
                                                            MainActivity.this, period));
                                            if (getSelectedNavigationIndex() != myIndex) {
                                                setSelectedNavigationItem(myIndex);
                                            }
                                            runDefaultFragmentWithBundle(args, thisNi);
                                        }
                                    });
                                }
                                alerDialog.show();
                                restyleChildrenOrWidget(alerDialog.getWindow().getDecorView());
                            }
                            return null;
                        }
                    });
            return;
        }
    });
    navigationItems.add(new NavigationItem(NAVITEM_SAVED, R.string.navigationSaved,
            R.drawable.navicon_juickadvanced, "msrcSaved") {
        @Override
        public void action() {
            final Bundle args = new Bundle();
            args.putSerializable("messagesSource", new SavedMessagesSource(MainActivity.this));
            runDefaultFragmentWithBundle(args, this);
        }
    });
    navigationItems.add(new NavigationItem(NAVITEM_RECENT_READ, R.string.navigationRecentlyOpened,
            R.drawable.navicon_juickadvanced, "msrcRecentOpen") {
        @Override
        public void action() {
            final Bundle args = new Bundle();
            args.putSerializable("messagesSource", new RecentlyOpenedMessagesSource(MainActivity.this));
            runDefaultFragmentWithBundle(args, this);
        }
    });
    navigationItems.add(new NavigationItem(NAVITEM_RECENT_WRITE, R.string.navigationRecentlyCommented,
            R.drawable.navicon_juickadvanced, "msrcRecentComment") {
        @Override
        public void action() {
            final Bundle args = new Bundle();
            args.putSerializable("messagesSource", new RecentlyCommentedMessagesSource(MainActivity.this));
            runDefaultFragmentWithBundle(args, this);
        }
    });
    navigationItems.add(new NavigationItem(NAVITEM_ALL_COMBINED, R.string.navigationAllCombined,
            R.drawable.navicon_juickadvanced, "msrcAllCombined") {
        @Override
        public void action() {
            final Bundle args = new Bundle();
            args.putSerializable("messagesSource",
                    new CombinedAllMessagesSource(MainActivity.this, "combined_all"));
            runDefaultFragmentWithBundle(args, this);
        }

        @Override
        public ArrayList<String> getMenuItems() {
            String s = getString(R.string.SelectSources);
            ArrayList<String> strings = new ArrayList<String>();
            strings.add(s);
            return strings;
        }

        @Override
        public void handleMenuAction(int which, String value) {
            switch (which) {
            case 0:
                selectSourcesForAllCombined();
                break;
            }
        }
    });
    navigationItems.add(new NavigationItem(NAVITEM_SUBS_COMBINED, R.string.navigationSubsCombined,
            R.drawable.navicon_juickadvanced, "msrcSubsCombined") {
        @Override
        public void action() {
            final NavigationItem thiz = this;
            new Thread("MessageSource Initializer") {
                @Override
                public void run() {
                    final Bundle args = new Bundle();
                    args.putSerializable("messagesSource",
                            new CombinedSubscriptionMessagesSource(MainActivity.this));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            runDefaultFragmentWithBundle(args, thiz);
                        }

                    });
                }
            }.start();
            final Bundle args = new Bundle();
            runDefaultFragmentWithBundle(args, this);
        }

        @Override
        public ArrayList<String> getMenuItems() {
            String s = getString(R.string.SelectSources);
            ArrayList<String> strings = new ArrayList<String>();
            strings.add(s);
            return strings;
        }

        @Override
        public void handleMenuAction(int which, String value) {
            switch (which) {
            case 0:
                selectSourcesForAllSubs();
                break;
            }
        }
    });
    int index = 10000;
    final SharedPreferences sp_order = getSharedPreferences("messages_source_ordering", MODE_PRIVATE);
    for (NavigationItem navigationItem : navigationItems) {
        navigationItem.itemOrder = sp_order.getInt("order_" + navigationItem.id, -1);
        if (navigationItem.itemOrder == -1) {
            navigationItem.itemOrder = index;
            sp_order.edit().putInt("order_" + navigationItem.id, navigationItem.itemOrder).commit();
        }
        index++;
    }
    Collections.sort(navigationItems, new Comparator<NavigationItem>() {
        @Override
        public int compare(NavigationItem lhs, NavigationItem rhs) {
            return lhs.itemOrder - rhs.itemOrder; // increasing
        }
    });
    allNavigationItems = new ArrayList<NavigationItem>(navigationItems);
    final Iterator<NavigationItem> iterator = navigationItems.iterator();
    while (iterator.hasNext()) {
        NavigationItem next = iterator.next();
        if (next.sharedPrefsKey != null) {
            if (!sp.getBoolean(next.sharedPrefsKey, defaultValues(next.sharedPrefsKey))) {
                iterator.remove();
            }
        }
    }
    sp_order.edit().commit(); // save

    final boolean compressedMenu = sp.getBoolean("compressedMenu", false);
    float menuFontScale = 1;
    try {
        menuFontScale = Float.parseFloat(sp.getString("menuFontScale", "1.0"));
    } catch (Exception e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    final float finalMenuFontScale = menuFontScale;
    navigationList = (DragSortListView) findViewById(R.id.navigation_list);

    // adapter for old-style navigation
    final BaseAdapter navigationAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return navigationItems.size();
        }

        @Override
        public Object getItem(int position) {
            return navigationItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (position == -1) {
                // NOOK is funny
                return convertView;
            }
            final int screenHeight = getWindow().getWindowManager().getDefaultDisplay().getHeight();
            final int layoutId = R.layout.simple_list_item_1_mine;
            final PressableLinearLayout retval = convertView != null ? (PressableLinearLayout) convertView
                    : (PressableLinearLayout) getLayoutInflater().inflate(layoutId, null);
            TextView tv = (TextView) retval.findViewById(android.R.id.text1);
            if (parent instanceof Spinner) {
                tv.setTextSize(18 * finalMenuFontScale);
                tv.setEllipsize(TextUtils.TruncateAt.MARQUEE);
            } else {
                tv.setTextSize(22 * finalMenuFontScale);
            }
            tv.setText(getString(navigationItems.get(position).labelId));
            if (compressedMenu) {
                int minHeight = (int) ((screenHeight * 0.7) / getCount());
                tv.setMinHeight(minHeight);
                tv.setMinimumHeight(minHeight);
            }
            retval.setPressedListener(new PressableLinearLayout.PressedListener() {
                @Override
                public void onPressStateChanged(boolean selected) {
                    MainActivity.restyleChildrenOrWidget(retval, false);
                }

                @Override
                public void onSelectStateChanged(boolean selected) {
                    MainActivity.restyleChildrenOrWidget(retval, false);
                }
            });
            MainActivity.restyleChildrenOrWidget(retval, false);
            return retval;
        }
    };
    // adapter for new-style navigation
    final BaseAdapter navigationListAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return getItems().size();
        }

        private ArrayList<NavigationItem> getItems() {
            if (navigationList.isDragEnabled()) {
                return allNavigationItems;
            } else {
                return navigationItems;
            }
        }

        @Override
        public Object getItem(int position) {
            return getItems().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        float textSize = -1;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (position == -1) {
                // NOOK is funny
                return convertView;
            }
            if (textSize < 0) {
                View inflate = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
                TextView text = (TextView) inflate.findViewById(android.R.id.text1);
                textSize = text.getTextSize();
            }
            final int layoutId = R.layout.navigation_list_item;
            final PressableLinearLayout retval = convertView != null ? (PressableLinearLayout) convertView
                    : (PressableLinearLayout) getLayoutInflater().inflate(layoutId, null);
            TextView tv = (TextView) retval.findViewById(android.R.id.text1);
            final ArrayList<NavigationItem> items = getItems();
            final NavigationItem theItem = items.get(position);
            tv.setText(getString(theItem.labelId));
            ImageButton menuButton = (ImageButton) retval.findViewById(R.id.menu_button);
            menuButton.setFocusable(false);
            ArrayList<String> menuItems = theItem.getMenuItems();
            menuButton.setVisibility(menuItems != null && menuItems.size() > 0 ? View.VISIBLE : View.GONE);
            menuButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    doNavigationItemMenu(theItem);
                }
            });
            ImageView iv = (ImageView) retval.findViewById(android.R.id.icon);
            iv.setImageResource(theItem.imageId);
            retval.findViewById(R.id.draggable)
                    .setVisibility(items != allNavigationItems ? View.GONE : View.VISIBLE);
            retval.findViewById(R.id.checkbox).setVisibility(
                    items != allNavigationItems || theItem.sharedPrefsKey == null ? View.GONE : View.VISIBLE);
            CheckBox cb = (CheckBox) retval.findViewById(R.id.checkbox);
            cb.setOnCheckedChangeListener(null);
            if (theItem.sharedPrefsKey != null) {
                cb.setChecked(sp.getBoolean(theItem.sharedPrefsKey, defaultValues(theItem.sharedPrefsKey)));
            }
            cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    sp.edit().putBoolean(theItem.sharedPrefsKey, isChecked).commit();
                }
            });
            int spacing = sp.getInt("navigation_spacing", 0);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize + spacing);

            retval.setPadding(0, spacing, 0, spacing);
            return retval;
        }
    };
    ActionBar bar = getSupportActionBar();
    updateActionBarMode();
    navigationList.setDragEnabled(false);
    ((DragSortController) navigationList.getFloatViewManager()).setDragHandleId(R.id.draggable);
    navigationList.setAdapter(navigationListAdapter);
    navigationList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
            setSelectedNavigationItem(position);
            closeNavigationMenu(true, false);
        }
    });
    navigationList.setDropListener(new DragSortListView.DropListener() {
        @Override
        public void drop(int from, int to) {
            final NavigationItem item = allNavigationItems.remove(from);
            allNavigationItems.add(to, item);

            int index = 0;
            for (NavigationItem allNavigationItem : allNavigationItems) {
                if (allNavigationItem.itemOrder != index) {
                    allNavigationItem.itemOrder = index;
                    sp_order.edit().putInt("order_" + allNavigationItem.id, allNavigationItem.itemOrder)
                            .commit();
                }
                index++;
            }
            sp_order.edit().commit(); // save
            navigationListAdapter.notifyDataSetChanged();
            //To change body of implemented methods use File | Settings | File Templates.
        }
    });
    bar.setListNavigationCallbacks(navigationAdapter, this);
    final View navigationMenuButton = (View) findViewById(R.id.navigation_menu_button);
    navigationMenuButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(MainActivity.this)
                    .setItems(navigationList.isDragEnabled() ? R.array.navigation_menu_end
                            : R.array.navigation_menu_start, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    int spacing = sp.getInt("navigation_spacing", 0);
                                    switch (which) {
                                    case 0:
                                        if (navigationList.isDragEnabled()) {
                                            navigationList.setDragEnabled(false);
                                            updateNavigation();
                                        } else {
                                            navigationList.setDragEnabled(true);
                                        }
                                        break;
                                    case 1:
                                        final Map<String, ?> all = sp_order.getAll();
                                        for (String s : all.keySet()) {
                                            sp_order.edit().remove(s).commit();
                                        }
                                        sp_order.edit().commit();
                                        updateNavigation();
                                        break;
                                    case 2: // wider
                                        sp.edit().putInt("navigation_spacing", spacing + 1).commit();
                                        ((BaseAdapter) navigationList.getAdapter()).notifyDataSetInvalidated();
                                        break;
                                    case 3: // narrower
                                        if (spacing > 0) {
                                            sp.edit().putInt("navigation_spacing", spacing - 1).commit();
                                            ((BaseAdapter) navigationList.getAdapter())
                                                    .notifyDataSetInvalidated();
                                        }
                                        break;
                                    case 4: // logout from..
                                        logoutFromSomeServices();
                                        break;

                                    }
                                    navigationListAdapter.notifyDataSetChanged();
                                }
                            })
                    .setCancelable(true).create().show();
        }
    });

    final SharedPreferences spn = getSharedPreferences("saved_last_navigation_type", MODE_PRIVATE);
    int restoredLastNavItem = spn.getInt("last_navigation", 0);
    if (restoredLastNavItem != 0) {
        NavigationItem allSources = null;
        for (int i = 0; i < navigationItems.size(); i++) {
            NavigationItem navigationItem = navigationItems.get(i);
            if (navigationItem.labelId == restoredLastNavItem) {
                lastNavigationItem = navigationItem;
            }
            if (navigationItem.labelId == R.string.navigationAll) {
                allSources = navigationItem;
            }
        }
        if (lastNavigationItem == null) {
            lastNavigationItem = allSources; // could be null if not configured
        }
        if (lastNavigationItem == null && navigationItems.size() > 0) {
            lastNavigationItem = navigationItems.get(0); // last default
        }
        if (lastNavigationItem != null) {
            restoreLastNavigationPosition();
            lastNavigationItem.action();
        }
    }

}

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

@Override
public boolean onContextItemSelected(final MenuItem item) {
    if (item.getItemId() == CLEAR) {
        final ProgressDialog loadingDialog = new ProgressDialog(this);
        final AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

            @Override//from  w w  w.  j a  v a 2  s  . c  o  m
            protected Void doInBackground(Void... arg0) {
                // clear all notifications
                ContentValues values = new ContentValues();
                values.put(Notifications.CLEARED, 1);
                SonetNotifications.this.getContentResolver().update(
                        Notifications.getContentUri(SonetNotifications.this), values, Notifications._ID + "=?",
                        new String[] { Long.toString(((AdapterContextMenuInfo) item.getMenuInfo()).id) });
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                if (loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }
                SonetNotifications.this.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();
    }
    return super.onContextItemSelected(item);
    // clear
}

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

private void startNavigationTask(String id) {

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

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

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

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

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

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

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

    final GeoPoint entrancef = entrance;

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

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

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

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

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

            }, userData.getLocationGPSorIP(), entrance);

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

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

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

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

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

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

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

@Override
public boolean onContextItemSelected(final MenuItem item) {
    if (item.getItemId() == CLEAR) {
        final ProgressDialog loadingDialog = new ProgressDialog(this);
        final AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

            @Override//from ww w . j av a 2  s.c o m
            protected Void doInBackground(Void... arg0) {
                // clear all notifications
                ContentValues values = new ContentValues();
                values.put(Notifications.CLEARED, 1);
                MyfeedleNotifications.this.getContentResolver().update(
                        Notifications.getContentUri(MyfeedleNotifications.this), values,
                        Notifications._ID + "=?",
                        new String[] { Long.toString(((AdapterContextMenuInfo) item.getMenuInfo()).id) });
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                if (loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }
                MyfeedleNotifications.this.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();
    }
    return super.onContextItemSelected(item);
    // clear
}