Search in sources :

Example 36 with AsyncTask

use of android.os.AsyncTask in project Slide by ccrama.

the class SubredditView method doSubOnlyStuff.

private void doSubOnlyStuff(final Subreddit subreddit) {
    if (!isFinishing()) {
        findViewById(R.id.loader).setVisibility(View.GONE);
        if (subreddit.getDataNode().has("subreddit_type") && !subreddit.getDataNode().get("subreddit_type").isNull()) {
            canSubmit = !subreddit.getDataNode().get("subreddit_type").asText().toUpperCase().equals("RESTRICTED");
        }
        if (subreddit.getSidebar() != null && !subreddit.getSidebar().isEmpty()) {
            findViewById(R.id.sidebar_text).setVisibility(View.VISIBLE);
            final String text = subreddit.getDataNode().get("description_html").asText().trim();
            final SpoilerRobotoTextView body = (SpoilerRobotoTextView) findViewById(R.id.sidebar_text);
            CommentOverflow overflow = (CommentOverflow) findViewById(R.id.commentOverflow);
            setViews(text, subreddit.getDisplayName(), body, overflow);
            // get all subs that have Notifications enabled
            ArrayList<String> rawSubs = Reddit.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
            HashMap<String, Integer> subThresholds = new HashMap<>();
            for (String s : rawSubs) {
                try {
                    String[] split = s.split(":");
                    subThresholds.put(split[0].toLowerCase(Locale.ENGLISH), Integer.valueOf(split[1]));
                } catch (Exception ignored) {
                // do nothing
                }
            }
            // whether or not this subreddit was in the keySet
            boolean isNotified = subThresholds.keySet().contains(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH));
            ((AppCompatCheckBox) findViewById(R.id.notify_posts_state)).setChecked(isNotified);
        } else {
            findViewById(R.id.sidebar_text).setVisibility(View.GONE);
        }
        View collection = findViewById(R.id.collection);
        if (Authentication.isLoggedIn) {
            collection.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    new AsyncTask<Void, Void, Void>() {

                        HashMap<String, MultiReddit> multis = new HashMap<String, MultiReddit>();

                        @Override
                        protected Void doInBackground(Void... params) {
                            if (UserSubscriptions.multireddits == null) {
                                UserSubscriptions.syncMultiReddits(SubredditView.this);
                            }
                            for (MultiReddit r : UserSubscriptions.multireddits) {
                                multis.put(r.getDisplayName(), r);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            new MaterialDialog.Builder(SubredditView.this).title("Add /r/" + subreddit.getDisplayName() + " to").items(multis.keySet()).itemsCallback(new MaterialDialog.ListCallback() {

                                @Override
                                public void onSelection(MaterialDialog dialog, View itemView, final int which, CharSequence text) {
                                    new AsyncTask<Void, Void, Void>() {

                                        @Override
                                        protected Void doInBackground(Void... params) {
                                            try {
                                                final String multiName = multis.keySet().toArray(new String[multis.size()])[which];
                                                List<String> subs = new ArrayList<String>();
                                                for (MultiSubreddit sub : multis.get(multiName).getSubreddits()) {
                                                    subs.add(sub.getDisplayName());
                                                }
                                                subs.add(subreddit.getDisplayName());
                                                new MultiRedditManager(Authentication.reddit).createOrUpdate(new MultiRedditUpdateRequest.Builder(Authentication.name, multiName).subreddits(subs).build());
                                                UserSubscriptions.syncMultiReddits(SubredditView.this);
                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        drawerLayout.closeDrawers();
                                                        Snackbar s = Snackbar.make(mToolbar, getString(R.string.multi_subreddit_added, multiName), Snackbar.LENGTH_LONG);
                                                        View view = s.getView();
                                                        TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
                                                        tv.setTextColor(Color.WHITE);
                                                        s.show();
                                                    }
                                                });
                                            } catch (final NetworkException | ApiException e) {
                                                runOnUiThread(new Runnable() {

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

                                                            @Override
                                                            public void run() {
                                                                Snackbar.make(mToolbar, getString(R.string.multi_error), Snackbar.LENGTH_LONG).setAction(R.string.btn_ok, new View.OnClickListener() {

                                                                    @Override
                                                                    public void onClick(View v) {
                                                                    }
                                                                }).show();
                                                            }
                                                        });
                                                    }
                                                });
                                                e.printStackTrace();
                                            }
                                            return null;
                                        }
                                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                }
                            }).show();
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            });
        } else {
            collection.setVisibility(View.GONE);
        }
        {
            final TextView subscribe = (TextView) findViewById(R.id.subscribe);
            currentlySubbed = (!Authentication.isLoggedIn && UserSubscriptions.getSubscriptions(this).contains(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH))) || (Authentication.isLoggedIn && subreddit.isUserSubscriber());
            doSubscribeButtonText(currentlySubbed, subscribe);
            assert subscribe != null;
            subscribe.setOnClickListener(new View.OnClickListener() {

                private void doSubscribe() {
                    if (Authentication.isLoggedIn) {
                        new AlertDialogWrapper.Builder(SubredditView.this).setTitle(getString(R.string.subscribe_to, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_add_subscribe, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new AsyncTask<Void, Void, Boolean>() {

                                    @Override
                                    public void onPostExecute(Boolean success) {
                                        if (!success) {
                                            // If subreddit was removed from account or not
                                            new AlertDialogWrapper.Builder(SubredditView.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    changeSubscription(subreddit, // Force add the subscription
                                                    true);
                                                    Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_subscribed), Snackbar.LENGTH_SHORT);
                                                    View view = s.getView();
                                                    TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
                                                    tv.setTextColor(Color.WHITE);
                                                    s.show();
                                                }
                                            }).setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                }
                                            }).setCancelable(false).show();
                                        } else {
                                            changeSubscription(subreddit, true);
                                        }
                                    }

                                    @Override
                                    protected Boolean doInBackground(Void... params) {
                                        try {
                                            new AccountManager(Authentication.reddit).subscribe(subreddit);
                                        } catch (NetworkException e) {
                                            // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                            return false;
                                        }
                                        return true;
                                    }
                                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                            }
                        }).setNegativeButton(R.string.btn_cancel, null).setNeutralButton(R.string.btn_add_to_sublist, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                changeSubscription(subreddit, // Force add the subscription
                                true);
                                Snackbar s = Snackbar.make(mToolbar, R.string.sub_added, Snackbar.LENGTH_SHORT);
                                View view = s.getView();
                                TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
                                tv.setTextColor(Color.WHITE);
                                s.show();
                            }
                        }).show();
                    } else {
                        changeSubscription(subreddit, true);
                    }
                }

                @Override
                public void onClick(View v) {
                    if (!currentlySubbed) {
                        doSubscribe();
                        doSubscribeButtonText(currentlySubbed, subscribe);
                    } else {
                        doUnsubscribe();
                        doSubscribeButtonText(currentlySubbed, subscribe);
                    }
                }

                private void doUnsubscribe() {
                    if (Authentication.didOnline) {
                        new AlertDialogWrapper.Builder(SubredditView.this).setTitle(getString(R.string.unsubscribe_from, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_remove_unsubsribe, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new AsyncTask<Void, Void, Boolean>() {

                                    @Override
                                    public void onPostExecute(Boolean success) {
                                        if (!success) {
                                            // If subreddit was removed from account or not
                                            new AlertDialogWrapper.Builder(SubredditView.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    changeSubscription(subreddit, // Force add the subscription
                                                    false);
                                                    Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_unsubscribed), Snackbar.LENGTH_SHORT);
                                                    View view = s.getView();
                                                    TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
                                                    tv.setTextColor(Color.WHITE);
                                                    s.show();
                                                }
                                            }).setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                }
                                            }).setCancelable(false).show();
                                        } else {
                                            changeSubscription(subreddit, false);
                                        }
                                    }

                                    @Override
                                    protected Boolean doInBackground(Void... params) {
                                        try {
                                            new AccountManager(Authentication.reddit).unsubscribe(subreddit);
                                        } catch (NetworkException e) {
                                            // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                            return false;
                                        }
                                        return true;
                                    }
                                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                            }
                        }).setNeutralButton(R.string.just_unsub, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                changeSubscription(subreddit, // Force add the subscription
                                false);
                                Snackbar s = Snackbar.make(mToolbar, R.string.misc_unsubscribed, Snackbar.LENGTH_SHORT);
                                View view = s.getView();
                                TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
                                tv.setTextColor(Color.WHITE);
                                s.show();
                            }
                        }).setNegativeButton(R.string.btn_cancel, null).show();
                    } else {
                        changeSubscription(subreddit, false);
                    }
                }
            });
        }
        {
            final AppCompatCheckBox notifyStateCheckBox = (AppCompatCheckBox) findViewById(R.id.notify_posts_state);
            assert notifyStateCheckBox != null;
            notifyStateCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        final String sub = subreddit.getDisplayName();
                        if (!sub.equalsIgnoreCase("all") && !sub.equalsIgnoreCase("frontpage") && !sub.equalsIgnoreCase("friends") && !sub.equalsIgnoreCase("mod") && !sub.contains("+") && !sub.contains(".") && !sub.contains("/m/")) {
                            new AlertDialogWrapper.Builder(SubredditView.this).setTitle(getString(R.string.sub_post_notifs_title, sub)).setMessage(R.string.sub_post_notifs_msg).setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    new MaterialDialog.Builder(SubredditView.this).title(R.string.sub_post_notifs_threshold).items(new String[] { "1", "5", "10", "20", "40", "50" }).alwaysCallSingleChoiceCallback().itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {

                                        @Override
                                        public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                            ArrayList<String> subs = Reddit.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
                                            subs.add(sub + ":" + text);
                                            Reddit.appRestart.edit().putString(CheckForMail.SUBS_TO_GET, Reddit.arrayToString(subs)).commit();
                                            return true;
                                        }
                                    }).cancelable(false).show();
                                }
                            }).setNegativeButton(R.string.btn_cancel, null).setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    notifyStateCheckBox.setChecked(false);
                                }
                            }).setOnCancelListener(new DialogInterface.OnCancelListener() {

                                @Override
                                public void onCancel(DialogInterface dialog) {
                                    notifyStateCheckBox.setChecked(false);
                                }
                            }).show();
                        } else {
                            notifyStateCheckBox.setChecked(false);
                            Toast.makeText(SubredditView.this, R.string.sub_post_notifs_err, Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Intent cancelIntent = new Intent(SubredditView.this, CancelSubNotifs.class);
                        cancelIntent.putExtra(CancelSubNotifs.EXTRA_SUB, subreddit.getDisplayName());
                        startActivity(cancelIntent);
                    }
                }
            });
        }
        if (!subreddit.getPublicDescription().isEmpty()) {
            findViewById(R.id.sub_title).setVisibility(View.VISIBLE);
            setViews(subreddit.getDataNode().get("public_description_html").asText(), subreddit.getDisplayName().toLowerCase(Locale.ENGLISH), ((SpoilerRobotoTextView) findViewById(R.id.sub_title)), (CommentOverflow) findViewById(R.id.sub_title_overflow));
        } else {
            findViewById(R.id.sub_title).setVisibility(View.GONE);
        }
        if (subreddit.getDataNode().has("icon_img") && !subreddit.getDataNode().get("icon_img").asText().isEmpty()) {
            ((Reddit) getApplication()).getImageLoader().displayImage(subreddit.getDataNode().get("icon_img").asText(), (ImageView) findViewById(R.id.subimage));
        } else {
            findViewById(R.id.subimage).setVisibility(View.GONE);
        }
        ((TextView) findViewById(R.id.subscribers)).setText(getString(R.string.subreddit_subscribers_string, subreddit.getLocalizedSubscriberCount()));
        findViewById(R.id.subscribers).setVisibility(View.VISIBLE);
        ((TextView) findViewById(R.id.active_users)).setText(getString(R.string.subreddit_active_users_string_new, subreddit.getLocalizedAccountsActive()));
        findViewById(R.id.active_users).setVisibility(View.VISIBLE);
    }
}
Also used : HashMap(java.util.HashMap) DialogInterface(android.content.DialogInterface) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) MultiReddit(net.dean.jraw.models.MultiReddit) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) CommentOverflow(me.ccrama.redditslide.Views.CommentOverflow) List(java.util.List) ArrayList(java.util.ArrayList) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) TextView(android.widget.TextView) NetworkException(net.dean.jraw.http.NetworkException) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) ImageView(android.widget.ImageView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) View(android.view.View) TextView(android.widget.TextView) ApiException(net.dean.jraw.ApiException) ActivityNotFoundException(android.content.ActivityNotFoundException) NetworkException(net.dean.jraw.http.NetworkException) AppCompatCheckBox(android.support.v7.widget.AppCompatCheckBox) MultiRedditManager(net.dean.jraw.managers.MultiRedditManager) AccountManager(net.dean.jraw.managers.AccountManager) CompoundButton(android.widget.CompoundButton) Snackbar(android.support.design.widget.Snackbar)

Example 37 with AsyncTask

use of android.os.AsyncTask in project Slide by ccrama.

the class CommentAdapterHelper method categorizeComment.

private static void categorizeComment(final Comment comment, final Context mContext) {
    new AsyncTask<Void, Void, List<String>>() {

        Dialog d;

        @Override
        public void onPreExecute() {
            d = new MaterialDialog.Builder(mContext).progress(true, 100).content(R.string.misc_please_wait).title(R.string.profile_category_loading).show();
        }

        @Override
        protected List<String> doInBackground(Void... params) {
            try {
                List<String> categories = new ArrayList<String>(new AccountManager(Authentication.reddit).getSavedCategories());
                categories.add("New category");
                return categories;
            } catch (Exception e) {
                e.printStackTrace();
                return new ArrayList<String>() {

                    {
                        add("New category");
                    }
                };
            }
        }

        @Override
        public void onPostExecute(final List<String> data) {
            try {
                new MaterialDialog.Builder(mContext).items(data).title(R.string.sidebar_select_flair).itemsCallback(new MaterialDialog.ListCallback() {

                    @Override
                    public void onSelection(MaterialDialog dialog, final View itemView, int which, CharSequence text) {
                        final String t = data.get(which);
                        if (which == data.size() - 1) {
                            new MaterialDialog.Builder(mContext).title(R.string.category_set_name).input(mContext.getString(R.string.category_set_name_hint), null, false, new MaterialDialog.InputCallback() {

                                @Override
                                public void onInput(MaterialDialog dialog, CharSequence input) {
                                }
                            }).positiveText(R.string.btn_set).onPositive(new MaterialDialog.SingleButtonCallback() {

                                @Override
                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                    final String flair = dialog.getInputEditText().getText().toString();
                                    new AsyncTask<Void, Void, Boolean>() {

                                        @Override
                                        protected Boolean doInBackground(Void... params) {
                                            try {
                                                new AccountManager(Authentication.reddit).save(comment, flair);
                                                return true;
                                            } catch (ApiException e) {
                                                e.printStackTrace();
                                                return false;
                                            }
                                        }

                                        @Override
                                        protected void onPostExecute(Boolean done) {
                                            Snackbar s;
                                            if (done) {
                                                if (itemView != null) {
                                                    s = Snackbar.make(itemView, R.string.submission_info_saved, Snackbar.LENGTH_SHORT);
                                                    View view = s.getView();
                                                    TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                    tv.setTextColor(Color.WHITE);
                                                    s.show();
                                                }
                                            } else {
                                                if (itemView != null) {
                                                    s = Snackbar.make(itemView, R.string.category_set_error, Snackbar.LENGTH_SHORT);
                                                    View view = s.getView();
                                                    TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                    tv.setTextColor(Color.WHITE);
                                                    s.show();
                                                }
                                            }
                                        }
                                    }.execute();
                                }
                            }).negativeText(R.string.btn_cancel).show();
                        } else {
                            new AsyncTask<Void, Void, Boolean>() {

                                @Override
                                protected Boolean doInBackground(Void... params) {
                                    try {
                                        new AccountManager(Authentication.reddit).save(comment, t);
                                        return true;
                                    } catch (ApiException e) {
                                        e.printStackTrace();
                                        return false;
                                    }
                                }

                                @Override
                                protected void onPostExecute(Boolean done) {
                                    Snackbar s;
                                    if (done) {
                                        if (itemView != null) {
                                            s = Snackbar.make(itemView, R.string.submission_info_saved, Snackbar.LENGTH_SHORT);
                                            View view = s.getView();
                                            TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                            tv.setTextColor(Color.WHITE);
                                            s.show();
                                        }
                                    } else {
                                        if (itemView != null) {
                                            s = Snackbar.make(itemView, R.string.category_set_error, Snackbar.LENGTH_SHORT);
                                            View view = s.getView();
                                            TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                            tv.setTextColor(Color.WHITE);
                                            s.show();
                                        }
                                    }
                                }
                            }.execute();
                        }
                    }
                }).show();
                if (d != null) {
                    d.dismiss();
                }
            } catch (Exception ignored) {
            }
        }
    }.execute();
}
Also used : SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Dialog(android.app.Dialog) List(java.util.List) ArrayList(java.util.ArrayList) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) TextView(android.widget.TextView) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AsyncTask(android.os.AsyncTask) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) View(android.view.View) TextView(android.widget.TextView) ApiException(net.dean.jraw.ApiException) InvalidScopeException(net.dean.jraw.http.oauth.InvalidScopeException) DialogAction(com.afollestad.materialdialogs.DialogAction) AccountManager(net.dean.jraw.managers.AccountManager) ApiException(net.dean.jraw.ApiException) Snackbar(android.support.design.widget.Snackbar)

Example 38 with AsyncTask

use of android.os.AsyncTask in project Slide by ccrama.

the class CommentAdapterHelper method showBan.

public static void showBan(final Context mContext, final View mToolbar, final Comment submission, String rs, String nt, String msg, String t) {
    LinearLayout l = new LinearLayout(mContext);
    l.setOrientation(LinearLayout.VERTICAL);
    int sixteen = Reddit.dpToPxVertical(16);
    l.setPadding(sixteen, 0, sixteen, 0);
    final EditText reason = new EditText(mContext);
    reason.setHint(R.string.mod_ban_reason);
    reason.setText(rs);
    reason.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
    l.addView(reason);
    final EditText note = new EditText(mContext);
    note.setHint(R.string.mod_ban_note_mod);
    note.setText(nt);
    note.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
    l.addView(note);
    final EditText message = new EditText(mContext);
    message.setHint(R.string.mod_ban_note_user);
    message.setText(msg);
    message.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
    l.addView(message);
    final EditText time = new EditText(mContext);
    time.setHint(R.string.mod_ban_time);
    time.setText(t);
    time.setInputType(InputType.TYPE_CLASS_NUMBER);
    l.addView(time);
    AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(mContext);
    builder.setView(l).setTitle(mContext.getString(R.string.mod_ban_title, submission.getAuthor())).setCancelable(true).setPositiveButton(R.string.mod_btn_ban, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // to ban
            if (reason.getText().toString().isEmpty() || time.getText().toString().isEmpty()) {
                new AlertDialogWrapper.Builder(mContext).setTitle(R.string.mod_ban_requirements).setMessage(R.string.misc_please_try_again).setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showBan(mContext, mToolbar, submission, reason.getText().toString(), note.getText().toString(), message.getText().toString(), time.getText().toString());
                    }
                }).setCancelable(false).show();
            } else {
                new AsyncTask<Void, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(Void... params) {
                        try {
                            String n = note.getText().toString();
                            String m = message.getText().toString();
                            if (n.isEmpty()) {
                                n = null;
                            }
                            if (m.isEmpty()) {
                                m = null;
                            }
                            new ModerationManager(Authentication.reddit).banUser(submission.getSubredditName(), submission.getAuthor(), reason.getText().toString(), n, m, Integer.valueOf(time.getText().toString()));
                            return true;
                        } catch (Exception e) {
                            if (e instanceof InvalidScopeException) {
                                scope = true;
                            }
                            e.printStackTrace();
                            return false;
                        }
                    }

                    boolean scope;

                    @Override
                    protected void onPostExecute(Boolean done) {
                        Snackbar s;
                        if (done) {
                            s = Snackbar.make(mToolbar, R.string.mod_ban_success, Snackbar.LENGTH_SHORT);
                        } else {
                            if (scope) {
                                new AlertDialogWrapper.Builder(mContext).setTitle(R.string.mod_ban_reauth).setMessage(R.string.mod_ban_reauth_question).setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent i = new Intent(mContext, Reauthenticate.class);
                                        mContext.startActivity(i);
                                    }
                                }).setNegativeButton(R.string.misc_maybe_later, null).setCancelable(false).show();
                            }
                            s = Snackbar.make(mToolbar, R.string.mod_ban_fail, Snackbar.LENGTH_INDEFINITE).setAction(R.string.misc_try_again, new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    showBan(mContext, mToolbar, submission, reason.getText().toString(), note.getText().toString(), message.getText().toString(), time.getText().toString());
                                }
                            });
                        }
                        if (s != null) {
                            View view = s.getView();
                            TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                            tv.setTextColor(Color.WHITE);
                            s.show();
                        }
                    }
                }.execute();
            }
        }
    }).setNegativeButton(R.string.btn_cancel, null).show();
}
Also used : EditText(android.widget.EditText) ModerationManager(net.dean.jraw.managers.ModerationManager) DialogInterface(android.content.DialogInterface) SpannableStringBuilder(android.text.SpannableStringBuilder) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) View(android.view.View) TextView(android.widget.TextView) ApiException(net.dean.jraw.ApiException) InvalidScopeException(net.dean.jraw.http.oauth.InvalidScopeException) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) TextView(android.widget.TextView) InvalidScopeException(net.dean.jraw.http.oauth.InvalidScopeException) LinearLayout(android.widget.LinearLayout) Snackbar(android.support.design.widget.Snackbar)

Example 39 with AsyncTask

use of android.os.AsyncTask in project Slide by ccrama.

the class SubredditPosts method doMainActivityOffline.

public void doMainActivityOffline(final Context c, final SubmissionDisplay displayer) {
    LogUtil.v(subreddit);
    if (all == null) {
        all = OfflineSubreddit.getAll(subreddit);
    }
    // Move 0, or "submission only", to the end
    Collections.rotate(all, -1);
    offline = true;
    final String[] titles = new String[all.size()];
    final String[] base = new String[all.size()];
    int i = 0;
    for (String s : all) {
        String[] split = s.split(",");
        titles[i] = (Long.valueOf(split[1]) == 0 ? c.getString(R.string.settings_backup_submission_only) : TimeUtils.getTimeAgo(Long.valueOf(split[1]), c) + c.getString(R.string.settings_backup_comments));
        base[i] = s;
        i++;
    }
    ((MainActivity) c).getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    ((MainActivity) c).getSupportActionBar().setListNavigationCallbacks(new OfflineSubAdapter(c, android.R.layout.simple_list_item_1, titles), new ActionBar.OnNavigationListener() {

        @Override
        public boolean onNavigationItemSelected(int itemPosition, long itemId) {
            final String[] s2 = base[itemPosition].split(",");
            OfflineSubreddit.currentid = Long.valueOf(s2[1]);
            currentid = OfflineSubreddit.currentid;
            new AsyncTask<Void, Void, Void>() {

                OfflineSubreddit cached;

                @Override
                protected Void doInBackground(Void... params) {
                    cached = OfflineSubreddit.getSubreddit(subreddit, Long.valueOf(s2[1]), true, c);
                    List<Submission> finalSubs = new ArrayList<>();
                    for (Submission s : cached.submissions) {
                        if (!PostMatch.doesMatch(s, subreddit, force18)) {
                            finalSubs.add(s);
                        }
                    }
                    posts = finalSubs;
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    if (cached.submissions.isEmpty()) {
                        displayer.updateOfflineError();
                    }
                    // update offline
                    displayer.updateOffline(posts, Long.valueOf(s2[1]));
                }
            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            return true;
        }
    });
}
Also used : Submission(net.dean.jraw.models.Submission) AsyncTask(android.os.AsyncTask) OfflineSubreddit(me.ccrama.redditslide.OfflineSubreddit) ArrayList(java.util.ArrayList) ActionBar(android.support.v7.app.ActionBar)

Example 40 with AsyncTask

use of android.os.AsyncTask in project Slide by ccrama.

the class PopulateShadowboxInfo method showBottomSheet.

public static void showBottomSheet(final Activity mContext, final Submission submission, final View rootView) {
    int[] attrs = new int[] { R.attr.tintColor };
    TypedArray ta = mContext.obtainStyledAttributes(attrs);
    int color = ta.getColor(0, Color.WHITE);
    Drawable profile = mContext.getResources().getDrawable(R.drawable.profile);
    final Drawable sub = mContext.getResources().getDrawable(R.drawable.sub);
    final Drawable report = mContext.getResources().getDrawable(R.drawable.report);
    Drawable copy = mContext.getResources().getDrawable(R.drawable.ic_content_copy);
    Drawable open = mContext.getResources().getDrawable(R.drawable.openexternal);
    Drawable link = mContext.getResources().getDrawable(R.drawable.link);
    Drawable reddit = mContext.getResources().getDrawable(R.drawable.commentchange);
    profile.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    sub.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    report.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    copy.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    open.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    link.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    reddit.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    ta.recycle();
    BottomSheet.Builder b = new BottomSheet.Builder(mContext).title(Html.fromHtml(submission.getTitle()));
    if (Authentication.didOnline) {
        b.sheet(1, profile, "/u/" + submission.getAuthor()).sheet(2, sub, "/r/" + submission.getSubredditName());
        if (Authentication.isLoggedIn) {
            b.sheet(12, report, mContext.getString(R.string.btn_report));
        }
    }
    b.sheet(7, open, mContext.getString(R.string.submission_link_extern)).sheet(4, link, mContext.getString(R.string.submission_share_permalink)).sheet(8, reddit, mContext.getString(R.string.submission_share_reddit_url)).listener(new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch(which) {
                case 1:
                    {
                        Intent i = new Intent(mContext, Profile.class);
                        i.putExtra(Profile.EXTRA_PROFILE, submission.getAuthor());
                        mContext.startActivity(i);
                    }
                    break;
                case 2:
                    {
                        Intent i = new Intent(mContext, SubredditView.class);
                        i.putExtra(SubredditView.EXTRA_SUBREDDIT, submission.getSubredditName());
                        mContext.startActivityForResult(i, 14);
                    }
                    break;
                case 7:
                    LinkUtil.openExternally(submission.getUrl(), mContext);
                    break;
                case 4:
                    Reddit.defaultShareText(submission.getTitle(), submission.getUrl(), mContext);
                    break;
                case 12:
                    reportReason = "";
                    new MaterialDialog.Builder(mContext).input(mContext.getString(R.string.input_reason_for_report), null, true, new MaterialDialog.InputCallback() {

                        @Override
                        public void onInput(MaterialDialog dialog, CharSequence input) {
                            reportReason = input.toString();
                        }
                    }).alwaysCallInputCallback().title(R.string.report_post).inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES).positiveText(R.string.btn_report).negativeText(R.string.btn_cancel).onNegative(null).onPositive(new MaterialDialog.SingleButtonCallback() {

                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            new AsyncTask<Void, Void, Void>() {

                                @Override
                                protected Void doInBackground(Void... params) {
                                    try {
                                        new AccountManager(Authentication.reddit).report(submission, reportReason);
                                    } catch (ApiException e) {
                                        e.printStackTrace();
                                    }
                                    return null;
                                }

                                @Override
                                protected void onPostExecute(Void aVoid) {
                                    Snackbar s = Snackbar.make(rootView, R.string.msg_report_sent, Snackbar.LENGTH_SHORT);
                                    View view = s.getView();
                                    TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
                                    tv.setTextColor(Color.WHITE);
                                    s.show();
                                }
                            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                    }).show();
                    break;
                case 8:
                    if (SettingValues.shareLongLink) {
                        Reddit.defaultShareText(submission.getTitle(), "htts://reddit.com" + submission.getPermalink(), mContext);
                    } else {
                        Reddit.defaultShareText(submission.getTitle(), "https://redd.it/" + submission.getId(), mContext);
                    }
                    break;
                case 6:
                    {
                        ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Link", submission.getUrl());
                        clipboard.setPrimaryClip(clip);
                        Toast.makeText(mContext, R.string.submission_link_copied, Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    });
    b.show();
}
Also used : DialogInterface(android.content.DialogInterface) SpannableStringBuilder(android.text.SpannableStringBuilder) TypedArray(android.content.res.TypedArray) TitleTextView(me.ccrama.redditslide.Views.TitleTextView) TextView(android.widget.TextView) ClipboardManager(android.content.ClipboardManager) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Drawable(android.graphics.drawable.Drawable) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) ImageView(android.widget.ImageView) TitleTextView(me.ccrama.redditslide.Views.TitleTextView) View(android.view.View) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) DialogAction(com.afollestad.materialdialogs.DialogAction) AccountManager(net.dean.jraw.managers.AccountManager) BottomSheet(com.cocosw.bottomsheet.BottomSheet) ClipData(android.content.ClipData) ApiException(net.dean.jraw.ApiException) Snackbar(android.support.design.widget.Snackbar)

Aggregations

AsyncTask (android.os.AsyncTask)395 IOException (java.io.IOException)188 InputStream (java.io.InputStream)159 URL (java.net.URL)159 HttpURLConnection (java.net.HttpURLConnection)158 ExecutionException (java.util.concurrent.ExecutionException)158 Gson (com.google.gson.Gson)155 Message (com.remswork.project.alice.model.support.Message)153 GradingFactorException (com.remswork.project.alice.exception.GradingFactorException)102 ArrayList (java.util.ArrayList)93 View (android.view.View)54 Intent (android.content.Intent)52 TextView (android.widget.TextView)52 JSONException (org.json.JSONException)51 JSONArray (org.json.JSONArray)50 DialogInterface (android.content.DialogInterface)40 OutputStream (java.io.OutputStream)37 BufferedWriter (java.io.BufferedWriter)35 OutputStreamWriter (java.io.OutputStreamWriter)35 ImageView (android.widget.ImageView)33