Search in sources :

Example 21 with CompositeSubscription

use of rx.subscriptions.CompositeSubscription in project twicalico by moko256.

the class UserInfoFragment method onCreate.

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    subscription = new CompositeSubscription();
    userId = getArguments().getLong("userId");
    User cachedUser = GlobalApplication.userCache.get(userId);
    if (cachedUser == null) {
        subscription.add(updateUser().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(this::setShowUserInfo, Throwable::printStackTrace));
    }
}
Also used : User(twitter4j.User) CompositeSubscription(rx.subscriptions.CompositeSubscription)

Example 22 with CompositeSubscription

use of rx.subscriptions.CompositeSubscription in project twicalico by moko256.

the class BaseTweetListFragment method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    list = new ArrayList<>();
    subscription = new CompositeSubscription();
    statusIdsDatabase = new CachedIdListSQLiteOpenHelper(getContext(), GlobalApplication.userId, getCachedIdsDatabaseName());
    if (savedInstanceState == null) {
        List<Long> c = statusIdsDatabase.getIds();
        if (c.size() > 0) {
            list.addAll(c);
        }
    }
    super.onCreate(savedInstanceState);
}
Also used : CompositeSubscription(rx.subscriptions.CompositeSubscription) CachedIdListSQLiteOpenHelper(com.github.moko256.twicalico.database.CachedIdListSQLiteOpenHelper)

Example 23 with CompositeSubscription

use of rx.subscriptions.CompositeSubscription in project twicalico by moko256.

the class BaseUsersFragment method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    list = new ArrayList<>();
    subscription = new CompositeSubscription();
    super.onCreate(savedInstanceState);
}
Also used : CompositeSubscription(rx.subscriptions.CompositeSubscription)

Example 24 with CompositeSubscription

use of rx.subscriptions.CompositeSubscription in project twicalico by moko256.

the class MainActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    subscription = new CompositeSubscription();
    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);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    drawer.addDrawerListener(new DrawerLayout.DrawerListener() {

        @Override
        public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
        }

        @Override
        public void onDrawerOpened(@NonNull View drawerView) {
        }

        @Override
        public void onDrawerClosed(@NonNull View drawerView) {
            if (isDrawerAccountsSelection) {
                changeIsDrawerAccountsSelection();
            }
        }

        @Override
        public void onDrawerStateChanged(int newState) {
        }
    });
    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.newInstance(GlobalApplication.userId));
                    break;
                case R.id.nav_settings:
                    startActivity(new Intent(this, SettingsActivity.class));
                    break;
            }
        }
        drawer.closeDrawer(GravityCompat.START);
        return (id != R.id.nav_settings) && (id != R.id.nav_account);
    });
    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);
    userBackgroundImage = headerView.findViewById(R.id.user_bg_image);
    userBackgroundImage.setOnClickListener(v -> changeIsDrawerAccountsSelection());
    updateDrawerImage();
    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);
    SelectAccountsAdapter adapter = new SelectAccountsAdapter(this);
    adapter.setOnImageButtonClickListener(accessToken -> {
        drawer.closeDrawer(GravityCompat.START);
        if (accessToken.getUserId() != GlobalApplication.userId) {
            PreferenceManager.getDefaultSharedPreferences(this).edit().putString("AccountKey", accessToken.getKeyString()).apply();
            ((GlobalApplication) getApplication()).initTwitter(accessToken);
            updateDrawerImage();
            clearAndPrepareFragment();
        }
    });
    adapter.setOnAddButtonClickListener(v -> {
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("AccountKey", "-1").apply();
        GlobalApplication.twitter = null;
        startActivity(new Intent(this, OAuthActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
    });
    adapter.setOnRemoveButtonClickListener(v -> new AlertDialog.Builder(this).setMessage(R.string.confirm_logout).setCancelable(true).setPositiveButton(R.string.do_logout, (dialog, i) -> {
        SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        TokenSQLiteOpenHelper helper = new TokenSQLiteOpenHelper(this);
        helper.deleteAccessToken(helper.getAccessToken(defaultSharedPreferences.getString("AccountKey", "-1")));
        int point = helper.getSize() - 1;
        if (point != -1) {
            AccessToken accessToken = helper.getAccessTokens()[point];
            defaultSharedPreferences.edit().putString("AccountKey", accessToken.getKeyString()).apply();
            ((GlobalApplication) getApplication()).initTwitter(accessToken);
            updateDrawerImage();
            clearAndPrepareFragment();
        } else {
            adapter.getOnAddButtonClickListener().onClick(v);
        }
        helper.close();
    }).setNeutralButton(R.string.back, (dialog, i) -> dialog.cancel()).show());
    accountListView.setAdapter(adapter);
    subscription.add(Single.create(singleSubscriber -> {
        TokenSQLiteOpenHelper helper = new TokenSQLiteOpenHelper(this);
        AccessToken[] accessTokens = helper.getAccessTokens();
        helper.close();
        ArrayList<Pair<User, AccessToken>> r = new ArrayList<>(accessTokens.length);
        for (AccessToken accessToken : accessTokens) {
            long id = accessToken.getUserId();
            CachedUsersSQLiteOpenHelper userHelper = new CachedUsersSQLiteOpenHelper(this, id, accessToken.getType() == Type.TWITTER);
            User user = userHelper.getCachedUser(id);
            if (user == null) {
                try {
                    user = ((GlobalApplication) getApplication()).getTwitterInstance(accessToken).verifyCredentials();
                    userHelper.addCachedUser(user);
                } catch (TwitterException e) {
                    singleSubscriber.onError(e);
                    return;
                } finally {
                    userHelper.close();
                }
            }
            r.add(new Pair<>(user, accessToken));
        }
        singleSubscriber.onSuccess(r);
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(o -> {
        ArrayList<Pair<User, AccessToken>> pairs = (ArrayList<Pair<User, AccessToken>>) o;
        adapter.getImagesList().addAll(pairs);
        adapter.notifyDataSetChanged();
    }, Throwable::printStackTrace));
    findViewById(R.id.fab).setOnClickListener(v -> startActivity(new Intent(this, PostActivity.class)));
    tabLayout = findViewById(R.id.toolbar_tab);
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            Fragment fragment = ((FragmentPagerAdapter) ((UseTabsInterface) getMainFragment()).getTabsViewPager().getAdapter()).getFragment(tab.getPosition());
            if (fragment instanceof MovableTopInterface) {
                ((MovableTopInterface) fragment).moveToTop();
            }
        }
    });
    tweetListViewPool = new RecyclerView.RecycledViewPool();
    userListViewPool = new RecyclerView.RecycledViewPool();
    getSupportFragmentManager().addOnBackStackChangedListener(() -> attachFragment(getMainFragment()));
    if (savedInstanceState == null) {
        prepareFragment();
    }
}
Also used : NavigationView(android.support.design.widget.NavigationView) LinearLayout(android.widget.LinearLayout) Type(com.github.moko256.twicalico.entity.Type) Bundle(android.os.Bundle) ImageView(android.widget.ImageView) CachedUsersSQLiteOpenHelper(com.github.moko256.twicalico.database.CachedUsersSQLiteOpenHelper) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Intent(android.content.Intent) NonNull(android.support.annotation.NonNull) TwitterStringUtils(com.github.moko256.twicalico.text.TwitterStringUtils) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) TabLayout(android.support.design.widget.TabLayout) GravityCompat(android.support.v4.view.GravityCompat) Single(rx.Single) Menu(android.view.Menu) Schedulers(rx.schedulers.Schedulers) User(twitter4j.User) View(android.view.View) TwitterException(twitter4j.TwitterException) PreferenceManager(android.preference.PreferenceManager) DrawerLayout(android.support.v4.widget.DrawerLayout) AccessToken(com.github.moko256.twicalico.entity.AccessToken) Fragment(android.support.v4.app.Fragment) ActivityOptionsCompat(android.support.v4.app.ActivityOptionsCompat) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) AppCompatActivity(android.support.v7.app.AppCompatActivity) ViewGroup(android.view.ViewGroup) CompositeSubscription(rx.subscriptions.CompositeSubscription) RecyclerView(android.support.v7.widget.RecyclerView) FragmentManager(android.support.v4.app.FragmentManager) AlertDialog(android.support.v7.app.AlertDialog) TextView(android.widget.TextView) SharedPreferences(android.content.SharedPreferences) Toolbar(android.support.v7.widget.Toolbar) Pair(android.support.v4.util.Pair) TokenSQLiteOpenHelper(com.github.moko256.twicalico.database.TokenSQLiteOpenHelper) FragmentPagerAdapter(com.github.moko256.twicalico.widget.FragmentPagerAdapter) ActionBarDrawerToggle(android.support.v7.app.ActionBarDrawerToggle) User(twitter4j.User) ActionBarDrawerToggle(android.support.v7.app.ActionBarDrawerToggle) ArrayList(java.util.ArrayList) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) Fragment(android.support.v4.app.Fragment) AccessToken(com.github.moko256.twicalico.entity.AccessToken) TabLayout(android.support.design.widget.TabLayout) DrawerLayout(android.support.v4.widget.DrawerLayout) TwitterException(twitter4j.TwitterException) TokenSQLiteOpenHelper(com.github.moko256.twicalico.database.TokenSQLiteOpenHelper) Pair(android.support.v4.util.Pair) SharedPreferences(android.content.SharedPreferences) CachedUsersSQLiteOpenHelper(com.github.moko256.twicalico.database.CachedUsersSQLiteOpenHelper) Intent(android.content.Intent) NavigationView(android.support.design.widget.NavigationView) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) TextView(android.widget.TextView) CompositeSubscription(rx.subscriptions.CompositeSubscription) RecyclerView(android.support.v7.widget.RecyclerView) LinearLayout(android.widget.LinearLayout)

Example 25 with CompositeSubscription

use of rx.subscriptions.CompositeSubscription in project twicalico by moko256.

the class PostActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);
    model = PostTweetModelCreator.getInstance(GlobalApplication.twitter, getContentResolver());
    subscription = new CompositeSubscription();
    rootViewGroup = findViewById(R.id.activity_tweet_send_layout_root);
    toolbar = findViewById(R.id.activity_tweet_send_toolbar);
    setSupportActionBar(toolbar);
    actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeAsUpIndicator(R.drawable.ic_clear_white_24dp);
    userIcon = findViewById(R.id.activity_tweet_send_user_icon);
    GlideApp.with(this).load(GlobalApplication.userCache.get(GlobalApplication.userId).get400x400ProfileImageURLHttps()).circleCrop().into(userIcon);
    counterTextView = findViewById(R.id.tweet_text_edit_counter);
    editText = findViewById(R.id.tweet_text_edit);
    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            model.setTweetText(s.toString());
            counterTextView.setText(String.valueOf(model.getTweetLength()) + " / " + String.valueOf(model.getMaxTweetLength()));
            counterTextView.setTextColor(model.isValidTweet() ? Color.GRAY : Color.RED);
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    editText.setImageAddedListener(imageUri -> {
        if (model.getUriList().size() < model.getUriListSizeLimit()) {
            addedImagesAdapter.getImagesList().add(imageUri);
            model.getUriList().add(imageUri);
            addedImagesAdapter.notifyItemChanged(addedImagesAdapter.getImagesList().size() - 1);
            possiblySensitiveSwitch.setEnabled(true);
            return true;
        } else {
            return false;
        }
    });
    editText.setHint(model.isReply() ? R.string.reply : R.string.post);
    imagesRecyclerView = findViewById(R.id.activity_tweet_send_images_recycler_view);
    addedImagesAdapter = new AddedImagesAdapter(this);
    imagesRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
    imagesRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.right = Math.round(getResources().getDisplayMetrics().density);
        }
    });
    addedImagesAdapter.setLimit(model.getUriListSizeLimit());
    addedImagesAdapter.setOnAddButtonClickListener(v -> startActivityForResult(Intent.createChooser(new Intent(Intent.ACTION_GET_CONTENT).addCategory(Intent.CATEGORY_OPENABLE).putExtra(Intent.EXTRA_MIME_TYPES, new String[] { "image/*", "video/*" }).putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true).setType("*/*"), getString(R.string.add_image)), REQUEST_GET_IMAGE));
    addedImagesAdapter.setOnDeleteButtonListener(position -> {
        addedImagesAdapter.getImagesList().remove(position);
        model.getUriList().remove(position);
        addedImagesAdapter.notifyDataSetChanged();
        boolean enabled = model.getUriList().size() > 0;
        possiblySensitiveSwitch.setEnabled(enabled);
        possiblySensitiveSwitch.setChecked(possiblySensitiveSwitch.isChecked() && enabled);
    });
    addedImagesAdapter.setOnImageClickListener(position -> {
        Intent open = new Intent(Intent.ACTION_VIEW).setData(model.getUriList().get(position)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(open, getString(R.string.open_image)));
    });
    imagesRecyclerView.setAdapter(addedImagesAdapter);
    possiblySensitiveSwitch = findViewById(R.id.activity_tweet_possibly_sensitive_switch);
    possiblySensitiveSwitch.setEnabled(addedImagesAdapter.getImagesList().size() > 0);
    possiblySensitiveSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> model.setPossiblySensitive(isChecked));
    addLocationSwitch = findViewById(R.id.activity_tweet_location_switch);
    addLocationSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
        if (isChecked) {
            if (PermissionChecker.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PermissionChecker.PERMISSION_GRANTED) {
                subscription.add(getLocation().subscribe(it -> {
                    model.setLocation(new GeoLocation(it.getLatitude(), it.getLongitude()));
                    locationText.setVisibility(View.VISIBLE);
                    locationText.setText(getString(R.string.lat_and_lon, it.getLatitude(), it.getLongitude()));
                }, Throwable::printStackTrace));
            } else {
                ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, 400);
            }
        } else {
            locationText.setVisibility(View.GONE);
        }
    });
    locationText = findViewById(R.id.activity_tweet_location_result);
    locationText.setVisibility(View.GONE);
    if (getIntent() != null) {
        if (!model.isReply()) {
            model.setInReplyToStatusId(getIntent().getLongExtra(INTENT_EXTRA_IN_REPLY_TO_STATUS_ID, -1));
        }
        String text = getIntent().getStringExtra(INTENT_EXTRA_TWEET_TEXT);
        if (text != null) {
            editText.setText(text);
            editText.setSelection(text.length());
        } else {
            editText.setText("");
        }
        ArrayList<Uri> uris = getIntent().getParcelableArrayListExtra(INTENT_EXTRA_IMAGE_URI);
        if (uris != null) {
            addedImagesAdapter.getImagesList().addAll(uris);
            model.getUriList().addAll(uris);
            possiblySensitiveSwitch.setEnabled(true);
        }
    }
}
Also used : Context(android.content.Context) Rect(android.graphics.Rect) Bundle(android.os.Bundle) PostTweetModel(com.github.moko256.twicalico.model.base.PostTweetModel) Criteria(android.location.Criteria) Uri(android.net.Uri) ImageView(android.widget.ImageView) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Intent(android.content.Intent) NonNull(android.support.annotation.NonNull) LocationListener(android.location.LocationListener) TwitterStringUtils(com.github.moko256.twicalico.text.TwitterStringUtils) Editable(android.text.Editable) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) ClipData(android.content.ClipData) Manifest(android.Manifest) ImageKeyboardEditText(com.github.moko256.twicalico.widget.ImageKeyboardEditText) Single(rx.Single) Menu(android.view.Menu) Schedulers(rx.schedulers.Schedulers) View(android.view.View) ActionBar(android.support.v7.app.ActionBar) Parcelable(android.os.Parcelable) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) SwitchCompat(android.support.v7.widget.SwitchCompat) ActivityCompat(android.support.v4.app.ActivityCompat) AppCompatActivity(android.support.v7.app.AppCompatActivity) ViewGroup(android.view.ViewGroup) Color(android.graphics.Color) CompositeSubscription(rx.subscriptions.CompositeSubscription) RecyclerView(android.support.v7.widget.RecyclerView) TextView(android.widget.TextView) Toolbar(android.support.v7.widget.Toolbar) GeoLocation(twitter4j.GeoLocation) PermissionChecker(android.support.v4.content.PermissionChecker) Location(android.location.Location) Snackbar(android.support.design.widget.Snackbar) PostTweetModelCreator(com.github.moko256.twicalico.model.impl.PostTweetModelCreator) LocationManager(android.location.LocationManager) TextWatcher(android.text.TextWatcher) Rect(android.graphics.Rect) Intent(android.content.Intent) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) TextView(android.widget.TextView) Uri(android.net.Uri) CompositeSubscription(rx.subscriptions.CompositeSubscription) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) RecyclerView(android.support.v7.widget.RecyclerView) GeoLocation(twitter4j.GeoLocation)

Aggregations

CompositeSubscription (rx.subscriptions.CompositeSubscription)49 ArrayList (java.util.ArrayList)9 View (android.view.View)7 Subscription (rx.Subscription)7 Context (android.content.Context)6 Bundle (android.os.Bundle)6 AndroidSchedulers (rx.android.schedulers.AndroidSchedulers)6 Intent (android.content.Intent)5 AppCompatActivity (android.support.v7.app.AppCompatActivity)5 RecyclerView (android.support.v7.widget.RecyclerView)5 ViewGroup (android.view.ViewGroup)5 List (java.util.List)5 Schedulers (rx.schedulers.Schedulers)5 MenuItem (android.view.MenuItem)4 Issue (com.kboyarshinov.realmrxjavaexample.model.Issue)4 ActionBar (android.support.v7.app.ActionBar)3 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)3 Menu (android.view.Menu)3 TextView (android.widget.TextView)3 TwitterStringUtils (com.github.moko256.twicalico.text.TwitterStringUtils)3