Search in sources :

Example 11 with Build

use of android.os.Build in project AntennaPod by AntennaPod.

the class ProxyDialog method test.

private void test() {
    if (disposable != null) {
        disposable.dispose();
    }
    if (!checkValidity()) {
        setTestRequired(true);
        return;
    }
    TypedArray res = context.getTheme().obtainStyledAttributes(new int[] { android.R.attr.textColorPrimary });
    int textColorPrimary = res.getColor(0, 0);
    res.recycle();
    String checking = context.getString(R.string.proxy_checking);
    txtvMessage.setTextColor(textColorPrimary);
    txtvMessage.setText("{fa-circle-o-notch spin} " + checking);
    txtvMessage.setVisibility(View.VISIBLE);
    disposable = Completable.create(emitter -> {
        String type = (String) spType.getSelectedItem();
        String host = etHost.getText().toString();
        String port = etPort.getText().toString();
        String username = etUsername.getText().toString();
        String password = etPassword.getText().toString();
        int portValue = 8080;
        if (!TextUtils.isEmpty(port)) {
            portValue = Integer.parseInt(port);
        }
        SocketAddress address = InetSocketAddress.createUnresolved(host, portValue);
        Proxy.Type proxyType = Proxy.Type.valueOf(type.toUpperCase(Locale.US));
        OkHttpClient.Builder builder = AntennapodHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS).proxy(new Proxy(proxyType, address));
        if (!TextUtils.isEmpty(username)) {
            builder.proxyAuthenticator((route, response) -> {
                String credentials = Credentials.basic(username, password);
                return response.request().newBuilder().header("Proxy-Authorization", credentials).build();
            });
        }
        OkHttpClient client = builder.build();
        Request request = new Request.Builder().url("https://www.example.com").head().build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                emitter.onComplete();
            } else {
                emitter.onError(new IOException(response.message()));
            }
        } catch (IOException e) {
            emitter.onError(e);
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(() -> {
        txtvMessage.setTextColor(ContextCompat.getColor(context, R.color.download_success_green));
        String message = String.format("%s %s", "{fa-check}", context.getString(R.string.proxy_test_successful));
        txtvMessage.setText(message);
        setTestRequired(false);
    }, error -> {
        error.printStackTrace();
        txtvMessage.setTextColor(ContextCompat.getColor(context, R.color.download_failed_red));
        String message = String.format("%s %s: %s", "{fa-close}", context.getString(R.string.proxy_test_failed), error.getMessage());
        txtvMessage.setText(message);
        setTestRequired(true);
    });
}
Also used : Context(android.content.Context) AlertDialog(androidx.appcompat.app.AlertDialog) SocketAddress(java.net.SocketAddress) Completable(io.reactivex.Completable) Dialog(android.app.Dialog) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) Editable(android.text.Editable) TypedArray(android.content.res.TypedArray) ArrayList(java.util.ArrayList) UserPreferences(de.danoeh.antennapod.core.preferences.UserPreferences) Patterns(android.util.Patterns) Proxy(java.net.Proxy) Locale(java.util.Locale) View(android.view.View) Response(okhttp3.Response) Schedulers(io.reactivex.schedulers.Schedulers) AdapterView(android.widget.AdapterView) Build(android.os.Build) ContextCompat(androidx.core.content.ContextCompat) AntennapodHttpClient(de.danoeh.antennapod.core.service.download.AntennapodHttpClient) Request(okhttp3.Request) R(de.danoeh.antennapod.R) TextUtils(android.text.TextUtils) IOException(java.io.IOException) Credentials(okhttp3.Credentials) InetSocketAddress(java.net.InetSocketAddress) ProxyConfig(de.danoeh.antennapod.core.service.download.ProxyConfig) Spinner(android.widget.Spinner) TimeUnit(java.util.concurrent.TimeUnit) ArrayAdapter(android.widget.ArrayAdapter) List(java.util.List) Disposable(io.reactivex.disposables.Disposable) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) EditText(android.widget.EditText) TextWatcher(android.text.TextWatcher) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Response(okhttp3.Response) Proxy(java.net.Proxy) TypedArray(android.content.res.TypedArray) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 12 with Build

use of android.os.Build in project kcanotify by antest1.

the class UpdateCheckActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rescheck);
    Intent intent = this.getIntent();
    if (intent != null && intent.getExtras() != null) {
        main_flag = intent.getExtras().getBoolean("main_flag", false);
    }
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(getResources().getString(R.string.setting_menu_kand_title_game_data_down));
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    dbHelper = new KcaDBHelper(getApplicationContext(), null, KCANOTIFY_DB_VERSION);
    KcaApiData.setDBHelper(dbHelper);
    downloader = KcaUtils.getInfoDownloader(getApplicationContext());
    FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(getApplicationContext()).setDownloadConcurrentLimit(80).build();
    fetch = Fetch.Impl.getInstance(fetchConfiguration);
    handler = new UpdateHandler(this);
    gamedata_adapter.setHandler(handler);
    resource_adapter.setHandler(handler);
    checkstart_chkbox = findViewById(R.id.reschk_checkatstart);
    checkstart_chkbox.setText(getStringWithLocale(R.string.download_setting_checkatstart));
    checkstart_chkbox.setChecked(getBooleanPreferences(getApplicationContext(), PREF_CHECK_UPDATE_START));
    checkstart_chkbox.setOnCheckedChangeListener((buttonView, isChecked) -> setPreferences(getApplicationContext(), PREF_CHECK_UPDATE_START, isChecked));
    localonly_chkbox = findViewById(R.id.reschk_local);
    localonly_chkbox.setText(getStringWithLocale(R.string.download_use_internal_data));
    localonly_chkbox.setChecked(getBooleanPreferences(getApplicationContext(), PREF_RES_USELOCAL));
    localonly_chkbox.setOnCheckedChangeListener((buttonView, isChecked) -> setPreferences(getApplicationContext(), PREF_RES_USELOCAL, isChecked));
    resource_reset = findViewById(R.id.reschk_reset);
    resource_reset.setText(getStringWithLocale(R.string.download_reset));
    resource_reset.setOnCheckedChangeListener((buttonView, isChecked) -> {
        if (isChecked) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(UpdateCheckActivity.this);
            alertDialog.setMessage(getString(R.string.download_reset_message));
            alertDialog.setPositiveButton(getStringWithLocale(R.string.dialog_ok), (dialog, which) -> {
                dbHelper.clearResVer();
                setPreferences(getApplicationContext(), PREF_KCARESOURCE_VERSION, 0);
                Intent mainIntent = new Intent(this, InitStartActivity.class);
                mainIntent.putExtra(ACTION_RESET, true);
                startActivity(mainIntent);
                finish();
            });
            alertDialog.setNegativeButton(getStringWithLocale(R.string.dialog_cancel), (dialog, which) -> {
                resource_reset.setChecked(false);
                dialog.dismiss();
            });
            AlertDialog alert = alertDialog.create();
            alert.setIcon(R.mipmap.ic_launcher);
            alert.show();
        }
    });
    data_list = findViewById(R.id.gamedata_list);
    resource_list = findViewById(R.id.resources_list);
    data_list.setAdapter(gamedata_adapter);
    resource_list.setAdapter(resource_adapter);
    gamedata_load = findViewById(R.id.gamedata_loading);
    resource_load = findViewById(R.id.resources_loading);
    gamedata_chk = findViewById(R.id.gamedata_updatecheck);
    resource_chk = findViewById(R.id.resources_updatecheck);
    resource_downall = findViewById(R.id.resources_downloadall);
    gamedata_chk.setOnClickListener(v -> checkVersionUpdate());
    resource_chk.setOnClickListener(v -> checkResourceUpdate());
    resource_downall.setOnClickListener(v -> downloadAllResources());
    resource_downall.setVisibility(View.GONE);
    gamedata_server = findViewById(R.id.gamedata_server);
    gamedata_server.setText(getStringWithLocale(R.string.action_server));
    gamedata_server.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int initValue = checked;
            String[] listItems = getResources().getStringArray(R.array.ServerLocation);
            String[] listEntry = getResources().getStringArray(R.array.ServerLocationValue);
            AlertDialog.Builder mBuilder = new AlertDialog.Builder(UpdateCheckActivity.this);
            mBuilder.setTitle(getStringWithLocale(R.string.setting_menu_app_title_updatecheckserver));
            String currentServer = getStringPreferences(getApplicationContext(), PREF_UPDATE_SERVER);
            for (int i = 0; i < listEntry.length; i++) if (currentServer.equals(listEntry[i])) {
                checked = i;
                break;
            }
            mBuilder.setSingleChoiceItems(listItems, checked, (dialog, which) -> {
                checked = which;
            });
            mBuilder.setPositiveButton(getStringWithLocale(R.string.dialog_ok), (dialog, which) -> {
                Log.e("KCA", "selected: " + checked);
                if (checked != -1) {
                    String selectedServer = listEntry[checked];
                    setPreferences(getApplicationContext(), PREF_UPDATE_SERVER, selectedServer);
                }
            });
            mBuilder.setNegativeButton(getStringWithLocale(R.string.dialog_cancel), ((dialog, which) -> {
                checked = initValue;
            }));
            AlertDialog mDialog = mBuilder.create();
            mDialog.show();
        }
    });
    checkVersionUpdate();
    checkResourceUpdate();
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) JsonObject(com.google.gson.JsonObject) Bundle(android.os.Bundle) TypeToken(com.google.gson.reflect.TypeToken) NonNull(androidx.annotation.NonNull) FetchListener(com.tonyodev.fetch2.FetchListener) PREF_KCARESOURCE_VERSION(com.antest1.kcanotify.KcaConstants.PREF_KCARESOURCE_VERSION) PREF_RES_USELOCAL(com.antest1.kcanotify.KcaConstants.PREF_RES_USELOCAL) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) CheckBox(android.widget.CheckBox) Gson(com.google.gson.Gson) Locale(java.util.Locale) DB_KEY_STARTDATA(com.antest1.kcanotify.KcaConstants.DB_KEY_STARTDATA) Handler(android.os.Handler) View(android.view.View) PREF_CHECK_UPDATE_START(com.antest1.kcanotify.KcaConstants.PREF_CHECK_UPDATE_START) ERROR_TYPE_SETTING(com.antest1.kcanotify.KcaConstants.ERROR_TYPE_SETTING) Log(android.util.Log) AsyncTask(android.os.AsyncTask) KcaApiData.loadTranslationData(com.antest1.kcanotify.KcaApiData.loadTranslationData) KcaUtils.getStringPreferences(com.antest1.kcanotify.KcaUtils.getStringPreferences) FetchConfiguration(com.tonyodev.fetch2.FetchConfiguration) JsonArray(com.google.gson.JsonArray) List(java.util.List) KcaUtils.getStringFromException(com.antest1.kcanotify.KcaUtils.getStringFromException) TextView(android.widget.TextView) Message(android.os.Message) Type(java.lang.reflect.Type) KcaUtils.compareVersion(com.antest1.kcanotify.KcaUtils.compareVersion) Toolbar(androidx.appcompat.widget.Toolbar) ListView(android.widget.ListView) Download(com.tonyodev.fetch2.Download) NotNull(org.jetbrains.annotations.NotNull) Call(retrofit2.Call) KcaUtils.getBooleanPreferences(com.antest1.kcanotify.KcaUtils.getBooleanPreferences) Fetch(com.tonyodev.fetch2.Fetch) Context(android.content.Context) AlertDialog(androidx.appcompat.app.AlertDialog) Intent(android.content.Intent) KCANOTIFY_DB_VERSION(com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION) Response(retrofit2.Response) JsonParser(com.google.gson.JsonParser) ACTION_RESET(com.antest1.kcanotify.InitStartActivity.ACTION_RESET) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) PREF_UPDATE_SERVER(com.antest1.kcanotify.KcaConstants.PREF_UPDATE_SERVER) Toast(android.widget.Toast) PREF_KCA_LANGUAGE(com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE) PREF_KCA_DATA_VERSION(com.antest1.kcanotify.KcaConstants.PREF_KCA_DATA_VERSION) ContextWrapper(android.content.ContextWrapper) Build(android.os.Build) WeakReference(java.lang.ref.WeakReference) PREF_KCA_VERSION(com.antest1.kcanotify.KcaConstants.PREF_KCA_VERSION) RESCHK_KEY(com.antest1.kcanotify.KcaResCheckItemAdpater.RESCHK_KEY) ProgressDialog(android.app.ProgressDialog) File(java.io.File) PREF_FAIRY_DOWN_FLAG(com.antest1.kcanotify.KcaConstants.PREF_FAIRY_DOWN_FLAG) Callback(retrofit2.Callback) Configuration(android.content.res.Configuration) KcaUtils.setPreferences(com.antest1.kcanotify.KcaUtils.setPreferences) Request(com.tonyodev.fetch2.Request) Activity(android.app.Activity) Intent(android.content.Intent) FetchConfiguration(com.tonyodev.fetch2.FetchConfiguration) View(android.view.View) TextView(android.widget.TextView) ListView(android.widget.ListView)

Example 13 with Build

use of android.os.Build in project TumCampusApp by TCA-Team.

the class Helper method getOkClient.

public static OkHttpClient getOkClient(Context c) {
    if (client != null) {
        return client;
    }
    final CertificatePinner certificatePinner = new CertificatePinner.Builder().add(API_HOSTNAME, // Fakultaet fuer Informatik
    "sha256/dVphPQ9xG7woPpEKXrNalw4eMUQ4Fw9r3OXTzxfuL5A=").add(API_HOSTNAME, // Technische Universitaet Muenchen
    "sha256/SwdQoHL7SB/6o12XsIhbQJ9bANVnbrJoHTLzlu/qXT0=").add(API_HOSTNAME, // DFN-Verein PCA Global
    "sha256/VzL+FtAKvzb4N5igmFJyv83GD7CBK7Yyw+R6XdRRfmg=").add(API_HOSTNAME, // Deutsche Telekom Root CA 2
    "sha256/0d4q5hyN8vpiOWYWPUxz1GC/xCjldYW+a/65pWMj0bY=").add(API_HOSTNAME, // Let's Encrypt Authority X3
    "sha256/YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=").add(API_HOSTNAME, // LE Cross Sign: DST Root CA X3
    "sha256/Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=").add(API_HOSTNAME_NEW, // Fakultaet fuer Informatik
    "sha256/dVphPQ9xG7woPpEKXrNalw4eMUQ4Fw9r3OXTzxfuL5A=").add(API_HOSTNAME_NEW, // Technische Universitaet Muenchen
    "sha256/SwdQoHL7SB/6o12XsIhbQJ9bANVnbrJoHTLzlu/qXT0=").add(API_HOSTNAME_NEW, // DFN-Verein PCA Global
    "sha256/VzL+FtAKvzb4N5igmFJyv83GD7CBK7Yyw+R6XdRRfmg=").add(API_HOSTNAME_NEW, // Deutsche Telekom Root CA 2
    "sha256/0d4q5hyN8vpiOWYWPUxz1GC/xCjldYW+a/65pWMj0bY=").add(API_HOSTNAME_NEW, // Let's Encrypt Authority X3
    "sha256/YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=").add(API_HOSTNAME_NEW, // LE Cross Sign: DST Root CA X3
    "sha256/Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=").add(STUDYROOM_HOST, // wwwv2.tum.de
    "sha256/dVphPQ9xG7woPpEKXrNalw4eMUQ4Fw9r3OXTzxfuL5A=").add(STUDYROOM_HOST, // wwwv4.tum.de
    "sha256/K64RzAqr/RSxwfpHN6fe0DcmdaIVmzAyi511ufYaK1s=").add(STUDYROOM_HOST, // Zertifizierungsstelle der TUM
    "sha256/SwdQoHL7SB/6o12XsIhbQJ9bANVnbrJoHTLzlu/qXT0=").add(STUDYROOM_HOST, // DFN-Verein PCA Global - G01
    "sha256/VzL+FtAKvzb4N5igmFJyv83GD7CBK7Yyw+R6XdRRfmg=").add(STUDYROOM_HOST, // Deutsche Telekom Root CA 2
    "sha256/0d4q5hyN8vpiOWYWPUxz1GC/xCjldYW+a/65pWMj0bY=").build();
    // We want to persist our cookies through app session
    ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(c));
    // Start building the http client
    OkHttpClient.Builder builder = new OkHttpClient.Builder().cookieJar(cookieJar).certificatePinner(certificatePinner);
    // Add the device identifying header
    builder.addInterceptor(Helper.getDeviceInterceptor(c));
    builder.connectTimeout(Helper.HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.readTimeout(Helper.HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.addNetworkInterceptor(new TumHttpLoggingInterceptor(message -> Utils.logwithTag(TAG, message)));
    // Save it to the static handle and return
    client = builder.build();
    return client;
}
Also used : Context(android.content.Context) Interceptor(okhttp3.Interceptor) SetCookieCache(com.franmontiel.persistentcookiejar.cache.SetCookieCache) Request(okhttp3.Request) PersistentCookieJar(com.franmontiel.persistentcookiejar.PersistentCookieJar) API_HOSTNAME_NEW(de.tum.in.tumcampusapp.utils.Const.API_HOSTNAME_NEW) PackageManager(android.content.pm.PackageManager) SharedPrefsCookiePersistor(com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor) STUDYROOM_HOST(de.tum.in.tumcampusapp.component.ui.studyroom.StudyRoomGroupManager.STUDYROOM_HOST) UrlEscapers(com.google.common.net.UrlEscapers) CertificatePinner(okhttp3.CertificatePinner) ClearableCookieJar(com.franmontiel.persistentcookiejar.ClearableCookieJar) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) Utils(de.tum.in.tumcampusapp.utils.Utils) API_HOSTNAME(de.tum.in.tumcampusapp.utils.Const.API_HOSTNAME) Build(android.os.Build) ClearableCookieJar(com.franmontiel.persistentcookiejar.ClearableCookieJar) OkHttpClient(okhttp3.OkHttpClient) PersistentCookieJar(com.franmontiel.persistentcookiejar.PersistentCookieJar) CertificatePinner(okhttp3.CertificatePinner) SetCookieCache(com.franmontiel.persistentcookiejar.cache.SetCookieCache) SharedPrefsCookiePersistor(com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor)

Example 14 with Build

use of android.os.Build 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 = StringUtil.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.containsKey(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[0])[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);
                                                        LayoutUtils.showSnackbar(s);
                                                    }
                                                });
                                            } 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, null).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 AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.sub_post_notifs_title, sub)).setMessage(R.string.sub_post_notifs_msg).setPositiveButton(R.string.btn_ok, (dialog, 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 = StringUtil.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
                                subs.add(sub + ":" + text);
                                Reddit.appRestart.edit().putString(CheckForMail.SUBS_TO_GET, StringUtil.arrayToString(subs)).commit();
                                return true;
                            }
                        }).cancelable(false).show()).setNegativeButton(R.string.btn_cancel, null).setNegativeButton(R.string.btn_cancel, (dialog, which) -> notifyStateCheckBox.setChecked(false)).setOnCancelListener(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();
        MiscUtil.doSubscribeButtonText(currentlySubbed, subscribe);
        assert subscribe != null;
        subscribe.setOnClickListener(new View.OnClickListener() {

            private void doSubscribe() {
                if (Authentication.isLoggedIn) {
                    new AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.subscribe_to, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_add_subscribe, (dialog, which) -> new AsyncTask<Void, Void, Boolean>() {

                        @Override
                        public void onPostExecute(Boolean success) {
                            if (!success) {
                                // If subreddit was removed from account or not
                                new AlertDialog.Builder(MainActivity.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, (dialog1, which1) -> {
                                    // Force add the subscription
                                    changeSubscription(subreddit, true);
                                    Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_subscribed), Snackbar.LENGTH_LONG);
                                    LayoutUtils.showSnackbar(s);
                                }).setNegativeButton(R.string.btn_no, null).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, (dialog, which) -> {
                        // Force add the subscription
                        changeSubscription(subreddit, true);
                        Snackbar s = Snackbar.make(mToolbar, R.string.sub_added, Snackbar.LENGTH_LONG);
                        LayoutUtils.showSnackbar(s);
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                } else {
                    changeSubscription(subreddit, true);
                }
            }

            private void doUnsubscribe() {
                if (Authentication.didOnline) {
                    new AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.unsubscribe_from, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_remove_unsubscribe, (dialog, which) -> new AsyncTask<Void, Void, Boolean>() {

                        @Override
                        public void onPostExecute(Boolean success) {
                            if (!success) {
                                // If subreddit was removed from account or not
                                new AlertDialog.Builder(MainActivity.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, (dialog12, which12) -> {
                                    // Force add the subscription
                                    changeSubscription(subreddit, false);
                                    Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_unsubscribed), Snackbar.LENGTH_LONG);
                                    LayoutUtils.showSnackbar(s);
                                }).setNegativeButton(R.string.btn_no, null).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, (dialog, which) -> {
                        // Force add the subscription
                        changeSubscription(subreddit, false);
                        Snackbar s = Snackbar.make(mToolbar, R.string.misc_unsubscribed, Snackbar.LENGTH_LONG);
                        LayoutUtils.showSnackbar(s);
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                } else {
                    changeSubscription(subreddit, false);
                }
            }

            @Override
            public void onClick(View v) {
                if (!currentlySubbed) {
                    doSubscribe();
                } else {
                    doUnsubscribe();
                }
                MiscUtil.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);
    }
    String bannerImage = subreddit.getBannerImage();
    if (bannerImage != null && !bannerImage.isEmpty()) {
        findViewById(R.id.sub_banner).setVisibility(View.VISIBLE);
        ((Reddit) getApplication()).getImageLoader().displayImage(bannerImage, (ImageView) findViewById(R.id.sub_banner));
    } else {
        findViewById(R.id.sub_banner).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 : AlertDialog(androidx.appcompat.app.AlertDialog) Arrays(java.util.Arrays) Bundle(android.os.Bundle) R(me.ccrama.redditslide.R) NonNull(androidx.annotation.NonNull) AnimatorUtil(me.ccrama.redditslide.util.AnimatorUtil) Uri(android.net.Uri) ImageView(android.widget.ImageView) PostMatch(me.ccrama.redditslide.PostMatch) ColorDrawable(android.graphics.drawable.ColorDrawable) ContentType(me.ccrama.redditslide.ContentType) AppCompatCheckBox(androidx.appcompat.widget.AppCompatCheckBox) UserRecordPaginator(net.dean.jraw.paginators.UserRecordPaginator) NeverAgainWhenClickedOnce(org.ligi.snackengage.conditions.NeverAgainWhenClickedOnce) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) ShortcutManagerCompat(androidx.core.content.pm.ShortcutManagerCompat) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) Manifest(android.Manifest) Handler(android.os.Handler) Map(java.util.Map) Fragment(androidx.fragment.app.Fragment) ClipboardManager(android.content.ClipboardManager) Canvas(android.graphics.Canvas) JsonNode(com.fasterxml.jackson.databind.JsonNode) ContextCompat(androidx.core.content.ContextCompat) ProUtil(me.ccrama.redditslide.util.ProUtil) Log(android.util.Log) CardView(androidx.cardview.widget.CardView) WithLimitedNumberOfTimes(org.ligi.snackengage.conditions.WithLimitedNumberOfTimes) SubredditPosts(me.ccrama.redditslide.Adapters.SubredditPosts) CheckForMail(me.ccrama.redditslide.Notifications.CheckForMail) KeyboardUtil(me.ccrama.redditslide.util.KeyboardUtil) IntentFilter(android.content.IntentFilter) CommentPage(me.ccrama.redditslide.Fragments.CommentPage) SidebarLayout(me.ccrama.redditslide.Views.SidebarLayout) Set(java.util.Set) DensityUtils(me.ccrama.redditslide.ForceTouch.util.DensityUtils) NotificationJobScheduler(me.ccrama.redditslide.Notifications.NotificationJobScheduler) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) Palette(me.ccrama.redditslide.Visuals.Palette) SimpleTextWatcher(me.ccrama.redditslide.util.stubs.SimpleTextWatcher) SubredditPaginator(net.dean.jraw.paginators.SubredditPaginator) Executors(java.util.concurrent.Executors) CatchStaggeredGridLayoutManager(me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager) SortingUtil(me.ccrama.redditslide.util.SortingUtil) KVManger(com.lusfold.androidkeyvaluestore.core.KVManger) DrawerItemsDialog(me.ccrama.redditslide.Fragments.DrawerItemsDialog) DrawableUtil(me.ccrama.redditslide.util.DrawableUtil) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) BuildConfig(me.ccrama.redditslide.BuildConfig) SubmissionParser(me.ccrama.redditslide.util.SubmissionParser) AfterNumberOfOpportunities(org.ligi.snackengage.conditions.AfterNumberOfOpportunities) ViewDragHelper(androidx.customview.widget.ViewDragHelper) DrawerLayout(androidx.drawerlayout.widget.DrawerLayout) BaseSnack(org.ligi.snackengage.snacks.BaseSnack) HasSeen(me.ccrama.redditslide.HasSeen) ViewPager(androidx.viewpager.widget.ViewPager) Dialog(android.app.Dialog) Editable(android.text.Editable) AccountManager(net.dean.jraw.managers.AccountManager) ArrayList(java.util.ArrayList) MiscUtil(me.ccrama.redditslide.util.MiscUtil) MenuInflater(android.view.MenuInflater) Toast(android.widget.Toast) Menu(android.view.Menu) UserSubscriptions(me.ccrama.redditslide.UserSubscriptions) OpenRedditLink(me.ccrama.redditslide.OpenRedditLink) MultiRedditUpdateRequest(net.dean.jraw.http.MultiRedditUpdateRequest) TimePeriod(net.dean.jraw.paginators.TimePeriod) SettingsThemeFragment(me.ccrama.redditslide.ui.settings.SettingsThemeFragment) StringUtil(me.ccrama.redditslide.util.StringUtil) FragmentManager(androidx.fragment.app.FragmentManager) SettingsSubAdapter(me.ccrama.redditslide.ui.settings.SettingsSubAdapter) Parcelable(android.os.Parcelable) FlairTemplate(net.dean.jraw.models.FlairTemplate) UserSubscriptions.modOf(me.ccrama.redditslide.UserSubscriptions.modOf) Reddit(me.ccrama.redditslide.Reddit) ColorPreferences(me.ccrama.redditslide.Visuals.ColorPreferences) Field(java.lang.reflect.Field) AutoCompleteTextView(android.widget.AutoCompleteTextView) MultiRedditManager(net.dean.jraw.managers.MultiRedditManager) ContextThemeWrapper(androidx.appcompat.view.ContextThemeWrapper) Gravity(android.view.Gravity) MySynccitUpdateTask(me.ccrama.redditslide.Synccit.MySynccitUpdateTask) SharedPreferences(android.content.SharedPreferences) IconCompat(androidx.core.graphics.drawable.IconCompat) Configuration(android.content.res.Configuration) EditText(android.widget.EditText) ValueAnimator(android.animation.ValueAnimator) LinearLayout(android.widget.LinearLayout) ToggleSwipeViewPager(me.ccrama.redditslide.Views.ToggleSwipeViewPager) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) CommentCacheAsync(me.ccrama.redditslide.CommentCacheAsync) SideArrayAdapter(me.ccrama.redditslide.Adapters.SideArrayAdapter) PackageManager(android.content.pm.PackageManager) TimeUtils(me.ccrama.redditslide.util.TimeUtils) EditTextValidator(me.ccrama.redditslide.util.EditTextValidator) Spannable(android.text.Spannable) WindowManager(android.view.WindowManager) SettingsGeneralFragment(me.ccrama.redditslide.ui.settings.SettingsGeneralFragment) Animator(android.animation.Animator) DrawableRes(androidx.annotation.DrawableRes) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) AccelerateDecelerateInterpolator(android.view.animation.AccelerateDecelerateInterpolator) ActionBarDrawerToggle(androidx.appcompat.app.ActionBarDrawerToggle) Locale(java.util.Locale) View(android.view.View) Sorting(net.dean.jraw.paginators.Sorting) SynccitRead(me.ccrama.redditslide.Synccit.SynccitRead) ArgbEvaluator(android.animation.ArgbEvaluator) FragmentStatePagerAdapter(androidx.fragment.app.FragmentStatePagerAdapter) AutoCacheScheduler(me.ccrama.redditslide.Autocache.AutoCacheScheduler) CaseInsensitiveArrayList(me.ccrama.redditslide.CaseInsensitiveArrayList) NetworkStateReceiver(me.ccrama.redditslide.util.NetworkStateReceiver) NotificationManager(android.app.NotificationManager) AsyncTask(android.os.AsyncTask) TabLayout(com.google.android.material.tabs.TabLayout) Authentication(me.ccrama.redditslide.Authentication) ApiException(net.dean.jraw.ApiException) ViewGroup(android.view.ViewGroup) List(java.util.List) NetworkUtil(me.ccrama.redditslide.util.NetworkUtil) TextView(android.widget.TextView) LinearInterpolator(android.view.animation.LinearInterpolator) RelativeLayout(android.widget.RelativeLayout) Toolbar(androidx.appcompat.widget.Toolbar) ListView(android.widget.ListView) CommentOverflow(me.ccrama.redditslide.Views.CommentOverflow) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) EditorInfo(android.view.inputmethod.EditorInfo) Snackbar(com.google.android.material.snackbar.Snackbar) RequestPermission(androidx.activity.result.contract.ActivityResultContracts.RequestPermission) LayoutUtils(me.ccrama.redditslide.util.LayoutUtils) Context(android.content.Context) SettingValues(me.ccrama.redditslide.SettingValues) KeyEvent(android.view.KeyEvent) AlertDialog(androidx.appcompat.app.AlertDialog) ResourcesCompat(androidx.core.content.res.ResourcesCompat) ModerationManager(net.dean.jraw.managers.ModerationManager) Submission(net.dean.jraw.models.Submission) Pair(android.util.Pair) Intent(android.content.Intent) HashMap(java.util.HashMap) Constants(me.ccrama.redditslide.Constants) PreCachingLayoutManager(me.ccrama.redditslide.Views.PreCachingLayoutManager) LogUtil(me.ccrama.redditslide.util.LogUtil) MenuItem(android.view.MenuItem) InputMethodManager(android.view.inputmethod.InputMethodManager) ClipData(android.content.ClipData) HashSet(java.util.HashSet) UserRecord(net.dean.jraw.models.UserRecord) ManageOfflineContent(me.ccrama.redditslide.ui.settings.ManageOfflineContent) Build(android.os.Build) ShortcutInfoCompat(androidx.core.content.pm.ShortcutInfoCompat) ExecutorService(java.util.concurrent.ExecutorService) DialogInterface(android.content.DialogInterface) RateSnack(org.ligi.snackengage.snacks.RateSnack) ViewStub(android.view.ViewStub) MultiReddit(net.dean.jraw.models.MultiReddit) SwitchCompat(androidx.appcompat.widget.SwitchCompat) CompoundButton(android.widget.CompoundButton) ActivityResultLauncher(androidx.activity.result.ActivityResultLauncher) LayoutInflater(android.view.LayoutInflater) ImageFlairs(me.ccrama.redditslide.ImageFlairs) GravityCompat(androidx.core.view.GravityCompat) KVStore(com.lusfold.androidkeyvaluestore.KVStore) Point(android.graphics.Point) DialogAction(com.afollestad.materialdialogs.DialogAction) SnackEngage(org.ligi.snackengage.SnackEngage) ResolveInfo(android.content.pm.ResolveInfo) PopupMenu(androidx.appcompat.widget.PopupMenu) ImageUtil(me.ccrama.redditslide.util.ImageUtil) SettingsActivity(me.ccrama.redditslide.ui.settings.SettingsActivity) Bitmap(android.graphics.Bitmap) ViewTreeObserver(android.view.ViewTreeObserver) Subreddit(net.dean.jraw.models.Subreddit) Activity(android.app.Activity) NetworkException(net.dean.jraw.http.NetworkException) Collections(java.util.Collections) LoggedInAccount(net.dean.jraw.models.LoggedInAccount) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CaseInsensitiveArrayList(me.ccrama.redditslide.CaseInsensitiveArrayList) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) MultiReddit(net.dean.jraw.models.MultiReddit) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) MultiRedditUpdateRequest(net.dean.jraw.http.MultiRedditUpdateRequest) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) TextView(android.widget.TextView) ImageView(android.widget.ImageView) NetworkException(net.dean.jraw.http.NetworkException) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) ImageView(android.widget.ImageView) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) CardView(androidx.cardview.widget.CardView) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) View(android.view.View) TextView(android.widget.TextView) ListView(android.widget.ListView) ApiException(net.dean.jraw.ApiException) NetworkException(net.dean.jraw.http.NetworkException) Point(android.graphics.Point) AppCompatCheckBox(androidx.appcompat.widget.AppCompatCheckBox) MultiRedditManager(net.dean.jraw.managers.MultiRedditManager) AccountManager(net.dean.jraw.managers.AccountManager) CompoundButton(android.widget.CompoundButton) Snackbar(com.google.android.material.snackbar.Snackbar) ApiException(net.dean.jraw.ApiException)

Example 15 with Build

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

the class Profile method onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case (android.R.id.home):
            onBackPressed();
            break;
        case (R.id.category):
            new AsyncTask<Void, Void, List<String>>() {

                Dialog d;

                @Override
                public void onPreExecute() {
                    d = new MaterialDialog.Builder(Profile.this).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<>(new AccountManager(Authentication.reddit).getSavedCategories());
                        categories.add(0, "No category");
                        return categories;
                    } catch (Exception e) {
                        e.printStackTrace();
                        // probably has no categories?
                        return new ArrayList<String>() {

                            {
                                add(0, "No category");
                            }
                        };
                    }
                }

                @Override
                public void onPostExecute(final List<String> data) {
                    try {
                        new MaterialDialog.Builder(Profile.this).items(data).title(R.string.profile_category_select).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 == 0)
                                    category = null;
                                else
                                    category = t;
                                int current = pager.getCurrentItem();
                                ProfilePagerAdapter adapter = new ProfilePagerAdapter(getSupportFragmentManager());
                                pager.setAdapter(adapter);
                                pager.setOffscreenPageLimit(1);
                                tabs.setupWithViewPager(pager);
                                pager.setCurrentItem(current);
                            }
                        }).show();
                        if (d != null) {
                            d.dismiss();
                        }
                    } catch (Exception ignored) {
                    }
                }
            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            break;
        case (R.id.info):
            if (account != null && trophyCase != null) {
                LayoutInflater inflater = getLayoutInflater();
                final View dialoglayout = inflater.inflate(R.layout.colorprofile, null);
                final TextView title = dialoglayout.findViewById(R.id.title);
                title.setText(name);
                if (account.getDataNode().has("is_employee") && account.getDataNode().get("is_employee").asBoolean()) {
                    SpannableStringBuilder admin = new SpannableStringBuilder("[A]");
                    admin.setSpan(new RelativeSizeSpan(.67f), 0, admin.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    title.append(" ");
                    title.append(admin);
                }
                dialoglayout.findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Reddit.defaultShareText(getString(R.string.profile_share, name), "https://www.reddit.com/u/" + name, Profile.this);
                    }
                });
                final int currentColor = Palette.getColorUser(name);
                title.setBackgroundColor(currentColor);
                String info = getString(R.string.profile_age, TimeUtils.getTimeSince(account.getCreated().getTime(), Profile.this));
                /*todo better if (account.hasGold() &&account.getDataNode().has("gold_expiration") ) {
                    Calendar c = Calendar.getInstance();
                    c.setTimeInMillis(account.getDataNode().get("gold_expiration").asLong());
                    info.append("Gold expires on " + new SimpleDateFormat("dd/MM/yy").format(c.getTime()));
                }*/
                ((TextView) dialoglayout.findViewById(R.id.moreinfo)).setText(info);
                String tag = UserTags.getUserTag(name);
                if (tag.isEmpty()) {
                    tag = getString(R.string.profile_tag_user);
                } else {
                    tag = getString(R.string.profile_tag_user_existing, tag);
                }
                ((TextView) dialoglayout.findViewById(R.id.tagged)).setText(tag);
                LinearLayout l = dialoglayout.findViewById(R.id.trophies_inner);
                dialoglayout.findViewById(R.id.tag).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        MaterialDialog.Builder b = new MaterialDialog.Builder(Profile.this).title(getString(R.string.profile_tag_set, name)).input(getString(R.string.profile_tag), UserTags.getUserTag(name), false, (dialog, input) -> {
                        }).positiveText(R.string.profile_btn_tag).neutralText(R.string.btn_cancel);
                        if (UserTags.isUserTagged(name)) {
                            b.negativeText(R.string.profile_btn_untag);
                        }
                        b.onPositive(new MaterialDialog.SingleButtonCallback() {

                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {
                                UserTags.setUserTag(name, dialog.getInputEditText().getText().toString());
                                String tag = UserTags.getUserTag(name);
                                if (tag.isEmpty()) {
                                    tag = getString(R.string.profile_tag_user);
                                } else {
                                    tag = getString(R.string.profile_tag_user_existing, tag);
                                }
                                ((TextView) dialoglayout.findViewById(R.id.tagged)).setText(tag);
                            }
                        }).onNeutral(null).onNegative(new MaterialDialog.SingleButtonCallback() {

                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {
                                UserTags.removeUserTag(name);
                                String tag = UserTags.getUserTag(name);
                                if (tag.isEmpty()) {
                                    tag = getString(R.string.profile_tag_user);
                                } else {
                                    tag = getString(R.string.profile_tag_user_existing, tag);
                                }
                                ((TextView) dialoglayout.findViewById(R.id.tagged)).setText(tag);
                            }
                        }).show();
                    }
                });
                if (trophyCase.isEmpty()) {
                    dialoglayout.findViewById(R.id.trophies).setVisibility(View.GONE);
                } else {
                    for (final Trophy t : trophyCase) {
                        View view = getLayoutInflater().inflate(R.layout.trophy, null);
                        ((Reddit) getApplicationContext()).getImageLoader().displayImage(t.getIcon(), ((ImageView) view.findViewById(R.id.image)));
                        ((TextView) view.findViewById(R.id.trophyTitle)).setText(t.getFullName());
                        if (t.getAboutUrl() != null && !t.getAboutUrl().equalsIgnoreCase("null")) {
                            view.setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    LinkUtil.openUrl(LinkUtil.formatURL(t.getAboutUrl()).toString(), Palette.getColorUser(account.getFullName()), Profile.this);
                                }
                            });
                        }
                        l.addView(view);
                    }
                }
                if (Authentication.isLoggedIn) {
                    dialoglayout.findViewById(R.id.pm).setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(Profile.this, SendMessage.class);
                            i.putExtra(SendMessage.EXTRA_NAME, name);
                            startActivity(i);
                        }
                    });
                    friend = account.isFriend();
                    if (friend) {
                        ((TextView) dialoglayout.findViewById(R.id.friend)).setText(R.string.profile_remove_friend);
                    } else {
                        ((TextView) dialoglayout.findViewById(R.id.friend)).setText(R.string.profile_add_friend);
                    }
                    dialoglayout.findViewById(R.id.friend_body).setOnClickListener(new View.OnClickListener() {

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

                                @Override
                                protected Void doInBackground(Void... params) {
                                    if (friend) {
                                        try {
                                            new AccountManager(Authentication.reddit).deleteFriend(name);
                                        } catch (Exception ignored) {
                                        // Will throw java.lang.IllegalStateException: No Content-Type header was found, but it still works.
                                        }
                                        friend = false;
                                    } else {
                                        new AccountManager(Authentication.reddit).updateFriend(name);
                                        friend = true;
                                    }
                                    return null;
                                }

                                @Override
                                public void onPostExecute(Void voids) {
                                    if (friend) {
                                        ((TextView) dialoglayout.findViewById(R.id.friend)).setText(R.string.profile_remove_friend);
                                    } else {
                                        ((TextView) dialoglayout.findViewById(R.id.friend)).setText(R.string.profile_add_friend);
                                    }
                                }
                            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                    });
                    dialoglayout.findViewById(R.id.block_body).setOnClickListener(new View.OnClickListener() {

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

                                @Override
                                protected Boolean doInBackground(Void... params) {
                                    Map<String, String> map = new HashMap();
                                    map.put("account_id", "t2_" + account.getId());
                                    try {
                                        Authentication.reddit.execute(Authentication.reddit.request().post(map).path("/api/block_user").build());
                                    } catch (Exception ex) {
                                        return false;
                                    }
                                    return true;
                                }

                                @Override
                                public void onPostExecute(Boolean blocked) {
                                    if (!blocked) {
                                        Toast.makeText(getBaseContext(), getString(R.string.err_block_user), Toast.LENGTH_LONG).show();
                                    } else {
                                        Toast.makeText(getBaseContext(), getString(R.string.success_block_user), Toast.LENGTH_LONG).show();
                                    }
                                }
                            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                    });
                } else {
                    dialoglayout.findViewById(R.id.pm).setVisibility(View.GONE);
                }
                dialoglayout.findViewById(R.id.multi_body).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent inte = new Intent(Profile.this, MultiredditOverview.class);
                        inte.putExtra(EXTRA_PROFILE, name);
                        Profile.this.startActivity(inte);
                    }
                });
                final View body = dialoglayout.findViewById(R.id.body2);
                body.setVisibility(View.INVISIBLE);
                final View center = dialoglayout.findViewById(R.id.colorExpandFrom);
                dialoglayout.findViewById(R.id.color).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        int cx = center.getWidth() / 2;
                        int cy = center.getHeight() / 2;
                        int finalRadius = Math.max(body.getWidth(), body.getHeight());
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            Animator anim = ViewAnimationUtils.createCircularReveal(body, cx, cy, 0, finalRadius);
                            body.setVisibility(View.VISIBLE);
                            anim.start();
                        } else {
                            body.setVisibility(View.VISIBLE);
                        }
                    }
                });
                LineColorPicker colorPicker = dialoglayout.findViewById(R.id.picker);
                final LineColorPicker colorPicker2 = dialoglayout.findViewById(R.id.picker2);
                colorPicker.setColors(ColorPreferences.getBaseColors(Profile.this));
                colorPicker.setOnColorChangedListener(new OnColorChangedListener() {

                    @Override
                    public void onColorChanged(int c) {
                        colorPicker2.setColors(ColorPreferences.getColors(getBaseContext(), c));
                        colorPicker2.setSelectedColor(c);
                    }
                });
                for (int i : colorPicker.getColors()) {
                    for (int i2 : ColorPreferences.getColors(getBaseContext(), i)) {
                        if (i2 == currentColor) {
                            colorPicker.setSelectedColor(i);
                            colorPicker2.setColors(ColorPreferences.getColors(getBaseContext(), i));
                            colorPicker2.setSelectedColor(i2);
                            break;
                        }
                    }
                }
                colorPicker2.setOnColorChangedListener(new OnColorChangedListener() {

                    @Override
                    public void onColorChanged(int i) {
                        findViewById(R.id.header).setBackgroundColor(colorPicker2.getColor());
                        if (mToolbar != null)
                            mToolbar.setBackgroundColor(colorPicker2.getColor());
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            Window window = getWindow();
                            window.setStatusBarColor(Palette.getDarkerColor(colorPicker2.getColor()));
                        }
                        title.setBackgroundColor(colorPicker2.getColor());
                    }
                });
                {
                    TextView dialogButton = dialoglayout.findViewById(R.id.ok);
                    // if button is clicked, close the custom dialog
                    dialogButton.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            Palette.setColorUser(name, colorPicker2.getColor());
                            int cx = center.getWidth() / 2;
                            int cy = center.getHeight() / 2;
                            int initialRadius = body.getWidth();
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                Animator anim = ViewAnimationUtils.createCircularReveal(body, cx, cy, initialRadius, 0);
                                anim.addListener(new AnimatorListenerAdapter() {

                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        super.onAnimationEnd(animation);
                                        body.setVisibility(View.GONE);
                                    }
                                });
                                anim.start();
                            } else {
                                body.setVisibility(View.GONE);
                            }
                        }
                    });
                }
                {
                    final TextView dialogButton = dialoglayout.findViewById(R.id.reset);
                    // if button is clicked, close the custom dialog
                    dialogButton.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            Palette.removeUserColor(name);
                            Snackbar.make(dialogButton, "User color removed", Snackbar.LENGTH_SHORT).show();
                            int cx = center.getWidth() / 2;
                            int cy = center.getHeight() / 2;
                            int initialRadius = body.getWidth();
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                Animator anim = ViewAnimationUtils.createCircularReveal(body, cx, cy, initialRadius, 0);
                                anim.addListener(new AnimatorListenerAdapter() {

                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        super.onAnimationEnd(animation);
                                        body.setVisibility(View.GONE);
                                    }
                                });
                                anim.start();
                            } else {
                                body.setVisibility(View.GONE);
                            }
                        }
                    });
                }
                ((TextView) dialoglayout.findViewById(R.id.commentkarma)).setText(String.format(Locale.getDefault(), "%d", account.getCommentKarma()));
                ((TextView) dialoglayout.findViewById(R.id.linkkarma)).setText(String.format(Locale.getDefault(), "%d", account.getLinkKarma()));
                ((TextView) dialoglayout.findViewById(R.id.totalKarma)).setText(String.format(Locale.getDefault(), "%d", account.getCommentKarma() + account.getLinkKarma()));
                new AlertDialog.Builder(Profile.this).setOnDismissListener(dialogInterface -> {
                    findViewById(R.id.header).setBackgroundColor(currentColor);
                    if (mToolbar != null)
                        mToolbar.setBackgroundColor(currentColor);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        Window window = getWindow();
                        window.setStatusBarColor(Palette.getDarkerColor(currentColor));
                    }
                }).setView(dialoglayout).show();
            }
            return true;
        case (R.id.sort):
            openPopup();
            return true;
    }
    return false;
}
Also used : LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) R(me.ccrama.redditslide.R) TimeUtils(me.ccrama.redditslide.util.TimeUtils) NonNull(androidx.annotation.NonNull) Spannable(android.text.Spannable) WindowManager(android.view.WindowManager) ImageView(android.widget.ImageView) Animator(android.animation.Animator) Locale(java.util.Locale) Map(java.util.Map) Fragment(androidx.fragment.app.Fragment) View(android.view.View) Sorting(net.dean.jraw.paginators.Sorting) FragmentStatePagerAdapter(androidx.fragment.app.FragmentStatePagerAdapter) Log(android.util.Log) AsyncTask(android.os.AsyncTask) TabLayout(com.google.android.material.tabs.TabLayout) Authentication(me.ccrama.redditslide.Authentication) ViewAnimationUtils(android.view.ViewAnimationUtils) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) Palette(me.ccrama.redditslide.Visuals.Palette) List(java.util.List) TextView(android.widget.TextView) SortingUtil(me.ccrama.redditslide.util.SortingUtil) LinearInterpolator(android.view.animation.LinearInterpolator) LineColorPicker(uz.shift.colorpicker.LineColorPicker) ContributionsView(me.ccrama.redditslide.Fragments.ContributionsView) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) Snackbar(com.google.android.material.snackbar.Snackbar) LayoutUtils(me.ccrama.redditslide.util.LayoutUtils) Spanned(android.text.Spanned) AlertDialog(androidx.appcompat.app.AlertDialog) ViewPager(androidx.viewpager.widget.ViewPager) HistoryView(me.ccrama.redditslide.Fragments.HistoryView) Dialog(android.app.Dialog) Intent(android.content.Intent) HashMap(java.util.HashMap) LogUtil(me.ccrama.redditslide.util.LogUtil) MenuItem(android.view.MenuItem) AccountManager(net.dean.jraw.managers.AccountManager) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) MenuInflater(android.view.MenuInflater) Toast(android.widget.Toast) Menu(android.view.Menu) Build(android.os.Build) TimePeriod(net.dean.jraw.paginators.TimePeriod) OnColorChangedListener(uz.shift.colorpicker.OnColorChangedListener) FragmentManager(androidx.fragment.app.FragmentManager) FluentRedditClient(net.dean.jraw.fluent.FluentRedditClient) UserTags(me.ccrama.redditslide.UserTags) LayoutInflater(android.view.LayoutInflater) Reddit(me.ccrama.redditslide.Reddit) RelativeSizeSpan(android.text.style.RelativeSizeSpan) DialogAction(com.afollestad.materialdialogs.DialogAction) ColorPreferences(me.ccrama.redditslide.Visuals.ColorPreferences) Trophy(net.dean.jraw.models.Trophy) PopupMenu(androidx.appcompat.widget.PopupMenu) Gravity(android.view.Gravity) Account(net.dean.jraw.models.Account) LinkUtil(me.ccrama.redditslide.util.LinkUtil) AlertDialog(androidx.appcompat.app.AlertDialog) Trophy(net.dean.jraw.models.Trophy) HashMap(java.util.HashMap) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) RelativeSizeSpan(android.text.style.RelativeSizeSpan) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AlertDialog(androidx.appcompat.app.AlertDialog) Dialog(android.app.Dialog) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) List(java.util.List) ArrayList(java.util.ArrayList) TextView(android.widget.TextView) ImageView(android.widget.ImageView) Window(android.view.Window) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) ContributionsView(me.ccrama.redditslide.Fragments.ContributionsView) HistoryView(me.ccrama.redditslide.Fragments.HistoryView) LineColorPicker(uz.shift.colorpicker.LineColorPicker) Animator(android.animation.Animator) DialogAction(com.afollestad.materialdialogs.DialogAction) OnColorChangedListener(uz.shift.colorpicker.OnColorChangedListener) LayoutInflater(android.view.LayoutInflater) AccountManager(net.dean.jraw.managers.AccountManager) SpannableStringBuilder(android.text.SpannableStringBuilder) LinearLayout(android.widget.LinearLayout)

Aggregations

Build (android.os.Build)42 Context (android.content.Context)30 Intent (android.content.Intent)22 List (java.util.List)22 PackageManager (android.content.pm.PackageManager)20 ArrayList (java.util.ArrayList)19 View (android.view.View)16 Toast (android.widget.Toast)15 File (java.io.File)15 Bundle (android.os.Bundle)14 Uri (android.net.Uri)13 TextView (android.widget.TextView)13 Locale (java.util.Locale)13 Manifest (android.Manifest)11 SharedPreferences (android.content.SharedPreferences)11 NonNull (android.support.annotation.NonNull)11 Activity (android.app.Activity)10 DialogInterface (android.content.DialogInterface)10 EditText (android.widget.EditText)10 Arrays (java.util.Arrays)10