Search in sources :

Example 1 with AccountsModel

use of com.github.moko256.twitlatte.model.AccountsModel in project twicalico by moko256.

the class SettingsFragment method onCreatePreferences.

@Override
public void onCreatePreferences(Bundle bundle, String rootKey) {
    setPreferencesFromResource(R.xml.settings, rootKey);
    if (rootKey == null) {
        AccountsModel accountsModel = GlobalApplicationKt.getAccountsModel(requireActivity());
        List<AccessToken> accessTokens = accountsModel.getAccessTokens();
        CharSequence[] entriesAccountList = new CharSequence[accessTokens.size() + 1];
        CharSequence[] entryValues = new CharSequence[accessTokens.size() + 1];
        for (int i = 0; i < accessTokens.size(); i++) {
            AccessToken accessToken = accessTokens.get(i);
            entriesAccountList[i] = TwitterStringUtils.plusAtMark(accessToken.getScreenName(), accessToken.getUrl());
            entryValues[i] = accessToken.getKeyString();
        }
        entriesAccountList[entriesAccountList.length - 1] = getString(R.string.login_with_another_account);
        entryValues[entryValues.length - 1] = "-1";
        ListPreference nowAccountList = findPreference(KEY_ACCOUNT_KEY);
        nowAccountList.setEntries(entriesAccountList);
        nowAccountList.setEntryValues(entryValues);
        nowAccountList.setDefaultValue(GlobalApplicationKt.preferenceRepository.getString(KEY_ACCOUNT_KEY, "-1"));
        nowAccountList.setOnPreferenceChangeListener((preference, newValue) -> {
            if (newValue.equals("-1")) {
                startActivityForResult(new Intent(getContext(), OAuthActivity.class), REQUEST_OAUTH_OR_CANCEL);
                return false;
            } else {
                AccessToken accessToken = GlobalApplicationKt.getAccountsModel(requireActivity()).get((String) newValue);
                ((GlobalApplication) requireActivity().getApplication()).initCurrentClient(accessToken);
                startActivity(new Intent(getContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
                return true;
            }
        });
        List<AccessToken> accessTokensTwitter = accountsModel.getAccessTokensByType(CLIENT_TYPE_TWITTER);
        CharSequence[] entriesLinkOpen = new CharSequence[accessTokensTwitter.size() + 1];
        CharSequence[] entriesLinkOpenValue = new CharSequence[accessTokensTwitter.size() + 1];
        for (int i = 0; i < accessTokensTwitter.size(); i++) {
            AccessToken accessToken = accessTokensTwitter.get(i);
            entriesLinkOpen[i] = TwitterStringUtils.plusAtMark(accessToken.getScreenName(), accessToken.getUrl());
            entriesLinkOpenValue[i] = accessToken.getKeyString();
        }
        entriesLinkOpen[entriesLinkOpen.length - 1] = getString(R.string.not_set);
        entriesLinkOpenValue[entriesLinkOpenValue.length - 1] = "-1";
        ListPreference linkOpenAccountList = findPreference(KEY_ACCOUNT_KEY_LINK_OPEN);
        linkOpenAccountList.setEntries(entriesLinkOpen);
        linkOpenAccountList.setEntryValues(entriesLinkOpenValue);
        linkOpenAccountList.setDefaultValue("-1");
        findPreference("logout").setOnPreferenceClickListener(preference -> {
            new AlertDialog.Builder(requireContext()).setMessage(R.string.confirm_logout).setCancelable(true).setPositiveButton(R.string.do_logout, (dialog, i) -> {
                accountsModel.delete(accountsModel.get(GlobalApplicationKt.preferenceRepository.getString(KEY_ACCOUNT_KEY, "-1")));
                int point = accountsModel.size() - 1;
                if (point != -1) {
                    AccessToken accessToken = accountsModel.getAccessTokens().get(point);
                    GlobalApplicationKt.preferenceRepository.putString(KEY_ACCOUNT_KEY, accessToken.getKeyString());
                    ((GlobalApplication) requireActivity().getApplication()).initCurrentClient(accessToken);
                    startActivity(new Intent(getContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
                } else {
                    GlobalApplicationKt.preferenceRepository.putString(KEY_ACCOUNT_KEY, "-1");
                    ((GlobalApplication) requireActivity().getApplication()).clearCurrentClient();
                    startActivity(new Intent(getContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
                }
            }).setNegativeButton(android.R.string.cancel, null).show();
            return false;
        });
        ListPreference nowThemeMode = findPreference(KEY_NIGHT_MODE);
        nowThemeMode.setOnPreferenceChangeListener((preference, newValue) -> {
            AppCompatDelegate.setDefaultNightMode(ThemePreferenceConverterKt.convertToAppCompatNightThemeMode(String.valueOf(newValue)));
            ((AppCompatActivity) requireActivity()).getDelegate().applyDayNight();
            return true;
        });
        Preference licenseThisApp = findPreference("license_at_this_app");
        licenseThisApp.setOnPreferenceClickListener(preference -> {
            requireContext().startActivity(new Intent(getContext(), LicensesActivity.class).putExtra("title", getResources().getText(R.string.app_name)).putExtra("library_name", "twitlatte"));
            return true;
        });
        Preference sourceCodeLink = findPreference("source_code_link");
        sourceCodeLink.setOnPreferenceClickListener(preference -> {
            AppCustomTabsKt.launchChromeCustomTabs(requireContext(), "https://github.com/moko256/twitlatte", false);
            return true;
        });
        Preference version = findPreference("app_version");
        version.setSummary(BuildConfig.VERSION_NAME);
        version.setOnPreferenceClickListener(preference -> {
            eggCount--;
            if (eggCount <= 0) {
                startActivity(new Intent(getActivity(), AboutActivity.class));
                eggCount = 3;
            }
            return true;
        });
    } else if (rootKey.equals("regexMute")) {
        PreferenceScreen regexMute = getPreferenceScreen();
        for (int i = 0, length = regexMute.getPreferenceCount(); i < length; i++) {
            Preference name = regexMute.getPreference(i);
            if (name instanceof EditTextPreference) {
                name.setOnPreferenceChangeListener((preference, newValue) -> {
                    try {
                        GlobalApplicationKt.preferenceRepository.updateRegex(preference.getKey(), (String) newValue);
                    } catch (PatternSyntaxException e) {
                        e.printStackTrace();
                        Toast.makeText(requireContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                    return true;
                });
            }
        }
    } else if (rootKey.equals("license")) {
        PreferenceScreen license = getPreferenceScreen();
        for (int i = 0, length = license.getPreferenceCount(); i < length; i++) {
            license.getPreference(i).setOnPreferenceClickListener(preference -> {
                startActivity(new Intent(getContext(), LicensesActivity.class).putExtra("title", preference.getTitle()).putExtra("library_name", // "license_lib_".length
                preference.getKey().substring(12)));
                return true;
            });
        }
    } else if (rootKey.equals("contributors")) {
        PreferenceScreen contributorCategory = getPreferenceScreen();
        for (int c = 0, length = contributorCategory.getPreferenceCount(); c < length; c++) {
            PreferenceCategory contributor = (PreferenceCategory) contributorCategory.getPreference(c);
            for (int i = 0, l = contributor.getPreferenceCount(); i < l; i++) {
                Preference name = contributor.getPreference(i);
                String uri = "https://github.com/" + name.getKey();
                name.setSummary(uri);
                name.setOnPreferenceClickListener(preference -> {
                    AppCustomTabsKt.launchChromeCustomTabs(requireContext(), uri, false);
                    return true;
                });
            }
        }
    }
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) Bundle(android.os.Bundle) AlertDialog(androidx.appcompat.app.AlertDialog) ThemePreferenceConverterKt(com.github.moko256.twitlatte.text.ThemePreferenceConverterKt) KEY_ACCOUNT_KEY_LINK_OPEN(com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_ACCOUNT_KEY_LINK_OPEN) RESULT_OK(android.app.Activity.RESULT_OK) PreferenceCategory(androidx.preference.PreferenceCategory) AccountsModel(com.github.moko256.twitlatte.model.AccountsModel) Intent(android.content.Intent) CLIENT_TYPE_TWITTER(com.github.moko256.latte.client.twitter.TwitterApiClientImplKt.CLIENT_TYPE_TWITTER) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) PreferenceFragmentCompat(androidx.preference.PreferenceFragmentCompat) AppCustomTabsKt(com.github.moko256.twitlatte.intent.AppCustomTabsKt) TwitterStringUtils(com.github.moko256.twitlatte.text.TwitterStringUtils) Toast(android.widget.Toast) EditTextPreference(androidx.preference.EditTextPreference) PreferenceScreen(androidx.preference.PreferenceScreen) PatternSyntaxException(java.util.regex.PatternSyntaxException) AppCompatDelegate(androidx.appcompat.app.AppCompatDelegate) KEY_ACCOUNT_KEY(com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_ACCOUNT_KEY) Preference(androidx.preference.Preference) AccessToken(com.github.moko256.latte.client.base.entity.AccessToken) List(java.util.List) KEY_NIGHT_MODE(com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_NIGHT_MODE) Nullable(androidx.annotation.Nullable) ListPreference(androidx.preference.ListPreference) PreferenceScreen(androidx.preference.PreferenceScreen) AccountsModel(com.github.moko256.twitlatte.model.AccountsModel) Intent(android.content.Intent) ListPreference(androidx.preference.ListPreference) EditTextPreference(androidx.preference.EditTextPreference) EditTextPreference(androidx.preference.EditTextPreference) Preference(androidx.preference.Preference) ListPreference(androidx.preference.ListPreference) PreferenceCategory(androidx.preference.PreferenceCategory) AccessToken(com.github.moko256.latte.client.base.entity.AccessToken) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 2 with AccountsModel

use of com.github.moko256.twitlatte.model.AccountsModel in project twicalico by moko256.

the class MainActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.MainActivityTheme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    disposable = new CompositeDisposable();
    client = GlobalApplicationKt.getClient(this);
    accountsModel = GlobalApplicationKt.getAccountsModel(this);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.getChildAt(0).setOnClickListener(v -> {
        Fragment fragment = getMainFragment();
        if (fragment instanceof MovableTopInterface) {
            ((MovableTopInterface) fragment).moveToTop();
        }
    });
    drawer = findViewById(R.id.drawer_layout);
    if (drawer != null) {
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        toggle.setDrawerSlideAnimationEnabled(false);
        toggle.syncState();
        drawer.addDrawerListener(this);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.color_primary_dark));
    }
    navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(item -> {
        int id = item.getItemId();
        if (!item.isChecked()) {
            switch(id) {
                case R.id.nav_timeline:
                    replaceFragment(new HomeTimeLineFragment());
                    break;
                case R.id.nav_mentions:
                    replaceFragment(new MentionsFragment());
                    break;
                case R.id.nav_account:
                    startMyUserActivity();
                    break;
                case R.id.nav_follow_and_follower:
                    replaceFragment(new MyFollowFollowerFragment());
                    break;
                case R.id.nav_like:
                    replaceFragment(UserLikeFragment.Companion.newInstance(client.getAccessToken().getUserId()));
                    break;
                case R.id.nav_lists:
                    replaceFragment(SelectListsEntriesFragment.Companion.newInstance(client.getAccessToken().getUserId()));
                    break;
                case R.id.nav_settings:
                    startActivity(new Intent(this, SettingsActivity.class));
                    break;
            }
        }
        if (drawer != null) {
            drawer.closeDrawer(GravityCompat.START);
        }
        return (id != R.id.nav_settings) && (id != R.id.nav_account);
    });
    View headerView = navigationView.inflateHeaderView(R.layout.nav_header_main);
    userNameText = headerView.findViewById(R.id.user_name);
    userIdText = headerView.findViewById(R.id.user_id);
    userImage = headerView.findViewById(R.id.user_image);
    userToggleImage = headerView.findViewById(R.id.toggle_account);
    userBackgroundImage = headerView.findViewById(R.id.user_bg_image);
    userBackgroundImage.setOnClickListener(v -> changeIsDrawerAccountsSelection());
    accountListView = new RecyclerView(this);
    accountListView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    accountListView.setLayoutManager(new LinearLayoutManager(this));
    accountListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    accountListView.setVisibility(View.GONE);
    navigationView.addHeaderView(accountListView);
    adapter = new SelectAccountsAdapter(this);
    adapter.onImageButtonClickListener = accessToken -> {
        if (accessToken.getUserId() != client.getAccessToken().getUserId()) {
            changeIsDrawerAccountsSelection();
            if (drawer != null) {
                drawer.closeDrawer(GravityCompat.START);
            }
            GlobalApplicationKt.preferenceRepository.putString(KEY_ACCOUNT_KEY, accessToken.getKeyString());
            ((GlobalApplication) getApplication()).initCurrentClient(accessToken);
            client = GlobalApplicationKt.getClient(this);
            adapter.updateSelectedPosition(accessToken);
            updateDrawerImage();
            clearAndPrepareFragment();
        }
    };
    adapter.onAddButtonClickListener = v -> startActivityForResult(new Intent(this, OAuthActivity.class), REQUEST_OAUTH);
    adapter.onRemoveButtonClickListener = v -> new AlertDialog.Builder(this).setMessage(R.string.confirm_logout).setCancelable(true).setPositiveButton(R.string.do_logout, (dialog, i) -> {
        AccessToken token = accountsModel.get(GlobalApplicationKt.preferenceRepository.getString(KEY_ACCOUNT_KEY, "-1"));
        accountsModel.delete(token);
        adapter.removeAccessTokensAndUpdate(token);
        int point = accountsModel.size() - 1;
        if (point != -1) {
            AccessToken accessToken = accountsModel.getAccessTokens().get(point);
            GlobalApplicationKt.preferenceRepository.putString(KEY_ACCOUNT_KEY, accessToken.getKeyString());
            ((GlobalApplication) getApplication()).initCurrentClient(accessToken);
            client = GlobalApplicationKt.getClient(this);
            adapter.updateSelectedPosition(accessToken);
            updateDrawerImage();
            updateAccountsList();
            clearAndPrepareFragment();
        } else {
            GlobalApplicationKt.preferenceRepository.putString(KEY_ACCOUNT_KEY, "-1");
            ((GlobalApplication) getApplication()).clearCurrentClient();
            startActivityForResult(new Intent(this, OAuthActivity.class), REQUEST_OAUTH);
        }
    }).setNegativeButton(android.R.string.cancel, null).show();
    accountListView.setAdapter(adapter);
    findViewById(R.id.fab).setOnClickListener(v -> startActivity(new Intent(this, PostActivity.class)));
    tabLayout = findViewById(R.id.toolbar_tab);
    tabLayout.addOnTabSelectedListener(this);
    alwaysCloseApp = GlobalApplicationKt.preferenceRepository.getBoolean(KEY_ALWAYS_CLOSE_APP, true);
    recycledViewPool = new RecyclerView.RecycledViewPool();
    recycledViewPool.setMaxRecycledViews(R.layout.layout_post_card, 16);
    getSupportFragmentManager().addOnBackStackChangedListener(() -> attachFragment(getMainFragment()));
    if (client == null) {
        startActivityForResult(new Intent(this, OAuthActivity.class), REQUEST_OAUTH);
    } else {
        updateDrawerImage();
        updateAccountsList();
        if (savedInstanceState == null) {
            prepareFragment();
        }
        if (client.getAccessToken().getToken().isEmpty()) {
            Toast.makeText(this, R.string.please_re_login, Toast.LENGTH_LONG).show();
        }
    }
}
Also used : LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) ImageView(android.widget.ImageView) AccountsModel(com.github.moko256.twitlatte.model.AccountsModel) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) DrawableTransitionOptions(com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions) ActivityOptionsCompat(androidx.core.app.ActivityOptionsCompat) RequestManager(com.bumptech.glide.RequestManager) ActionBarDrawerToggle(androidx.appcompat.app.ActionBarDrawerToggle) Fragment(androidx.fragment.app.Fragment) View(android.view.View) ListEntry(com.github.moko256.latte.client.base.entity.ListEntry) EmojiToTextViewSetter(com.github.moko256.twitlatte.view.EmojiToTextViewSetter) Schedulers(io.reactivex.schedulers.Schedulers) RecyclerView(androidx.recyclerview.widget.RecyclerView) ContextCompat(androidx.core.content.ContextCompat) MediaUrlConverter(com.github.moko256.latte.client.base.MediaUrlConverter) TabLayout(com.google.android.material.tabs.TabLayout) ViewGroup(android.view.ViewGroup) Objects(java.util.Objects) DpToPxKt(com.github.moko256.twitlatte.view.DpToPxKt) List(java.util.List) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) TextView(android.widget.TextView) Nullable(androidx.annotation.Nullable) KEY_ALWAYS_CLOSE_APP(com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_ALWAYS_CLOSE_APP) Toolbar(androidx.appcompat.widget.Toolbar) Emoji(com.github.moko256.latte.client.base.entity.Emoji) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) DrawerLayout(androidx.drawerlayout.widget.DrawerLayout) KeyEvent(android.view.KeyEvent) AlertDialog(androidx.appcompat.app.AlertDialog) NavigationView(com.google.android.material.navigation.NavigationView) User(com.github.moko256.latte.client.base.entity.User) Pair(android.util.Pair) Intent(android.content.Intent) Single(io.reactivex.Single) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) TwitterStringUtils(com.github.moko256.twitlatte.text.TwitterStringUtils) Toast(android.widget.Toast) Menu(android.view.Menu) Build(android.os.Build) FragmentManager(androidx.fragment.app.FragmentManager) GravityCompat(androidx.core.view.GravityCompat) Client(com.github.moko256.twitlatte.entity.Client) VerifyCredentialOnSubscribe(com.github.moko256.twitlatte.rx.VerifyCredentialOnSubscribe) KEY_ACCOUNT_KEY(com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_ACCOUNT_KEY) CachedUsersSQLiteOpenHelper(com.github.moko256.twitlatte.database.CachedUsersSQLiteOpenHelper) AccessToken(com.github.moko256.latte.client.base.entity.AccessToken) Glide(com.bumptech.glide.Glide) FragmentPagerAdapter(com.github.moko256.twitlatte.widget.FragmentPagerAdapter) ActionBarDrawerToggle(androidx.appcompat.app.ActionBarDrawerToggle) Intent(android.content.Intent) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) Fragment(androidx.fragment.app.Fragment) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) NavigationView(com.google.android.material.navigation.NavigationView) AccessToken(com.github.moko256.latte.client.base.entity.AccessToken) RecyclerView(androidx.recyclerview.widget.RecyclerView) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) LinearLayout(android.widget.LinearLayout) Toolbar(androidx.appcompat.widget.Toolbar)

Aggregations

Intent (android.content.Intent)2 Bundle (android.os.Bundle)2 Toast (android.widget.Toast)2 Nullable (androidx.annotation.Nullable)2 AlertDialog (androidx.appcompat.app.AlertDialog)2 AppCompatActivity (androidx.appcompat.app.AppCompatActivity)2 AccessToken (com.github.moko256.latte.client.base.entity.AccessToken)2 AccountsModel (com.github.moko256.twitlatte.model.AccountsModel)2 KEY_ACCOUNT_KEY (com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_ACCOUNT_KEY)2 TwitterStringUtils (com.github.moko256.twitlatte.text.TwitterStringUtils)2 List (java.util.List)2 RESULT_OK (android.app.Activity.RESULT_OK)1 Build (android.os.Build)1 Pair (android.util.Pair)1 KeyEvent (android.view.KeyEvent)1 Menu (android.view.Menu)1 MenuItem (android.view.MenuItem)1 View (android.view.View)1 ViewGroup (android.view.ViewGroup)1 ImageView (android.widget.ImageView)1