Search in sources :

Example 1 with MultiReddit

use of net.dean.jraw.models.MultiReddit in project Slide by ccrama.

the class MainActivity method doSubOnlyStuff.

public void doSubOnlyStuff(final Subreddit subreddit) {
    findViewById(R.id.loader).setVisibility(View.GONE);
    if (subreddit.getSubredditType() != null) {
        canSubmit = !subreddit.getSubredditType().equals("RESTRICTED");
    } else {
        canSubmit = true;
    }
    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();
        setViews(text, subreddit.getDisplayName(), sidebarBody, sidebarOverflow);
        // 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(MainActivity.this);
                            }
                            for (MultiReddit r : UserSubscriptions.multireddits) {
                                multis.put(r.getDisplayName(), r);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            new MaterialDialog.Builder(MainActivity.this).title(getString(R.string.multi_add_to, subreddit.getDisplayName())).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(MainActivity.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 = 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 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(MainActivity.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(MainActivity.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(MainActivity.this, R.string.sub_post_notifs_err, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Intent cancelIntent = new Intent(MainActivity.this, CancelSubNotifs.class);
                    cancelIntent.putExtra(CancelSubNotifs.EXTRA_SUB, subreddit.getDisplayName());
                    startActivity(cancelIntent);
                }
            }
        });
    }
    {
        final TextView subscribe = (TextView) findViewById(R.id.subscribe);
        currentlySubbed = (!Authentication.isLoggedIn && usedArray.contains(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH))) || subreddit.isUserSubscriber();
        doSubscribeButtonText(currentlySubbed, subscribe);
        assert subscribe != null;
        subscribe.setOnClickListener(new View.OnClickListener() {

            private void doSubscribe() {
                if (Authentication.isLoggedIn) {
                    new AlertDialogWrapper.Builder(MainActivity.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(MainActivity.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_LONG);
                                                View view = s.getView();
                                                TextView tv = 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);
                        }
                    }).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_LONG);
                            View view = s.getView();
                            TextView tv = 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, true);
                }
            }

            private void doUnsubscribe() {
                if (Authentication.didOnline) {
                    new AlertDialogWrapper.Builder(MainActivity.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(MainActivity.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_LONG);
                                                View view = s.getView();
                                                TextView tv = 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_LONG);
                            View view = s.getView();
                            TextView tv = 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);
                }
            }

            @Override
            public void onClick(View v) {
                if (!currentlySubbed) {
                    doSubscribe();
                    doSubscribeButtonText(currentlySubbed, subscribe);
                } else {
                    doUnsubscribe();
                    doSubscribeButtonText(currentlySubbed, subscribe);
                }
            }
        });
    }
    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);
    }
    ((ImageView) findViewById(R.id.subimage)).setImageResource(0);
    if (subreddit.getDataNode().has("icon_img") && !subreddit.getDataNode().get("icon_img").asText().isEmpty()) {
        findViewById(R.id.subimage).setVisibility(View.VISIBLE);
        ((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) ArrayList(java.util.ArrayList) CaseInsensitiveArrayList(me.ccrama.redditslide.CaseInsensitiveArrayList) MultiReddit(net.dean.jraw.models.MultiReddit) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) MultiRedditUpdateRequest(net.dean.jraw.http.MultiRedditUpdateRequest) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) TextView(android.widget.TextView) ImageView(android.widget.ImageView) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AsyncTask(android.os.AsyncTask) AccountManager(net.dean.jraw.managers.AccountManager) Snackbar(android.support.design.widget.Snackbar) DialogInterface(android.content.DialogInterface) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) NetworkException(net.dean.jraw.http.NetworkException) Intent(android.content.Intent) ImageView(android.widget.ImageView) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) View(android.view.View) CardView(android.support.v7.widget.CardView) TextView(android.widget.TextView) ListView(android.widget.ListView) ApiException(net.dean.jraw.ApiException) ActivityNotFoundException(android.content.ActivityNotFoundException) NetworkException(net.dean.jraw.http.NetworkException) Point(android.graphics.Point) AppCompatCheckBox(android.support.v7.widget.AppCompatCheckBox) MultiRedditManager(net.dean.jraw.managers.MultiRedditManager) CompoundButton(android.widget.CompoundButton) ApiException(net.dean.jraw.ApiException)

Example 2 with MultiReddit

use of net.dean.jraw.models.MultiReddit in project Slide by ccrama.

the class MultiredditOverview method doDrawerSubs.

public void doDrawerSubs(int position) {
    MultiReddit current = usedArray.get(position);
    LinearLayout l = (LinearLayout) findViewById(R.id.sidebar_scroll);
    l.removeAllViews();
    CaseInsensitiveArrayList toSort = new CaseInsensitiveArrayList();
    for (MultiSubreddit s : current.getSubreddits()) {
        toSort.add(s.getDisplayName().toLowerCase(Locale.ENGLISH));
    }
    for (String sub : UserSubscriptions.sortNoExtras(toSort)) {
        final View convertView = getLayoutInflater().inflate(R.layout.subforsublist, l, false);
        final String subreddit = sub;
        final TextView t = ((TextView) convertView.findViewById(R.id.name));
        t.setText(subreddit);
        convertView.findViewById(R.id.color).setBackgroundResource(R.drawable.circle);
        convertView.findViewById(R.id.color).getBackground().setColorFilter(Palette.getColor(subreddit), PorterDuff.Mode.MULTIPLY);
        convertView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent inte = new Intent(MultiredditOverview.this, SubredditView.class);
                inte.putExtra(SubredditView.EXTRA_SUBREDDIT, subreddit);
                MultiredditOverview.this.startActivityForResult(inte, 4);
            }
        });
        l.addView(convertView);
    }
}
Also used : MultiSubreddit(net.dean.jraw.models.MultiSubreddit) TextView(android.widget.TextView) Intent(android.content.Intent) CaseInsensitiveArrayList(me.ccrama.redditslide.CaseInsensitiveArrayList) MultiReddit(net.dean.jraw.models.MultiReddit) View(android.view.View) TextView(android.widget.TextView) MultiredditView(me.ccrama.redditslide.Fragments.MultiredditView) LinearLayout(android.widget.LinearLayout)

Example 3 with MultiReddit

use of net.dean.jraw.models.MultiReddit in project Slide by ccrama.

the class MultiredditOverview method onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case android.R.id.home:
            try {
                onBackPressed();
            } catch (Exception ignored) {
            }
            return true;
        case R.id.action_edit:
            {
                if (profile.isEmpty() && (UserSubscriptions.multireddits != null) && !UserSubscriptions.multireddits.isEmpty()) {
                    Intent i = new Intent(MultiredditOverview.this, CreateMulti.class);
                    i.putExtra(CreateMulti.EXTRA_MULTI, UserSubscriptions.multireddits.get(pager.getCurrentItem()).getDisplayName());
                    startActivity(i);
                }
            }
            return true;
        case R.id.search:
            {
                UserSubscriptions.MultiCallback m = new UserSubscriptions.MultiCallback() {

                    @Override
                    public void onComplete(List<MultiReddit> multireddits) {
                        if ((multireddits != null) && !multireddits.isEmpty()) {
                            searchMulti = multireddits.get(pager.getCurrentItem());
                            MaterialDialog.Builder builder = new MaterialDialog.Builder(MultiredditOverview.this).title(R.string.search_title).alwaysCallInputCallback().input(getString(R.string.search_msg), "", new MaterialDialog.InputCallback() {

                                @Override
                                public void onInput(MaterialDialog materialDialog, CharSequence charSequence) {
                                    term = charSequence.toString();
                                }
                            });
                            // Add "search current sub" if it is not frontpage/all/random
                            builder.positiveText(getString(R.string.search_subreddit, "/m/" + searchMulti.getDisplayName())).onPositive(new MaterialDialog.SingleButtonCallback() {

                                @Override
                                public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
                                    Intent i = new Intent(MultiredditOverview.this, Search.class);
                                    i.putExtra(Search.EXTRA_TERM, term);
                                    i.putExtra(Search.EXTRA_MULTIREDDIT, searchMulti.getDisplayName());
                                    startActivity(i);
                                }
                            });
                            builder.show();
                        }
                    }
                };
                if (profile.isEmpty()) {
                    UserSubscriptions.getMultireddits(m);
                } else {
                    UserSubscriptions.getPublicMultireddits(m, profile);
                }
            }
            return true;
        case R.id.create:
            if (profile.isEmpty()) {
                Intent i2 = new Intent(MultiredditOverview.this, CreateMulti.class);
                startActivity(i2);
            }
            return true;
        case R.id.action_sort:
            openPopup();
            return true;
        case R.id.subs:
            ((DrawerLayout) findViewById(R.id.drawer_layout)).openDrawer(Gravity.RIGHT);
            return true;
        case R.id.gallery:
            if (SettingValues.tabletUI) {
                List<Submission> posts = ((MultiredditView) adapter.getCurrentFragment()).posts.posts;
                if (posts != null && !posts.isEmpty()) {
                    Intent i2 = new Intent(this, Gallery.class);
                    i2.putExtra(Gallery.EXTRA_PROFILE, profile);
                    i2.putExtra(Gallery.EXTRA_MULTIREDDIT, ((MultiredditView) adapter.getCurrentFragment()).posts.multiReddit.getDisplayName());
                    startActivity(i2);
                }
            } else {
                AlertDialogWrapper.Builder b = new AlertDialogWrapper.Builder(this).setTitle(R.string.general_gallerymode_ispro).setMessage(R.string.pro_upgrade_msg).setPositiveButton(R.string.btn_yes_exclaim, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        try {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=me.ccrama.slideforreddittabletuiunlock")));
                        } catch (ActivityNotFoundException e) {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=me.ccrama.slideforreddittabletuiunlock")));
                        }
                    }
                }).setNegativeButton(R.string.btn_no_danks, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                    }
                });
                if (SettingValues.previews > 0) {
                    b.setNeutralButton(getString(R.string.pro_previews, SettingValues.previews), new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SettingValues.prefs.edit().putInt(SettingValues.PREVIEWS_LEFT, SettingValues.previews - 1).apply();
                            SettingValues.previews = SettingValues.prefs.getInt(SettingValues.PREVIEWS_LEFT, 10);
                            List<Submission> posts = ((MultiredditView) adapter.getCurrentFragment()).posts.posts;
                            if (posts != null && !posts.isEmpty()) {
                                Intent i2 = new Intent(MultiredditOverview.this, Gallery.class);
                                i2.putExtra(Gallery.EXTRA_PROFILE, profile);
                                i2.putExtra(Gallery.EXTRA_MULTIREDDIT, ((MultiredditView) adapter.getCurrentFragment()).posts.multiReddit.getDisplayName());
                                startActivity(i2);
                            }
                        }
                    });
                }
                b.show();
            }
            return true;
        case R.id.action_shadowbox:
            if (SettingValues.tabletUI) {
                List<Submission> posts = ((MultiredditView) adapter.getCurrentFragment()).posts.posts;
                if (posts != null && !posts.isEmpty()) {
                    Intent i = new Intent(this, Shadowbox.class);
                    i.putExtra(Shadowbox.EXTRA_PAGE, getCurrentPage());
                    i.putExtra(Shadowbox.EXTRA_PROFILE, profile);
                    i.putExtra(Shadowbox.EXTRA_MULTIREDDIT, ((MultiredditView) adapter.getCurrentFragment()).posts.multiReddit.getDisplayName());
                    startActivity(i);
                }
            } else {
                AlertDialogWrapper.Builder b = new AlertDialogWrapper.Builder(this).setTitle(R.string.general_shadowbox_ispro).setMessage(R.string.pro_upgrade_msg).setPositiveButton(R.string.btn_yes_exclaim, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        try {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=me.ccrama.slideforreddittabletuiunlock")));
                        } catch (ActivityNotFoundException e) {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=me.ccrama.slideforreddittabletuiunlock")));
                        }
                    }
                }).setNegativeButton(R.string.btn_no_danks, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                    }
                });
                if (SettingValues.previews > 0 && adapter != null && ((MultiredditView) adapter.getCurrentFragment()).posts != null && ((MultiredditView) adapter.getCurrentFragment()).posts.posts != null && !((MultiredditView) adapter.getCurrentFragment()).posts.posts.isEmpty()) {
                    b.setNeutralButton(getString(R.string.pro_previews, SettingValues.previews), new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SettingValues.prefs.edit().putInt(SettingValues.PREVIEWS_LEFT, SettingValues.previews - 1).apply();
                            SettingValues.previews = SettingValues.prefs.getInt(SettingValues.PREVIEWS_LEFT, 10);
                            List<Submission> posts = ((MultiredditView) adapter.getCurrentFragment()).posts.posts;
                            if (posts != null && !posts.isEmpty()) {
                                Intent i = new Intent(MultiredditOverview.this, Shadowbox.class);
                                i.putExtra(Shadowbox.EXTRA_PAGE, getCurrentPage());
                                i.putExtra(Shadowbox.EXTRA_PROFILE, profile);
                                i.putExtra(Shadowbox.EXTRA_MULTIREDDIT, ((MultiredditView) adapter.getCurrentFragment()).posts.multiReddit.getDisplayName());
                                startActivity(i);
                            }
                        }
                    });
                }
                b.show();
            }
            return true;
        default:
            return false;
    }
}
Also used : DialogInterface(android.content.DialogInterface) MultiReddit(net.dean.jraw.models.MultiReddit) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) NonNull(android.support.annotation.NonNull) CaseInsensitiveArrayList(me.ccrama.redditslide.CaseInsensitiveArrayList) List(java.util.List) ArrayList(java.util.ArrayList) DrawerLayout(android.support.v4.widget.DrawerLayout) UserSubscriptions(me.ccrama.redditslide.UserSubscriptions) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Submission(net.dean.jraw.models.Submission) Intent(android.content.Intent) ActivityNotFoundException(android.content.ActivityNotFoundException) ActivityNotFoundException(android.content.ActivityNotFoundException) DialogAction(com.afollestad.materialdialogs.DialogAction) MultiredditView(me.ccrama.redditslide.Fragments.MultiredditView)

Example 4 with MultiReddit

use of net.dean.jraw.models.MultiReddit 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 5 with MultiReddit

use of net.dean.jraw.models.MultiReddit in project Slide by ccrama.

the class MultiredditView method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_verticalcontent, container, false);
    rv = v.findViewById(R.id.vertical_content);
    final RecyclerView.LayoutManager mLayoutManager = createLayoutManager(getNumColumns(getResources().getConfiguration().orientation));
    rv.setLayoutManager(mLayoutManager);
    if (SettingValues.fab) {
        fab = v.findViewById(R.id.post_floating_action_button);
        if (SettingValues.fabType == Constants.FAB_POST) {
            fab.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    final ArrayList<String> subs = new ArrayList<>();
                    for (MultiSubreddit s : posts.multiReddit.getSubreddits()) {
                        subs.add(s.getDisplayName());
                    }
                    new MaterialDialog.Builder(getActivity()).title(R.string.multi_submit_which_sub).items(subs).itemsCallback(new MaterialDialog.ListCallback() {

                        @Override
                        public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                            Intent i = new Intent(getActivity(), Submit.class);
                            i.putExtra(Submit.EXTRA_SUBREDDIT, subs.get(which));
                            startActivity(i);
                        }
                    }).show();
                }
            });
        } else {
            fab.setImageResource(R.drawable.hide);
            fab.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (!Reddit.fabClear) {
                        new AlertDialogWrapper.Builder(getActivity()).setTitle(R.string.settings_fabclear).setMessage(R.string.settings_fabclear_msg).setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Reddit.colors.edit().putBoolean(SettingValues.PREF_FAB_CLEAR, true).apply();
                                Reddit.fabClear = true;
                                clearSeenPosts(false);
                            }
                        }).show();
                    } else {
                        clearSeenPosts(false);
                    }
                }
            });
            fab.setOnLongClickListener(new View.OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    if (!Reddit.fabClear) {
                        new AlertDialogWrapper.Builder(getActivity()).setTitle(R.string.settings_fabclear).setMessage(R.string.settings_fabclear_msg).setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Reddit.colors.edit().putBoolean(SettingValues.PREF_FAB_CLEAR, true).apply();
                                Reddit.fabClear = true;
                                clearSeenPosts(true);
                            }
                        }).show();
                    } else {
                        clearSeenPosts(true);
                    }
                    /*
                        ToDo Make a sncakbar with an undo option of the clear all
                        View.OnClickListener undoAction = new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                adapter.dataSet.posts = original;
                                for(Submission post : adapter.dataSet.posts){
                                    if(HasSeen.getSeen(post.getFullName()))
                                        Hidden.undoHidden(post);
                                }
                            }
                        };*/
                    Snackbar s = Snackbar.make(rv, getResources().getString(R.string.posts_hidden_forever), Snackbar.LENGTH_LONG);
                    View view = s.getView();
                    TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                    tv.setTextColor(Color.WHITE);
                    s.show();
                    return false;
                }
            });
        }
    } else {
        v.findViewById(R.id.post_floating_action_button).setVisibility(View.GONE);
    }
    refreshLayout = v.findViewById(R.id.activity_main_swipe_refresh_layout);
    /**
     * If using List view mode, we need to remove the start margin from the SwipeRefreshLayout.
     * The scrollbar style of "outsideInset" creates a 4dp padding around it. To counter this,
     * change the scrollbar style to "insideOverlay" when list view is enabled.
     * To recap: this removes the margins from the start/end so list view is full-width.
     */
    if (SettingValues.defaultCardView == CreateCardView.CardEnum.LIST) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            params.setMarginStart(0);
        }
        rv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        refreshLayout.setLayoutParams(params);
    }
    List<MultiReddit> multireddits;
    if (profile.isEmpty()) {
        multireddits = UserSubscriptions.multireddits;
    } else {
        multireddits = UserSubscriptions.public_multireddits.get(profile);
    }
    if ((multireddits != null) && !multireddits.isEmpty()) {
        refreshLayout.setColorSchemeColors(Palette.getColors(multireddits.get(id).getDisplayName(), getActivity()));
    }
    // If we use 'findViewById(R.id.header).getMeasuredHeight()', 0 is always returned.
    // So, we estimate the height of the header in dp
    refreshLayout.setProgressViewOffset(false, Constants.TAB_HEADER_VIEW_OFFSET - Constants.PTR_OFFSET_TOP, Constants.TAB_HEADER_VIEW_OFFSET + Constants.PTR_OFFSET_BOTTOM);
    refreshLayout.post(new Runnable() {

        @Override
        public void run() {
            refreshLayout.setRefreshing(true);
        }
    });
    if ((multireddits != null) && !multireddits.isEmpty()) {
        posts = new MultiredditPosts(multireddits.get(id).getDisplayName(), profile);
        adapter = new MultiredditAdapter(getActivity(), posts, rv, refreshLayout, this);
        rv.setAdapter(adapter);
        rv.setItemAnimator(new SlideUpAlphaAnimator());
        posts.loadMore(getActivity(), this, true, adapter);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                posts.loadMore(getActivity(), MultiredditView.this, true, adapter);
            // TODO catch errors
            }
        });
        if (fab != null) {
            fab.show();
        }
        rv.addOnScrollListener(new ToolbarScrollHideHandler((Toolbar) (getActivity()).findViewById(R.id.toolbar), getActivity().findViewById(R.id.header)) {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                visibleItemCount = rv.getLayoutManager().getChildCount();
                totalItemCount = rv.getLayoutManager().getItemCount();
                int[] firstVisibleItems;
                firstVisibleItems = ((CatchStaggeredGridLayoutManager) rv.getLayoutManager()).findFirstVisibleItemPositions(null);
                if (firstVisibleItems != null && firstVisibleItems.length > 0) {
                    for (int firstVisibleItem : firstVisibleItems) {
                        pastVisiblesItems = firstVisibleItem;
                        if (SettingValues.scrollSeen && pastVisiblesItems > 0 && SettingValues.storeHistory) {
                            HasSeen.addSeenScrolling(posts.posts.get(pastVisiblesItems - 1).getFullName());
                        }
                    }
                }
                if (!posts.loading) {
                    if ((visibleItemCount + pastVisiblesItems) + 5 >= totalItemCount && !posts.nomore) {
                        posts.loading = true;
                        posts.loadMore(getActivity(), MultiredditView.this, false, adapter);
                    }
                }
                if (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) {
                    diff += dy;
                } else {
                    diff = 0;
                }
                if (fab != null) {
                    if (dy <= 0 && fab.getId() != 0 && SettingValues.fab) {
                        if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_DRAGGING || diff < -fab.getHeight() * 2)
                            fab.show();
                    } else {
                        fab.hide();
                    }
                }
            }
        });
    }
    return v;
}
Also used : CatchStaggeredGridLayoutManager(me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager) DialogInterface(android.content.DialogInterface) ArrayList(java.util.ArrayList) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) MultiReddit(net.dean.jraw.models.MultiReddit) SwipeRefreshLayout(android.support.v4.widget.SwipeRefreshLayout) SlideUpAlphaAnimator(com.mikepenz.itemanimators.SlideUpAlphaAnimator) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) TextView(android.widget.TextView) ToolbarScrollHideHandler(me.ccrama.redditslide.handler.ToolbarScrollHideHandler) Toolbar(android.support.v7.widget.Toolbar) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Intent(android.content.Intent) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) TextView(android.widget.TextView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) MultiredditPosts(me.ccrama.redditslide.Adapters.MultiredditPosts) RelativeLayout(android.widget.RelativeLayout) Submit(me.ccrama.redditslide.Activities.Submit) RecyclerView(android.support.v7.widget.RecyclerView) MultiredditAdapter(me.ccrama.redditslide.Adapters.MultiredditAdapter) Snackbar(android.support.design.widget.Snackbar)

Aggregations

MultiReddit (net.dean.jraw.models.MultiReddit)8 MultiSubreddit (net.dean.jraw.models.MultiSubreddit)7 View (android.view.View)6 TextView (android.widget.TextView)6 DialogInterface (android.content.DialogInterface)5 Intent (android.content.Intent)5 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)5 AlertDialogWrapper (com.afollestad.materialdialogs.AlertDialogWrapper)4 ArrayList (java.util.ArrayList)4 CaseInsensitiveArrayList (me.ccrama.redditslide.CaseInsensitiveArrayList)4 ActivityNotFoundException (android.content.ActivityNotFoundException)3 Snackbar (android.support.design.widget.Snackbar)3 RecyclerView (android.support.v7.widget.RecyclerView)3 ApiException (net.dean.jraw.ApiException)3 NetworkException (net.dean.jraw.http.NetworkException)3 MultiRedditManager (net.dean.jraw.managers.MultiRedditManager)3 AsyncTask (android.os.AsyncTask)2 AppCompatCheckBox (android.support.v7.widget.AppCompatCheckBox)2 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)2 CompoundButton (android.widget.CompoundButton)2