diff options
author | Alex Ning <chineseperson5@gmail.com> | 2019-08-07 15:28:02 +0000 |
---|---|---|
committer | Alex Ning <chineseperson5@gmail.com> | 2019-08-07 15:28:02 +0000 |
commit | 425bc857cfe094d8b9be5815030ef3e6b0cf173d (patch) | |
tree | f1e4240531040bb20c9e840c123f03ce28a5f94e /app/src/main/java | |
parent | 7f2bc01180c284154fb69976122016c4638e9973 (diff) | |
download | infinity-for-reddit-425bc857cfe094d8b9be5815030ef3e6b0cf173d.tar infinity-for-reddit-425bc857cfe094d8b9be5815030ef3e6b0cf173d.tar.gz infinity-for-reddit-425bc857cfe094d8b9be5815030ef3e6b0cf173d.tar.bz2 infinity-for-reddit-425bc857cfe094d8b9be5815030ef3e6b0cf173d.tar.lz infinity-for-reddit-425bc857cfe094d8b9be5815030ef3e6b0cf173d.tar.xz infinity-for-reddit-425bc857cfe094d8b9be5815030ef3e6b0cf173d.tar.zst infinity-for-reddit-425bc857cfe094d8b9be5815030ef3e6b0cf173d.zip |
Refactored all the other classes to support multi user. Clearing the app data is required before launching the app.
Diffstat (limited to '')
61 files changed, 1105 insertions, 718 deletions
diff --git a/app/src/main/java/Account/Account.java b/app/src/main/java/Account/Account.java index 95873c61..4ae15741 100644 --- a/app/src/main/java/Account/Account.java +++ b/app/src/main/java/Account/Account.java @@ -58,6 +58,10 @@ public class Account { return accessToken; } + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + public String getRefreshToken() { return refreshToken; } diff --git a/app/src/main/java/Account/AccountDao.java b/app/src/main/java/Account/AccountDao.java index bd53b92b..8db57683 100644 --- a/app/src/main/java/Account/AccountDao.java +++ b/app/src/main/java/Account/AccountDao.java @@ -6,11 +6,19 @@ import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; +import java.util.List; + @Dao public interface AccountDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insert(Account account); + @Query("SELECT * FROM accounts WHERE is_current_user = 0") + List<Account> getAllNonCurrentAccounts(); + + @Query("UPDATE accounts SET is_current_user = 0 WHERE is_current_user = 1") + void markAllAccountsNonCurrent(); + @Query("DELETE FROM accounts") void deleteAllAccounts(); @@ -19,4 +27,7 @@ public interface AccountDao { @Query("SELECT * FROM accounts WHERE username = :userName COLLATE NOCASE LIMIT 1") Account getAccountData(String userName); + + @Query("SELECT * FROM accounts WHERE is_current_user = 1 LIMIT 1") + Account getCurrentAccount(); } diff --git a/app/src/main/java/Account/AccountRepository.java b/app/src/main/java/Account/AccountRepository.java index 49bdfacf..c495579d 100644 --- a/app/src/main/java/Account/AccountRepository.java +++ b/app/src/main/java/Account/AccountRepository.java @@ -1,17 +1,17 @@ package Account; -import android.app.Application; import android.os.AsyncTask; import androidx.lifecycle.LiveData; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + public class AccountRepository { private AccountDao mAccountDao; private LiveData<Account> mAccountLiveData; - AccountRepository(Application application, String username) { - mAccountDao = AccountRoomDatabase.getDatabase(application).accountDao(); - + AccountRepository(RedditDataRoomDatabase redditDataRoomDatabase, String username) { + mAccountDao = redditDataRoomDatabase.accountDao(); mAccountLiveData = mAccountDao.getAccountLiveData(username); } diff --git a/app/src/main/java/Account/AccountRoomDatabase.java b/app/src/main/java/Account/AccountRoomDatabase.java deleted file mode 100644 index 2f5d0120..00000000 --- a/app/src/main/java/Account/AccountRoomDatabase.java +++ /dev/null @@ -1,27 +0,0 @@ -package Account; - -import android.content.Context; - -import androidx.room.Database; -import androidx.room.Room; -import androidx.room.RoomDatabase; - -@Database(entities = {Account.class}, version = 1) -public abstract class AccountRoomDatabase extends RoomDatabase { - private static AccountRoomDatabase INSTANCE; - - public abstract AccountDao accountDao(); - - public static AccountRoomDatabase getDatabase(final Context context) { - if(INSTANCE == null) { - synchronized (AccountRoomDatabase.class) { - if(INSTANCE == null) { - INSTANCE = Room.databaseBuilder(context.getApplicationContext(), - AccountRoomDatabase.class, "accounts") - .build(); - } - } - } - return INSTANCE; - } -} diff --git a/app/src/main/java/Account/AccountViewModel.java b/app/src/main/java/Account/AccountViewModel.java index b649d9a7..ab6e9663 100644 --- a/app/src/main/java/Account/AccountViewModel.java +++ b/app/src/main/java/Account/AccountViewModel.java @@ -8,13 +8,15 @@ import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + public class AccountViewModel extends AndroidViewModel { private AccountRepository mAccountRepository; private LiveData<Account> mAccountLiveData; - public AccountViewModel(Application application, String id) { + public AccountViewModel(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String id) { super(application); - mAccountRepository = new AccountRepository(application, id); + mAccountRepository = new AccountRepository(redditDataRoomDatabase, id); mAccountLiveData = mAccountRepository.getAccountLiveData(); } @@ -30,18 +32,19 @@ public class AccountViewModel extends AndroidViewModel { @NonNull private final Application mApplication; + private final RedditDataRoomDatabase mRedditDataRoomDatabase; + private final String mUsername; - private final String userName; - - public Factory(@NonNull Application application, String userName) { + public Factory(@NonNull Application application, RedditDataRoomDatabase redditDataRoomDatabase, String username) { mApplication = application; - this.userName = userName; + mRedditDataRoomDatabase = redditDataRoomDatabase; + mUsername = username; } @Override public <T extends ViewModel> T create(Class<T> modelClass) { //noinspection unchecked - return (T) new AccountViewModel(mApplication, userName); + return (T) new AccountViewModel(mApplication, mRedditDataRoomDatabase, mUsername); } } } diff --git a/app/src/main/java/SubredditDatabase/SubredditData.java b/app/src/main/java/SubredditDatabase/SubredditData.java index 9af7204d..e1275809 100644 --- a/app/src/main/java/SubredditDatabase/SubredditData.java +++ b/app/src/main/java/SubredditDatabase/SubredditData.java @@ -1,29 +1,49 @@ package SubredditDatabase; +import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; -import androidx.annotation.NonNull; - -import SubscribedSubredditDatabase.SubscribedSubredditData; +import androidx.room.PrimaryKey; @Entity(tableName = "subreddits") -public class SubredditData extends SubscribedSubredditData { +public class SubredditData { + @PrimaryKey + @NonNull + @ColumnInfo(name = "id") + private String id; + @ColumnInfo(name = "name") + private String name; + @ColumnInfo(name = "icon") + private String iconUrl; @ColumnInfo(name = "banner") private String bannerUrl; - @ColumnInfo(name = "description") private String description; - @ColumnInfo(name = "subscribers_count") private int nSubscribers; public SubredditData(@NonNull String id, String name, String iconUrl, String bannerUrl, String description, int nSubscribers) { - super(id, name, iconUrl); + this.id = id; + this.name = name; + this.iconUrl = iconUrl; this.bannerUrl = bannerUrl; this.description = description; this.nSubscribers = nSubscribers; } + @NonNull + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getIconUrl() { + return iconUrl; + } + public String getBannerUrl() { return bannerUrl; } diff --git a/app/src/main/java/SubredditDatabase/SubredditRepository.java b/app/src/main/java/SubredditDatabase/SubredditRepository.java index 5e4cb7d7..2c66ad4b 100644 --- a/app/src/main/java/SubredditDatabase/SubredditRepository.java +++ b/app/src/main/java/SubredditDatabase/SubredditRepository.java @@ -1,17 +1,17 @@ package SubredditDatabase; -import android.app.Application; -import androidx.lifecycle.LiveData; import android.os.AsyncTask; +import androidx.lifecycle.LiveData; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + public class SubredditRepository { private SubredditDao mSubredditDao; private LiveData<SubredditData> mSubredditLiveData; - SubredditRepository(Application application, String subredditName) { - SubredditRoomDatabase db = SubredditRoomDatabase.getDatabase(application); - mSubredditDao = db.subredditDao(); - + SubredditRepository(RedditDataRoomDatabase redditDataRoomDatabase, String subredditName) { + mSubredditDao = redditDataRoomDatabase.subredditDao(); mSubredditLiveData = mSubredditDao.getSubredditLiveDataByName(subredditName); } diff --git a/app/src/main/java/SubredditDatabase/SubredditRoomDatabase.java b/app/src/main/java/SubredditDatabase/SubredditRoomDatabase.java deleted file mode 100644 index fa656b30..00000000 --- a/app/src/main/java/SubredditDatabase/SubredditRoomDatabase.java +++ /dev/null @@ -1,26 +0,0 @@ -package SubredditDatabase; - -import androidx.room.Database; -import androidx.room.Room; -import androidx.room.RoomDatabase; -import android.content.Context; - -@Database(entities = {SubredditData.class}, version = 1) -public abstract class SubredditRoomDatabase extends RoomDatabase{ - private static SubredditRoomDatabase INSTANCE; - - public abstract SubredditDao subredditDao(); - - public static SubredditRoomDatabase getDatabase(final Context context) { - if(INSTANCE == null) { - synchronized (SubredditRoomDatabase.class) { - if(INSTANCE == null) { - INSTANCE = Room.databaseBuilder(context.getApplicationContext(), - SubredditRoomDatabase.class, "subreddits") - .build(); - } - } - } - return INSTANCE; - } -} diff --git a/app/src/main/java/SubredditDatabase/SubredditViewModel.java b/app/src/main/java/SubredditDatabase/SubredditViewModel.java index 8899abdd..dc0247d2 100644 --- a/app/src/main/java/SubredditDatabase/SubredditViewModel.java +++ b/app/src/main/java/SubredditDatabase/SubredditViewModel.java @@ -7,13 +7,15 @@ import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import androidx.annotation.NonNull; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + public class SubredditViewModel extends AndroidViewModel { private SubredditRepository mSubredditRepository; private LiveData<SubredditData> mSubredditLiveData; - public SubredditViewModel(Application application, String id) { + public SubredditViewModel(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String id) { super(application); - mSubredditRepository = new SubredditRepository(application, id); + mSubredditRepository = new SubredditRepository(redditDataRoomDatabase, id); mSubredditLiveData = mSubredditRepository.getSubredditLiveData(); } @@ -29,19 +31,20 @@ public class SubredditViewModel extends AndroidViewModel { @NonNull private final Application mApplication; + private final RedditDataRoomDatabase mRedditDataRoomDatabase; + private final String mSubredditName; - private final String subredditName; - - public Factory(@NonNull Application application, String subredditName) { + public Factory(@NonNull Application application, RedditDataRoomDatabase redditDataRoomDatabase, String subredditname) { mApplication = application; - this.subredditName = subredditName; + mRedditDataRoomDatabase = redditDataRoomDatabase; + mSubredditName = subredditname; } @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { //noinspection unchecked - return (T) new SubredditViewModel(mApplication, subredditName); + return (T) new SubredditViewModel(mApplication, mRedditDataRoomDatabase, mSubredditName); } } } diff --git a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditDao.java b/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditDao.java index 3a5aa9be..6ddaf835 100644 --- a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditDao.java +++ b/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditDao.java @@ -16,12 +16,12 @@ public interface SubscribedSubredditDao { @Query("DELETE FROM subscribed_subreddits") void deleteAllSubscribedSubreddits(); - @Query("SELECT * from subscribed_subreddits ORDER BY name COLLATE NOCASE ASC") - LiveData<List<SubscribedSubredditData>> getAllSubscribedSubreddits(); + @Query("SELECT * from subscribed_subreddits WHERE username = :accountName ORDER BY name COLLATE NOCASE ASC") + LiveData<List<SubscribedSubredditData>> getAllSubscribedSubreddits(String accountName); - @Query("SELECT * from subscribed_subreddits WHERE name = :subredditName COLLATE NOCASE LIMIT 1") - SubscribedSubredditData getSubscribedSubreddit(String subredditName); + @Query("SELECT * from subscribed_subreddits WHERE name = :subredditName AND username = :accountName COLLATE NOCASE LIMIT 1") + SubscribedSubredditData getSubscribedSubreddit(String subredditName, String accountName); - @Query("DELETE FROM subscribed_subreddits WHERE name = :subredditName") - void deleteSubscribedSubreddit(String subredditName); + @Query("DELETE FROM subscribed_subreddits WHERE name = :subredditName AND username = :accountName") + void deleteSubscribedSubreddit(String subredditName, String accountName); } diff --git a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditData.java b/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditData.java index 4c6f1a49..bf2a87b8 100644 --- a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditData.java +++ b/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditData.java @@ -2,10 +2,14 @@ package SubscribedSubredditDatabase; import androidx.room.ColumnInfo; import androidx.room.Entity; +import androidx.room.ForeignKey; import androidx.room.PrimaryKey; import androidx.annotation.NonNull; -@Entity(tableName = "subscribed_subreddits") +import Account.Account; + +@Entity(tableName = "subscribed_subreddits", foreignKeys = @ForeignKey(entity = Account.class, parentColumns = "username", + childColumns = "username", onDelete = ForeignKey.CASCADE)) public class SubscribedSubredditData { @PrimaryKey @@ -16,11 +20,14 @@ public class SubscribedSubredditData { private String name; @ColumnInfo(name = "icon") private String iconUrl; + @ColumnInfo(name = "username") + private String username; - public SubscribedSubredditData(@NonNull String id, String name, String iconUrl) { + public SubscribedSubredditData(@NonNull String id, String name, String iconUrl, String username) { this.id = id; this.name = name; this.iconUrl = iconUrl; + this.username = username; } @NonNull @@ -35,4 +42,12 @@ public class SubscribedSubredditData { public String getIconUrl() { return iconUrl; } + + public void setUsername(String username) { + this.username = username; + } + + public String getUsername() { + return username; + } } diff --git a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditRepository.java b/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditRepository.java index 02bb7881..1cbf8824 100644 --- a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditRepository.java +++ b/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditRepository.java @@ -1,19 +1,20 @@ package SubscribedSubredditDatabase; -import android.app.Application; -import androidx.lifecycle.LiveData; import android.os.AsyncTask; +import androidx.lifecycle.LiveData; + import java.util.List; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + public class SubscribedSubredditRepository { private SubscribedSubredditDao mSubscribedSubredditDao; private LiveData<List<SubscribedSubredditData>> mAllSubscribedSubreddits; - SubscribedSubredditRepository(Application application) { - SubscribedSubredditRoomDatabase db = SubscribedSubredditRoomDatabase.getDatabase(application); - mSubscribedSubredditDao = db.subscribedSubredditDao(); - mAllSubscribedSubreddits = mSubscribedSubredditDao.getAllSubscribedSubreddits(); + SubscribedSubredditRepository(RedditDataRoomDatabase redditDataRoomDatabase, String accountName) { + mSubscribedSubredditDao = redditDataRoomDatabase.subscribedSubredditDao(); + mAllSubscribedSubreddits = mSubscribedSubredditDao.getAllSubscribedSubreddits(accountName); } LiveData<List<SubscribedSubredditData>> getAllSubscribedSubreddits() { diff --git a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditRoomDatabase.java b/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditRoomDatabase.java deleted file mode 100644 index 48602fcc..00000000 --- a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditRoomDatabase.java +++ /dev/null @@ -1,26 +0,0 @@ -package SubscribedSubredditDatabase; - -import androidx.room.Database; -import androidx.room.Room; -import androidx.room.RoomDatabase; -import android.content.Context; - -@Database(entities = {SubscribedSubredditData.class}, version = 1) -public abstract class SubscribedSubredditRoomDatabase extends RoomDatabase { - private static SubscribedSubredditRoomDatabase INSTANCE; - - public abstract SubscribedSubredditDao subscribedSubredditDao(); - - public static SubscribedSubredditRoomDatabase getDatabase(final Context context) { - if(INSTANCE == null) { - synchronized (SubscribedSubredditRoomDatabase.class) { - if(INSTANCE == null) { - INSTANCE = Room.databaseBuilder(context.getApplicationContext(), - SubscribedSubredditRoomDatabase.class, "subscribed_subreddits") - .build(); - } - } - } - return INSTANCE; - } -} diff --git a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditViewModel.java b/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditViewModel.java index 9ed8ac93..d062f9d9 100644 --- a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditViewModel.java +++ b/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditViewModel.java @@ -1,18 +1,24 @@ package SubscribedSubredditDatabase; import android.app.Application; + +import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; +import androidx.lifecycle.ViewModel; +import androidx.lifecycle.ViewModelProvider; import java.util.List; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + public class SubscribedSubredditViewModel extends AndroidViewModel { private SubscribedSubredditRepository mSubscribedSubredditRepository; private LiveData<List<SubscribedSubredditData>> mAllSubscribedSubreddits; - public SubscribedSubredditViewModel(Application application) { + public SubscribedSubredditViewModel(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) { super(application); - mSubscribedSubredditRepository = new SubscribedSubredditRepository(application); + mSubscribedSubredditRepository = new SubscribedSubredditRepository(redditDataRoomDatabase, accountName); mAllSubscribedSubreddits = mSubscribedSubredditRepository.getAllSubscribedSubreddits(); } @@ -23,4 +29,22 @@ public class SubscribedSubredditViewModel extends AndroidViewModel { public void insert(SubscribedSubredditData subscribedSubredditData) { mSubscribedSubredditRepository.insert(subscribedSubredditData); } + + public static class Factory extends ViewModelProvider.NewInstanceFactory { + private Application mApplication; + private RedditDataRoomDatabase mRedditDataRoomDatabase; + private String mAccountName; + + public Factory(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) { + this.mApplication = application; + this.mRedditDataRoomDatabase = redditDataRoomDatabase; + this.mAccountName = accountName; + } + + @NonNull + @Override + public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { + return (T) new SubscribedSubredditViewModel(mApplication, mRedditDataRoomDatabase, mAccountName); + } + } } diff --git a/app/src/main/java/SubscribedUserDatabase/SubscribedUserDao.java b/app/src/main/java/SubscribedUserDatabase/SubscribedUserDao.java index 711b02a6..513a1ea4 100644 --- a/app/src/main/java/SubscribedUserDatabase/SubscribedUserDao.java +++ b/app/src/main/java/SubscribedUserDatabase/SubscribedUserDao.java @@ -16,12 +16,12 @@ public interface SubscribedUserDao { @Query("DELETE FROM subscribed_users") void deleteAllSubscribedUsers(); - @Query("SELECT * FROM subscribed_users ORDER BY name COLLATE NOCASE ASC") - LiveData<List<SubscribedUserData>> getAllSubscribedUsers(); + @Query("SELECT * FROM subscribed_users WHERE username = :accountName ORDER BY name COLLATE NOCASE ASC") + LiveData<List<SubscribedUserData>> getAllSubscribedUsers(String accountName); - @Query("SELECT * FROM subscribed_users WHERE name = :userName COLLATE NOCASE LIMIT 1") - SubscribedUserData getSubscribedUser(String userName); + @Query("SELECT * FROM subscribed_users WHERE name = :name AND username = :accountName COLLATE NOCASE LIMIT 1") + SubscribedUserData getSubscribedUser(String name, String accountName); - @Query("DELETE FROM subscribed_users WHERE name = :userName") - void deleteSubscribedUser(String userName); + @Query("DELETE FROM subscribed_users WHERE name = :name AND username = :accountName") + void deleteSubscribedUser(String name, String accountName); } diff --git a/app/src/main/java/SubscribedUserDatabase/SubscribedUserData.java b/app/src/main/java/SubscribedUserDatabase/SubscribedUserData.java index 98c5a971..8ea89e04 100644 --- a/app/src/main/java/SubscribedUserDatabase/SubscribedUserData.java +++ b/app/src/main/java/SubscribedUserDatabase/SubscribedUserData.java @@ -1,11 +1,15 @@ package SubscribedUserDatabase; +import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; +import androidx.room.ForeignKey; import androidx.room.PrimaryKey; -import androidx.annotation.NonNull; -@Entity(tableName = "subscribed_users") +import Account.Account; + +@Entity(tableName = "subscribed_users", foreignKeys = @ForeignKey(entity = Account.class, parentColumns = "username", + childColumns = "username", onDelete = ForeignKey.CASCADE)) public class SubscribedUserData { @PrimaryKey @NonNull @@ -13,10 +17,13 @@ public class SubscribedUserData { private String name; @ColumnInfo(name = "icon") private String iconUrl; + @ColumnInfo(name = "username") + private String username; - public SubscribedUserData(@NonNull String name, String iconUrl) { + public SubscribedUserData(@NonNull String name, String iconUrl, String username) { this.name = name; this.iconUrl = iconUrl; + this.username = username; } @NonNull @@ -27,4 +34,12 @@ public class SubscribedUserData { public String getIconUrl() { return iconUrl; } + + public void setUsername(String username) { + this.username = username; + } + + public String getUsername() { + return username; + } } diff --git a/app/src/main/java/SubscribedUserDatabase/SubscribedUserRepository.java b/app/src/main/java/SubscribedUserDatabase/SubscribedUserRepository.java index 10549113..eb588958 100644 --- a/app/src/main/java/SubscribedUserDatabase/SubscribedUserRepository.java +++ b/app/src/main/java/SubscribedUserDatabase/SubscribedUserRepository.java @@ -1,19 +1,20 @@ package SubscribedUserDatabase; -import android.app.Application; -import androidx.lifecycle.LiveData; import android.os.AsyncTask; +import androidx.lifecycle.LiveData; + import java.util.List; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + public class SubscribedUserRepository { private SubscribedUserDao mSubscribedUserDao; private LiveData<List<SubscribedUserData>> mAllSubscribedUsers; - SubscribedUserRepository(Application application) { - SubscribedUserRoomDatabase db = SubscribedUserRoomDatabase.getDatabase(application); - mSubscribedUserDao = db.subscribedUserDao(); - mAllSubscribedUsers = mSubscribedUserDao.getAllSubscribedUsers(); + SubscribedUserRepository(RedditDataRoomDatabase redditDataRoomDatabase, String accountName) { + mSubscribedUserDao = redditDataRoomDatabase.subscribedUserDao(); + mAllSubscribedUsers = mSubscribedUserDao.getAllSubscribedUsers(accountName); } LiveData<List<SubscribedUserData>> getAllSubscribedSubreddits() { diff --git a/app/src/main/java/SubscribedUserDatabase/SubscribedUserRoomDatabase.java b/app/src/main/java/SubscribedUserDatabase/SubscribedUserRoomDatabase.java deleted file mode 100644 index 12e6fb90..00000000 --- a/app/src/main/java/SubscribedUserDatabase/SubscribedUserRoomDatabase.java +++ /dev/null @@ -1,26 +0,0 @@ -package SubscribedUserDatabase; - -import androidx.room.Database; -import androidx.room.Room; -import androidx.room.RoomDatabase; -import android.content.Context; - -@Database(entities = {SubscribedUserData.class}, version = 1) -public abstract class SubscribedUserRoomDatabase extends RoomDatabase { - private static SubscribedUserRoomDatabase INSTANCE; - - public abstract SubscribedUserDao subscribedUserDao(); - - public static SubscribedUserRoomDatabase getDatabase(final Context context) { - if(INSTANCE == null) { - synchronized (SubscribedUserRoomDatabase.class) { - if(INSTANCE == null) { - INSTANCE = Room.databaseBuilder(context.getApplicationContext(), - SubscribedUserRoomDatabase.class, "subscribed_users") - .build(); - } - } - } - return INSTANCE; - } -} diff --git a/app/src/main/java/SubscribedUserDatabase/SubscribedUserViewModel.java b/app/src/main/java/SubscribedUserDatabase/SubscribedUserViewModel.java index ed1db58f..387c918c 100644 --- a/app/src/main/java/SubscribedUserDatabase/SubscribedUserViewModel.java +++ b/app/src/main/java/SubscribedUserDatabase/SubscribedUserViewModel.java @@ -1,18 +1,24 @@ package SubscribedUserDatabase; import android.app.Application; + +import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; +import androidx.lifecycle.ViewModel; +import androidx.lifecycle.ViewModelProvider; import java.util.List; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + public class SubscribedUserViewModel extends AndroidViewModel { private SubscribedUserRepository mSubscribedUserRepository; private LiveData<List<SubscribedUserData>> mAllSubscribedUsers; - public SubscribedUserViewModel(Application application) { + public SubscribedUserViewModel(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) { super(application); - mSubscribedUserRepository = new SubscribedUserRepository(application); + mSubscribedUserRepository = new SubscribedUserRepository(redditDataRoomDatabase, accountName); mAllSubscribedUsers = mSubscribedUserRepository.getAllSubscribedSubreddits(); } @@ -23,4 +29,22 @@ public class SubscribedUserViewModel extends AndroidViewModel { public void insert(SubscribedUserData subscribedUserData) { mSubscribedUserRepository.insert(subscribedUserData); } + + public static class Factory extends ViewModelProvider.NewInstanceFactory { + private Application mApplication; + private RedditDataRoomDatabase mRedditDataRoomDatabase; + private String mAccountName; + + public Factory(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) { + mApplication = application; + mRedditDataRoomDatabase = redditDataRoomDatabase; + mAccountName = accountName; + } + + @NonNull + @Override + public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { + return (T) new SubscribedUserViewModel(mApplication, mRedditDataRoomDatabase, mAccountName); + } + } } diff --git a/app/src/main/java/User/UserData.java b/app/src/main/java/User/UserData.java index c334c289..b3f71029 100644 --- a/app/src/main/java/User/UserData.java +++ b/app/src/main/java/User/UserData.java @@ -1,13 +1,18 @@ package User; +import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; -import androidx.annotation.NonNull; - -import SubscribedUserDatabase.SubscribedUserData; +import androidx.room.PrimaryKey; @Entity(tableName = "users") -public class UserData extends SubscribedUserData { +public class UserData { + @PrimaryKey + @NonNull + @ColumnInfo(name = "name") + private String name; + @ColumnInfo(name = "icon") + private String iconUrl; @ColumnInfo(name = "banner") private String banner; @ColumnInfo(name = "karma") @@ -20,7 +25,8 @@ public class UserData extends SubscribedUserData { private boolean canBeFollowed; public UserData(@NonNull String name, String iconUrl, String banner, int karma, boolean isGold, boolean isFriend, boolean canBeFollowed) { - super(name, iconUrl); + this.name = name; + this.iconUrl = iconUrl; this.banner = banner; this.karma = karma; this.isGold = isGold; @@ -28,6 +34,15 @@ public class UserData extends SubscribedUserData { this.canBeFollowed = canBeFollowed; } + @NonNull + public String getName() { + return name; + } + + public String getIconUrl() { + return iconUrl; + } + public String getBanner() { return banner; } diff --git a/app/src/main/java/User/UserRepository.java b/app/src/main/java/User/UserRepository.java index b9e36ea4..d781a694 100644 --- a/app/src/main/java/User/UserRepository.java +++ b/app/src/main/java/User/UserRepository.java @@ -1,16 +1,17 @@ package User; -import android.app.Application; -import androidx.lifecycle.LiveData; import android.os.AsyncTask; +import androidx.lifecycle.LiveData; + +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + public class UserRepository { private UserDao mUserDao; private LiveData<UserData> mUserLiveData; - UserRepository(Application application, String userName) { - mUserDao = UserRoomDatabase.getDatabase(application).userDao(); - + UserRepository(RedditDataRoomDatabase redditDataRoomDatabase, String userName) { + mUserDao = redditDataRoomDatabase.userDao(); mUserLiveData = mUserDao.getUserLiveData(userName); } diff --git a/app/src/main/java/User/UserRoomDatabase.java b/app/src/main/java/User/UserRoomDatabase.java deleted file mode 100644 index 7faa7e2c..00000000 --- a/app/src/main/java/User/UserRoomDatabase.java +++ /dev/null @@ -1,26 +0,0 @@ -package User; - -import androidx.room.Database; -import androidx.room.Room; -import androidx.room.RoomDatabase; -import android.content.Context; - -@Database(entities = {UserData.class}, version = 1) -public abstract class UserRoomDatabase extends RoomDatabase { - private static UserRoomDatabase INSTANCE; - - public abstract UserDao userDao(); - - public static UserRoomDatabase getDatabase(final Context context) { - if(INSTANCE == null) { - synchronized (UserRoomDatabase.class) { - if(INSTANCE == null) { - INSTANCE = Room.databaseBuilder(context.getApplicationContext(), - UserRoomDatabase.class, "users") - .build(); - } - } - } - return INSTANCE; - } -} diff --git a/app/src/main/java/User/UserViewModel.java b/app/src/main/java/User/UserViewModel.java index aab98645..2c746cad 100644 --- a/app/src/main/java/User/UserViewModel.java +++ b/app/src/main/java/User/UserViewModel.java @@ -7,13 +7,15 @@ import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import androidx.annotation.NonNull; +import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; + public class UserViewModel extends AndroidViewModel { private UserRepository mSubredditRepository; private LiveData<UserData> mUserLiveData; - public UserViewModel(Application application, String id) { + public UserViewModel(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String id) { super(application); - mSubredditRepository = new UserRepository(application, id); + mSubredditRepository = new UserRepository(redditDataRoomDatabase, id); mUserLiveData = mSubredditRepository.getUserLiveData(); } @@ -29,18 +31,19 @@ public class UserViewModel extends AndroidViewModel { @NonNull private final Application mApplication; + private final RedditDataRoomDatabase mRedditDataRoomDatabase; + private final String mUsername; - private final String userName; - - public Factory(@NonNull Application application, String userName) { + public Factory(@NonNull Application application, RedditDataRoomDatabase redditDataRoomDatabase, String username) { mApplication = application; - this.userName = userName; + mRedditDataRoomDatabase = redditDataRoomDatabase; + mUsername = username; } @Override public <T extends ViewModel> T create(Class<T> modelClass) { //noinspection unchecked - return (T) new UserViewModel(mApplication, userName); + return (T) new UserViewModel(mApplication, mRedditDataRoomDatabase, mUsername); } } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/AccessTokenAuthenticator.java b/app/src/main/java/ml/docilealligator/infinityforreddit/AccessTokenAuthenticator.java index 2aebbd52..0c568a06 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/AccessTokenAuthenticator.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/AccessTokenAuthenticator.java @@ -1,8 +1,10 @@ package ml.docilealligator.infinityforreddit; -import android.content.SharedPreferences; import android.util.Log; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + import org.json.JSONException; import org.json.JSONObject; @@ -10,8 +12,7 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; +import Account.Account; import okhttp3.Authenticator; import okhttp3.Headers; import okhttp3.Request; @@ -22,37 +23,38 @@ import retrofit2.Retrofit; class AccessTokenAuthenticator implements Authenticator { private Retrofit mRetrofit; - private SharedPreferences mAuthInfoSharedPreferences; + private RedditDataRoomDatabase mRedditDataRoomDatabase; - AccessTokenAuthenticator(Retrofit retrofit, SharedPreferences authInfoSharedPreferences) { + AccessTokenAuthenticator(Retrofit retrofit, RedditDataRoomDatabase accountRoomDatabase) { mRetrofit = retrofit; - mAuthInfoSharedPreferences = authInfoSharedPreferences; + mRedditDataRoomDatabase = accountRoomDatabase; } @Nullable @Override - public Request authenticate(@NonNull Route route, @NonNull Response response) { + public Request authenticate(Route route, @NonNull Response response) { if (response.code() == 401) { String accessToken = response.request().header(RedditUtils.AUTHORIZATION_KEY).substring(RedditUtils.AUTHORIZATION_BASE.length()); synchronized (this) { - String accessTokenFromSharedPreferences = mAuthInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); - if (accessToken.equals(accessTokenFromSharedPreferences)) { - String newAccessToken = refreshAccessToken(); + Account account = mRedditDataRoomDatabase.accountDao().getCurrentAccount(); + String accessTokenFromDatabase = account.getAccessToken(); + if (accessToken.equals(accessTokenFromDatabase)) { + String newAccessToken = refreshAccessToken(account); if (!newAccessToken.equals("")) { return response.request().newBuilder().headers(Headers.of(RedditUtils.getOAuthHeader(newAccessToken))).build(); } else { return null; } } else { - return response.request().newBuilder().headers(Headers.of(RedditUtils.getOAuthHeader(accessTokenFromSharedPreferences))).build(); + return response.request().newBuilder().headers(Headers.of(RedditUtils.getOAuthHeader(accessTokenFromDatabase))).build(); } } } return null; } - private String refreshAccessToken() { - String refreshToken = mAuthInfoSharedPreferences.getString(SharedPreferencesUtils.REFRESH_TOKEN_KEY, ""); + private String refreshAccessToken(Account account) { + String refreshToken = mRedditDataRoomDatabase.accountDao().getCurrentAccount().getRefreshToken(); RedditAPI api = mRetrofit.create(RedditAPI.class); @@ -63,11 +65,14 @@ class AccessTokenAuthenticator implements Authenticator { Call<String> accessTokenCall = api.getAccessToken(RedditUtils.getHttpBasicAuthHeader(), params); try { retrofit2.Response response = accessTokenCall.execute(); - JSONObject jsonObject = new JSONObject((String) response.body()); + if(response.body() == null) { + return ""; + } + JSONObject jsonObject = new JSONObject((String) response.body()); String newAccessToken = jsonObject.getString(RedditUtils.ACCESS_TOKEN_KEY); - - mAuthInfoSharedPreferences.edit().putString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, newAccessToken).apply(); + account.setAccessToken(newAccessToken); + mRedditDataRoomDatabase.accountDao().insert(account); Log.i("access token", newAccessToken); return newAccessToken; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java b/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java index 3f93717a..12997920 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java @@ -26,4 +26,8 @@ interface AppComponent { void inject(RulesActivity rulesActivity); void inject(CommentsListingFragment commentsListingFragment); void inject(SubmitPostService submitPostService); + void inject(FilteredPostsActivity filteredPostsActivity); + void inject(SearchResultActivity searchResultActivity); + void inject(SearchSubredditsResultActivity searchSubredditsResultActivity); + void inject(FollowedUsersListingFragment followedUsersListingFragment); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/AppModule.java b/app/src/main/java/ml/docilealligator/infinityforreddit/AppModule.java index d690b164..76afe22c 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/AppModule.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/AppModule.java @@ -60,9 +60,9 @@ class AppModule { @Provides @Singleton - OkHttpClient provideOkHttpClient(@Named("no_oauth") Retrofit retrofit, @Named("auth_info") SharedPreferences sharedPreferences) { + OkHttpClient provideOkHttpClient(@Named("no_oauth") Retrofit retrofit, RedditDataRoomDatabase accountRoomDatabase) { OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder(); - okHttpClientBuilder.authenticator(new AccessTokenAuthenticator(retrofit, sharedPreferences)); + okHttpClientBuilder.authenticator(new AccessTokenAuthenticator(retrofit, accountRoomDatabase)); return okHttpClientBuilder.build(); } @@ -76,4 +76,10 @@ class AppModule { SharedPreferences provideUserInfoSharedPreferences() { return mApplication.getSharedPreferences(SharedPreferencesUtils.USER_INFO_FILE_KEY, Context.MODE_PRIVATE); } + + @Provides + @Singleton + RedditDataRoomDatabase provideRedditDataRoomDatabase() { + return RedditDataRoomDatabase.getDatabase(mApplication); + } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/CheckIsFollowingUserAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/CheckIsFollowingUserAsyncTask.java index 4d75d155..cc4f75af 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/CheckIsFollowingUserAsyncTask.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/CheckIsFollowingUserAsyncTask.java @@ -7,7 +7,8 @@ import SubscribedUserDatabase.SubscribedUserData; public class CheckIsFollowingUserAsyncTask extends AsyncTask<Void, Void, Void> { private SubscribedUserDao subscribedUserDao; - private String userName; + private String username; + private String accountName; private SubscribedUserData subscribedUserData; private CheckIsFollowingUserListener checkIsFollowingUserListener; @@ -16,16 +17,17 @@ public class CheckIsFollowingUserAsyncTask extends AsyncTask<Void, Void, Void> { void isNotSubscribed(); } - CheckIsFollowingUserAsyncTask(SubscribedUserDao subscribedUserDao, String userName, + CheckIsFollowingUserAsyncTask(SubscribedUserDao subscribedUserDao, String username, String accountName, CheckIsFollowingUserListener checkIsFollowingUserListener) { this.subscribedUserDao = subscribedUserDao; - this.userName = userName; + this.username = username; + this.accountName = accountName; this.checkIsFollowingUserListener = checkIsFollowingUserListener; } @Override protected Void doInBackground(Void... voids) { - subscribedUserData = subscribedUserDao.getSubscribedUser(userName); + subscribedUserData = subscribedUserDao.getSubscribedUser(username, accountName); return null; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/CheckIsSubscribedToSubredditAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/CheckIsSubscribedToSubredditAsyncTask.java index d1cf3cf1..ee78c566 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/CheckIsSubscribedToSubredditAsyncTask.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/CheckIsSubscribedToSubredditAsyncTask.java @@ -9,6 +9,7 @@ class CheckIsSubscribedToSubredditAsyncTask extends AsyncTask<Void, Void, Void> private SubscribedSubredditDao subscribedSubredditDao; private String subredditName; + private String accountName; private SubscribedSubredditData subscribedSubredditData; private CheckIsSubscribedToSubredditListener checkIsSubscribedToSubredditListener; @@ -17,16 +18,18 @@ class CheckIsSubscribedToSubredditAsyncTask extends AsyncTask<Void, Void, Void> void isNotSubscribed(); } - CheckIsSubscribedToSubredditAsyncTask(SubscribedSubredditDao subscribedSubredditDao, String subredditName, + CheckIsSubscribedToSubredditAsyncTask(SubscribedSubredditDao subscribedSubredditDao, + String subredditName, String accountName, CheckIsSubscribedToSubredditListener checkIsSubscribedToSubredditListener) { this.subscribedSubredditDao = subscribedSubredditDao; this.subredditName =subredditName; + this.accountName = accountName; this.checkIsSubscribedToSubredditListener = checkIsSubscribedToSubredditListener; } @Override protected Void doInBackground(Void... voids) { - subscribedSubredditData = subscribedSubredditDao.getSubscribedSubreddit(subredditName); + subscribedSubredditData = subscribedSubredditDao.getSubscribedSubreddit(subredditName, accountName); return null; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/CommentAndPostRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/CommentAndPostRecyclerViewAdapter.java index dcd2801a..0360abe8 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/CommentAndPostRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/CommentAndPostRecyclerViewAdapter.java @@ -2,7 +2,6 @@ package ml.docilealligator.infinityforreddit; import android.app.Activity; import android.content.Intent; -import android.content.SharedPreferences; import android.graphics.ColorFilter; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; @@ -40,8 +39,6 @@ import java.util.Locale; import CustomView.AspectRatioGifImageView; import CustomView.CustomMarkwonView; -import SubredditDatabase.SubredditRoomDatabase; -import User.UserRoomDatabase; import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.glide.transformations.BlurTransformation; @@ -61,8 +58,9 @@ class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVie private Activity mActivity; private Retrofit mRetrofit; private Retrofit mOauthRetrofit; + private RedditDataRoomDatabase mRedditDataRoomDatabase; private RequestManager mGlide; - private SharedPreferences mSharedPreferences; + private String mAccessToken; private Post mPost; private ArrayList<CommentData> mVisibleComments; private String mSubredditNamePrefixed; @@ -79,15 +77,17 @@ class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVie void retryFetchingMoreComments(); } - CommentAndPostRecyclerViewAdapter(Activity activity, Retrofit retrofit, Retrofit oauthRetrofit, RequestManager glide, - SharedPreferences sharedPreferences, Post post, String subredditNamePrefixed, + CommentAndPostRecyclerViewAdapter(Activity activity, Retrofit retrofit, Retrofit oauthRetrofit, + RedditDataRoomDatabase redditDataRoomDatabase, RequestManager glide, + String accessToken, Post post, String subredditNamePrefixed, Locale locale, LoadSubredditIconAsyncTask loadSubredditIconAsyncTask, CommentRecyclerViewAdapterCallback commentRecyclerViewAdapterCallback) { mActivity = activity; mRetrofit = retrofit; mOauthRetrofit = oauthRetrofit; + mRedditDataRoomDatabase = redditDataRoomDatabase; mGlide = glide; - mSharedPreferences = sharedPreferences; + mAccessToken = accessToken; mPost = post; mVisibleComments = new ArrayList<>(); mSubredditNamePrefixed = subredditNamePrefixed; @@ -164,7 +164,7 @@ class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVie if(mPost.getSubredditNamePrefixed().equals("u/" + mPost.getAuthor())) { if(mPost.getAuthorIconUrl() == null) { - new LoadUserDataAsyncTask(UserRoomDatabase.getDatabase(mActivity).userDao(), mPost.getAuthor(), mOauthRetrofit, iconImageUrl -> { + new LoadUserDataAsyncTask(mRedditDataRoomDatabase.userDao(), mPost.getAuthor(), mOauthRetrofit, iconImageUrl -> { if(mActivity != null && getItemCount() > 0) { if(iconImageUrl == null || iconImageUrl.equals("")) { mGlide.load(R.drawable.subreddit_default_icon) @@ -200,7 +200,7 @@ class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVie mLoadSubredditIconAsyncTask.cancel(true); } mLoadSubredditIconAsyncTask = new LoadSubredditIconAsyncTask( - SubredditRoomDatabase.getDatabase(mActivity).subredditDao(), mPost.getSubredditNamePrefixed().substring(2), + mRedditDataRoomDatabase.subredditDao(), mPost.getSubredditNamePrefixed().substring(2), mRetrofit, iconImageUrl -> { if(iconImageUrl == null || iconImageUrl.equals("")) { mGlide.load(R.drawable.subreddit_default_icon) @@ -749,7 +749,7 @@ class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVie mCommentRecyclerViewAdapterCallback.updatePost(mPost); - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { + VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingWithoutPositionListener() { @Override public void onVoteThingSuccess() { if(newVoteType.equals(RedditUtils.DIR_UPVOTE)) { @@ -808,7 +808,7 @@ class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVie mCommentRecyclerViewAdapterCallback.updatePost(mPost); - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { + VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingWithoutPositionListener() { @Override public void onVoteThingSuccess() { if(newVoteType.equals(RedditUtils.DIR_DOWNVOTE)) { @@ -911,7 +911,7 @@ class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVie scoreTextView.setText(Integer.toString(mVisibleComments.get(getAdapterPosition() - 1).getScore() + mVisibleComments.get(getAdapterPosition() - 1).getVoteType())); - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { + VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() { @Override public void onVoteThingSuccess(int position) { if(newVoteType.equals(RedditUtils.DIR_UPVOTE)) { @@ -951,7 +951,7 @@ class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVie scoreTextView.setText(Integer.toString(mVisibleComments.get(getAdapterPosition() - 1).getScore() + mVisibleComments.get(getAdapterPosition() - 1).getVoteType())); - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { + VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() { @Override public void onVoteThingSuccess(int position1) { if(newVoteType.equals(RedditUtils.DIR_DOWNVOTE)) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/CommentsListingFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/CommentsListingFragment.java index fbe4a7a6..7a4e1fef 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/CommentsListingFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/CommentsListingFragment.java @@ -3,7 +3,6 @@ package ml.docilealligator.infinityforreddit; import android.app.Activity; import android.content.Context; -import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; @@ -37,6 +36,7 @@ import retrofit2.Retrofit; public class CommentsListingFragment extends Fragment implements FragmentCommunicator { static final String EXTRA_USERNAME_KEY = "ENK"; + static final String EXTRA_ACCESS_TOKEN = "EAT"; @BindView(R.id.coordinator_layout_comments_listing_fragment) CoordinatorLayout mCoordinatorLayout; @BindView(R.id.recycler_view_comments_listing_fragment) RecyclerView mCommentRecyclerView; @@ -60,9 +60,6 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni @Inject @Named("oauth") Retrofit mOauthRetrofit; - @Inject @Named("auth_info") - SharedPreferences mSharedPreferences; - public CommentsListingFragment() { // Required empty public constructor } @@ -83,7 +80,7 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni CommentViewModel.Factory factory; mAdapter = new CommentsListingRecyclerViewAdapter(activity, mOauthRetrofit, - mSharedPreferences, () -> mCommentViewModel.retryLoadingMore()); + getArguments().getString(EXTRA_ACCESS_TOKEN), () -> mCommentViewModel.retryLoadingMore()); String username = getArguments().getString(EXTRA_USERNAME_KEY); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/CommentsListingRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/CommentsListingRecyclerViewAdapter.java index 6aac6a53..e61cca11 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/CommentsListingRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/CommentsListingRecyclerViewAdapter.java @@ -2,7 +2,6 @@ package ml.docilealligator.infinityforreddit; import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -28,9 +27,9 @@ import retrofit2.Retrofit; class CommentsListingRecyclerViewAdapter extends PagedListAdapter<CommentData, RecyclerView.ViewHolder> { private Context mContext; private Retrofit mOauthRetrofit; - private SharedPreferences mSharedPreferences; - private int textColorPrimaryDark; - private int colorAccent; + private String mAccessToken; + private int mTextColorPrimaryDark; + private int mColorAccent; private static final int VIEW_TYPE_DATA = 0; private static final int VIEW_TYPE_ERROR = 1; @@ -43,15 +42,15 @@ class CommentsListingRecyclerViewAdapter extends PagedListAdapter<CommentData, R void retryLoadingMore(); } - protected CommentsListingRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, SharedPreferences sharedPreferences, + protected CommentsListingRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, String accessToken, RetryLoadingMoreCallback retryLoadingMoreCallback) { super(DIFF_CALLBACK); mContext = context; mOauthRetrofit = oauthRetrofit; - mSharedPreferences = sharedPreferences; + mAccessToken = accessToken; mRetryLoadingMoreCallback = retryLoadingMoreCallback; - textColorPrimaryDark = mContext.getResources().getColor(R.color.textColorPrimaryDark); - colorAccent = mContext.getResources().getColor(R.color.colorAccent); + mTextColorPrimaryDark = mContext.getResources().getColor(R.color.textColorPrimaryDark); + mColorAccent = mContext.getResources().getColor(R.color.colorAccent); } private static final DiffUtil.ItemCallback<CommentData> DIFF_CALLBACK = new DiffUtil.ItemCallback<CommentData>() { @@ -88,7 +87,7 @@ class CommentsListingRecyclerViewAdapter extends PagedListAdapter<CommentData, R if(comment.getAuthor().equals(comment.getSubredditName().substring(2))) { ((DataViewHolder) holder).authorTextView.setText("u/" + comment.getAuthor()); - ((DataViewHolder) holder).authorTextView.setTextColor(textColorPrimaryDark); + ((DataViewHolder) holder).authorTextView.setTextColor(mTextColorPrimaryDark); ((DataViewHolder) holder).authorTextView.setOnClickListener(view -> { Intent intent = new Intent(mContext, ViewUserDetailActivity.class); intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, comment.getAuthor()); @@ -96,7 +95,7 @@ class CommentsListingRecyclerViewAdapter extends PagedListAdapter<CommentData, R }); } else { ((DataViewHolder) holder).authorTextView.setText("r/" + comment.getSubredditName()); - ((DataViewHolder) holder).authorTextView.setTextColor(colorAccent); + ((DataViewHolder) holder).authorTextView.setTextColor(mColorAccent); ((DataViewHolder) holder).authorTextView.setOnClickListener(view -> { Intent intent = new Intent(mContext, ViewSubredditDetailActivity.class); intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, comment.getSubredditName()); @@ -225,7 +224,7 @@ class CommentsListingRecyclerViewAdapter extends PagedListAdapter<CommentData, R scoreTextView.setText(Integer.toString(getItem(getAdapterPosition()).getScore() + getItem(getAdapterPosition()).getVoteType())); - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { + VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() { @Override public void onVoteThingSuccess(int position) { if(newVoteType.equals(RedditUtils.DIR_UPVOTE)) { @@ -265,7 +264,7 @@ class CommentsListingRecyclerViewAdapter extends PagedListAdapter<CommentData, R scoreTextView.setText(Integer.toString(getItem(getAdapterPosition()).getScore() + getItem(getAdapterPosition()).getVoteType())); - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { + VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() { @Override public void onVoteThingSuccess(int position1) { if(newVoteType.equals(RedditUtils.DIR_DOWNVOTE)) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/FetchMyInfo.java b/app/src/main/java/ml/docilealligator/infinityforreddit/FetchMyInfo.java index 63b80532..33dd4f02 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/FetchMyInfo.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/FetchMyInfo.java @@ -1,6 +1,5 @@ package ml.docilealligator.infinityforreddit; -import android.content.SharedPreferences; import android.util.Log; import androidx.annotation.NonNull; @@ -16,31 +15,6 @@ class FetchMyInfo { void onFetchMyInfoFail(); } - static void fetchMyInfo(final Retrofit retrofit, SharedPreferences authInfoSharedPreferences, - final FetchUserMyListener fetchUserMyListener) { - RedditAPI api = retrofit.create(RedditAPI.class); - - String accessToken = authInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); - Call<String> userInfo = api.getMyInfo(RedditUtils.getOAuthHeader(accessToken)); - userInfo.enqueue(new Callback<String>() { - @Override - public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) { - if(response.isSuccessful()) { - fetchUserMyListener.onFetchMyInfoSuccess(response.body()); - } else { - Log.i("call failed", response.message()); - fetchUserMyListener.onFetchMyInfoFail(); - } - } - - @Override - public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { - Log.i("call failed", t.getMessage()); - fetchUserMyListener.onFetchMyInfoFail(); - } - }); - } - static void fetchMyInfo(final Retrofit retrofit, String accessToken, final FetchUserMyListener fetchUserMyListener) { RedditAPI api = retrofit.create(RedditAPI.class); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/FetchSubscribedThing.java b/app/src/main/java/ml/docilealligator/infinityforreddit/FetchSubscribedThing.java index c0a96870..a6376432 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/FetchSubscribedThing.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/FetchSubscribedThing.java @@ -1,9 +1,9 @@ package ml.docilealligator.infinityforreddit; -import android.content.SharedPreferences; -import androidx.annotation.NonNull; import android.util.Log; +import androidx.annotation.NonNull; + import java.util.ArrayList; import SubredditDatabase.SubredditData; @@ -22,23 +22,20 @@ class FetchSubscribedThing { void onFetchSubscribedThingFail(); } - static void fetchSubscribedThing(final Retrofit retrofit, final SharedPreferences sharedPreferences, - final String lastItem, - final ArrayList<SubscribedSubredditData> subscribedSubredditData, + static void fetchSubscribedThing(final Retrofit retrofit, String accessToken, String accountName, + final String lastItem, final ArrayList<SubscribedSubredditData> subscribedSubredditData, final ArrayList<SubscribedUserData> subscribedUserData, final ArrayList<SubredditData> subredditData, final FetchSubscribedThingListener fetchSubscribedThingListener) { RedditAPI api = retrofit.create(RedditAPI.class); - String accessToken = sharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); - Call<String> subredditDataCall = api.getSubscribedThing(lastItem, RedditUtils.getOAuthHeader(accessToken)); subredditDataCall.enqueue(new Callback<String>() { @Override public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { if(response.isSuccessful()) { - ParseSubscribedThing.parseSubscribedSubreddits(response.body(), subscribedSubredditData, - subscribedUserData, subredditData, + ParseSubscribedThing.parseSubscribedSubreddits(response.body(), accountName, + subscribedSubredditData, subscribedUserData, subredditData, new ParseSubscribedThing.ParseSubscribedSubredditsListener() { @Override @@ -50,8 +47,8 @@ class FetchSubscribedThing { fetchSubscribedThingListener.onFetchSubscribedThingSuccess( subscribedSubredditData, subscribedUserData, subredditData); } else { - fetchSubscribedThing(retrofit, sharedPreferences, lastItem, subscribedSubredditData, - subscribedUserData, subredditData, + fetchSubscribedThing(retrofit, accessToken, accountName, lastItem, + subscribedSubredditData, subscribedUserData, subredditData, fetchSubscribedThingListener); } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/FilteredPostsActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/FilteredPostsActivity.java index eae90333..6d5d8a2d 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/FilteredPostsActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/FilteredPostsActivity.java @@ -9,6 +9,8 @@ import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; +import javax.inject.Inject; + import butterknife.BindView; import butterknife.ButterKnife; @@ -21,10 +23,14 @@ public class FilteredPostsActivity extends AppCompatActivity implements SortType static final String EXTRA_POST_TYPE = "EPT"; static final String EXTRA_SORT_TYPE = "EST"; + private static final String NULL_ACCESS_TOKEN_STATE = "NATS"; + private static final String ACCESS_TOKEN_STATE = "ATS"; private static final String FRAGMENT_OUT_STATE = "FOS"; @BindView(R.id.toolbar_filtered_posts_activity) Toolbar toolbar; + private boolean mNullAccessToken = false; + private String mAccessToken; private String name; private int postType; @@ -35,6 +41,9 @@ public class FilteredPostsActivity extends AppCompatActivity implements SortType private SortTypeBottomSheetFragment subredditSortTypeBottomSheetFragment; private SearchPostSortTypeBottomSheetFragment searchPostSortTypeBottomSheetFragment; + @Inject + RedditDataRoomDatabase mRedditDataRoomDatabase; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -42,14 +51,43 @@ public class FilteredPostsActivity extends AppCompatActivity implements SortType ButterKnife.bind(this); + ((Infinity) getApplication()).getmAppComponent().inject(this); + setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); name = getIntent().getExtras().getString(EXTRA_NAME); - int filter = getIntent().getExtras().getInt(EXTRA_FILTER); postType = getIntent().getExtras().getInt(EXTRA_POST_TYPE); + int filter = getIntent().getExtras().getInt(EXTRA_FILTER); String sortType = getIntent().getExtras().getString(EXTRA_SORT_TYPE); + if(savedInstanceState != null) { + mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE); + mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE); + if(!mNullAccessToken && mAccessToken == null) { + getCurrentAccountAndBindView(filter, sortType); + } else { + mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE); + getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_filtered_posts_activity, mFragment).commit(); + bindView(filter, sortType, false); + } + } else { + getCurrentAccountAndBindView(filter, sortType); + } + } + + private void getCurrentAccountAndBindView(int filter, String sortType) { + new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> { + if(account == null) { + mNullAccessToken = true; + } else { + mAccessToken = account.getAccessToken(); + } + bindView(filter, sortType, true); + }).execute(); + } + + private void bindView(int filter, String sortType, boolean initializeFragment) { switch (postType) { case PostDataSource.TYPE_FRONT_PAGE: getSupportActionBar().setTitle(name); @@ -108,21 +146,19 @@ public class FilteredPostsActivity extends AppCompatActivity implements SortType toolbar.setSubtitle(R.string.gif); } - if(savedInstanceState == null) { + if(initializeFragment) { mFragment = new PostFragment(); Bundle bundle = new Bundle(); bundle.putString(PostFragment.EXTRA_NAME, name); bundle.putInt(PostFragment.EXTRA_POST_TYPE, postType); bundle.putString(PostFragment.EXTRA_SORT_TYPE, sortType); bundle.putInt(PostFragment.EXTRA_FILTER, filter); + bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken); if(postType == PostDataSource.TYPE_SEARCH) { bundle.putString(PostFragment.EXTRA_QUERY, getIntent().getExtras().getString(EXTRA_QUERY)); } mFragment.setArguments(bundle); getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_filtered_posts_activity, mFragment).commit(); - } else { - mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE); - getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_filtered_posts_activity, mFragment).commit(); } } @@ -170,6 +206,7 @@ public class FilteredPostsActivity extends AppCompatActivity implements SortType if (mFragment != null) { getSupportFragmentManager().putFragment(outState, FRAGMENT_OUT_STATE, mFragment); } + outState.putString(ACCESS_TOKEN_STATE, mAccessToken); } @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/FollowedUsersListingFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/FollowedUsersListingFragment.java index 3db27463..1d67a82d 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/FollowedUsersListingFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/FollowedUsersListingFragment.java @@ -17,6 +17,8 @@ import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; +import javax.inject.Inject; + import SubscribedUserDatabase.SubscribedUserViewModel; import butterknife.BindView; import butterknife.ButterKnife; @@ -27,6 +29,8 @@ import butterknife.ButterKnife; */ public class FollowedUsersListingFragment extends Fragment { + static final String EXTRA_ACCOUNT_NAME = "EAN"; + @BindView(R.id.recycler_view_followed_users_listing_fragment) RecyclerView mRecyclerView; @BindView(R.id.no_subscriptions_linear_layout_followed_users_listing_fragment) LinearLayout mLinearLayout; @BindView(R.id.no_subscriptions_image_view_followed_users_listing_fragment) ImageView mImageView; @@ -41,6 +45,8 @@ public class FollowedUsersListingFragment extends Fragment { // Required empty public constructor } + @Inject + RedditDataRoomDatabase mRedditDataRoomDatabase; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, @@ -51,13 +57,17 @@ public class FollowedUsersListingFragment extends Fragment { mActivity = getActivity(); + ((Infinity) mActivity.getApplication()).getmAppComponent().inject(this); + mGlide = Glide.with(this); mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity)); FollowedUsersRecyclerViewAdapter adapter = new FollowedUsersRecyclerViewAdapter(mActivity); mRecyclerView.setAdapter(adapter); - mSubscribedUserViewModel = ViewModelProviders.of(this).get(SubscribedUserViewModel.class); + mSubscribedUserViewModel = ViewModelProviders.of(this, + new SubscribedUserViewModel.Factory(mActivity.getApplication(), mRedditDataRoomDatabase, getArguments().getString(EXTRA_ACCOUNT_NAME))) + .get(SubscribedUserViewModel.class); mSubscribedUserViewModel.getAllSubscribedUsers().observe(this, subscribedUserData -> { if (subscribedUserData == null || subscribedUserData.size() == 0) { mRecyclerView.setVisibility(View.GONE); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/GetCurrentAccountAsyncTask.java b/app/src/main/java/ml/docilealligator/infinityforreddit/GetCurrentAccountAsyncTask.java new file mode 100644 index 00000000..ad740f92 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/GetCurrentAccountAsyncTask.java @@ -0,0 +1,33 @@ +package ml.docilealligator.infinityforreddit; + +import android.os.AsyncTask; + +import Account.Account; +import Account.AccountDao; + +class GetCurrentAccountAsyncTask extends AsyncTask<Void, Void, Void> { + + interface GetCurrentAccountAsyncTaskListener { + void success(Account account); + } + + Account account; + AccountDao accountDao; + GetCurrentAccountAsyncTaskListener getCurrentAccountAsyncTaskListener; + + GetCurrentAccountAsyncTask(AccountDao accountDao, GetCurrentAccountAsyncTaskListener getCurrentAccountAsyncTaskListener) { + this.accountDao = accountDao; + this.getCurrentAccountAsyncTaskListener = getCurrentAccountAsyncTaskListener; + } + + @Override + protected Void doInBackground(Void... voids) { + account = accountDao.getCurrentAccount(); + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + getCurrentAccountAsyncTaskListener.success(account); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/LoginActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/LoginActivity.java index 20fa44fa..e5e125f3 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/LoginActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/LoginActivity.java @@ -1,9 +1,7 @@ package ml.docilealligator.infinityforreddit; import android.app.Activity; -import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; @@ -24,7 +22,6 @@ import java.util.Map; import javax.inject.Inject; import javax.inject.Named; -import Account.AccountRoomDatabase; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; @@ -42,6 +39,9 @@ public class LoginActivity extends AppCompatActivity { @Named("oauth") Retrofit mOauthRetrofit; + @Inject + RedditDataRoomDatabase mRedditDataRoomDatabase; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -75,10 +75,6 @@ public class LoginActivity extends AppCompatActivity { if(state.equals(RedditUtils.STATE)) { authCode = uri.getQueryParameter("code"); - SharedPreferences.Editor editor = getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE).edit(); - editor.putString(SharedPreferencesUtils.AUTH_CODE_KEY, authCode); - editor.apply(); - Map<String, String> params = new HashMap<>(); params.put(RedditUtils.GRANT_TYPE_KEY, "authorization_code"); params.put("code", authCode); @@ -107,8 +103,8 @@ public class LoginActivity extends AppCompatActivity { ParseMyInfo.parseMyInfo(response, new ParseMyInfo.ParseMyInfoListener() { @Override public void onParseMyInfoSuccess(String name, String profileImageUrl, String bannerImageUrl, int karma) { - new ParseAndInsertAccount(name, accessToken, refreshToken, profileImageUrl, bannerImageUrl, - karma, authCode, AccountRoomDatabase.getDatabase(LoginActivity.this).accountDao(), + new ParseAndInsertNewAccountAsyncTask(name, accessToken, refreshToken, profileImageUrl, bannerImageUrl, + karma, authCode, mRedditDataRoomDatabase.accountDao(), () -> { Intent resultIntent = new Intent(); setResult(Activity.RESULT_OK, resultIntent); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/MainActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/MainActivity.java index 68199d6d..a5e3018d 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/MainActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/MainActivity.java @@ -1,7 +1,6 @@ package ml.docilealligator.infinityforreddit; import android.app.Activity; -import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; @@ -48,6 +47,8 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe private static final String FETCH_USER_INFO_STATE = "FUIS"; private static final String IS_IN_LAZY_MODE_STATE = "IILMS"; + private static final String NULL_ACCESS_TOKEN_STATE = "NATS"; + private static final String ACCESS_TOKEN_STATE = "ATS"; private static final int LOGIN_ACTIVITY_REQUEST_CODE = 0; @@ -73,6 +74,8 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe private SortTypeBottomSheetFragment bestSortTypeBottomSheetFragment; private SortTypeBottomSheetFragment popularAndAllSortTypeBottomSheetFragment; + private boolean mNullAccessToken = false; + private String mAccessToken; private String mName; private String mProfileImageUrl; private String mBannerImageUrl; @@ -88,13 +91,12 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe SharedPreferences mUserInfoSharedPreferences; @Inject - @Named("auth_info") - SharedPreferences mAuthInfoSharedPreferences; - - @Inject @Named("oauth") Retrofit mOauthRetrofit; + @Inject + RedditDataRoomDatabase mRedditDataRoomDatabase; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -127,85 +129,105 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams(); + if(savedInstanceState != null) { + mFetchUserInfoSuccess = savedInstanceState.getBoolean(FETCH_USER_INFO_STATE); + isInLazyMode = savedInstanceState.getBoolean(IS_IN_LAZY_MODE_STATE); + mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE); + mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE); + if(!mNullAccessToken && mAccessToken == null) { + getCurrentAccountAndBindView(); + } else { + bindView(); + } + } else { + getCurrentAccountAndBindView(); + } + + fab.setOnClickListener(view -> postTypeBottomSheetFragment.show(getSupportFragmentManager(), postTypeBottomSheetFragment.getTag())); + } + + private void getCurrentAccountAndBindView() { + new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> { + if(account == null) { + Intent loginIntent = new Intent(this, LoginActivity.class); + startActivityForResult(loginIntent, LOGIN_ACTIVITY_REQUEST_CODE); + } else { + mAccessToken = account.getAccessToken(); + if(mAccessToken == null) { + mNullAccessToken = true; + } + bindView(); + } + }).execute(); + } + + private void bindView() { sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(sectionsPagerAdapter); viewPager.setOffscreenPageLimit(2); tabLayout.setupWithViewPager(viewPager); - String accessToken = getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE).getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); - if (accessToken.equals("")) { - Intent loginIntent = new Intent(this, LoginActivity.class); - startActivityForResult(loginIntent, LOGIN_ACTIVITY_REQUEST_CODE); - } else { - if (savedInstanceState != null) { - mFetchUserInfoSuccess = savedInstanceState.getBoolean(FETCH_USER_INFO_STATE); - isInLazyMode = savedInstanceState.getBoolean(IS_IN_LAZY_MODE_STATE); + if(getIntent().hasExtra(EXTRA_POST_TYPE)) { + if(getIntent().getExtras().getString(EXTRA_POST_TYPE).equals("popular")) { + viewPager.setCurrentItem(1); } else { - if(getIntent().hasExtra(EXTRA_POST_TYPE)) { - if(getIntent().getExtras().getString(EXTRA_POST_TYPE).equals("popular")) { - viewPager.setCurrentItem(1); - } else { - viewPager.setCurrentItem(2); - } - } + viewPager.setCurrentItem(2); } + } - glide = Glide.with(this); - - View header = findViewById(R.id.nav_header_main_activity); - mNameTextView = header.findViewById(R.id.name_text_view_nav_header_main); - mKarmaTextView = header.findViewById(R.id.karma_text_view_nav_header_main); - mProfileImageView = header.findViewById(R.id.profile_image_view_nav_header_main); - mBannerImageView = header.findViewById(R.id.banner_image_view_nav_header_main); + glide = Glide.with(this); - loadUserData(); + View header = findViewById(R.id.nav_header_main_activity); + mNameTextView = header.findViewById(R.id.name_text_view_nav_header_main); + mKarmaTextView = header.findViewById(R.id.karma_text_view_nav_header_main); + mProfileImageView = header.findViewById(R.id.profile_image_view_nav_header_main); + mBannerImageView = header.findViewById(R.id.banner_image_view_nav_header_main); - mName = mUserInfoSharedPreferences.getString(SharedPreferencesUtils.USER_KEY, ""); - mProfileImageUrl = mUserInfoSharedPreferences.getString(SharedPreferencesUtils.PROFILE_IMAGE_URL_KEY, ""); - mBannerImageUrl = mUserInfoSharedPreferences.getString(SharedPreferencesUtils.BANNER_IMAGE_URL_KEY, ""); - mKarma = mUserInfoSharedPreferences.getString(SharedPreferencesUtils.KARMA_KEY, ""); + loadUserData(mAccessToken); - mNameTextView.setText(mName); - mKarmaTextView.setText(mKarma); + mName = mUserInfoSharedPreferences.getString(SharedPreferencesUtils.USER_KEY, ""); + mProfileImageUrl = mUserInfoSharedPreferences.getString(SharedPreferencesUtils.PROFILE_IMAGE_URL_KEY, ""); + mBannerImageUrl = mUserInfoSharedPreferences.getString(SharedPreferencesUtils.BANNER_IMAGE_URL_KEY, ""); + mKarma = mUserInfoSharedPreferences.getString(SharedPreferencesUtils.KARMA_KEY, ""); - if (!mProfileImageUrl.equals("")) { - glide.load(mProfileImageUrl) - .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(144, 0))) - .error(glide.load(R.drawable.subreddit_default_icon) - .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(144, 0)))) - .into(mProfileImageView); - } else { - glide.load(R.drawable.subreddit_default_icon) - .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(144, 0))) - .into(mProfileImageView); - } + mNameTextView.setText(mName); + mKarmaTextView.setText(mKarma); - if (!mBannerImageUrl.equals("")) { - glide.load(mBannerImageUrl).into(mBannerImageView); - } + if (!mProfileImageUrl.equals("")) { + glide.load(mProfileImageUrl) + .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(144, 0))) + .error(glide.load(R.drawable.subreddit_default_icon) + .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(144, 0)))) + .into(mProfileImageView); + } else { + glide.load(R.drawable.subreddit_default_icon) + .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(144, 0))) + .into(mProfileImageView); + } - profileLinearLayout.setOnClickListener(view -> { - Intent intent = new Intent(this, ViewUserDetailActivity.class); - intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mName); - startActivity(intent); - }); + if (!mBannerImageUrl.equals("")) { + glide.load(mBannerImageUrl).into(mBannerImageView); + } - subscriptionLinearLayout.setOnClickListener(view -> { - Intent intent = new Intent(this, SubscribedThingListingActivity.class); - startActivity(intent); - }); + profileLinearLayout.setOnClickListener(view -> { + Intent intent = new Intent(this, ViewUserDetailActivity.class); + intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mName); + startActivity(intent); + }); - settingsLinearLayout.setOnClickListener(view -> { + subscriptionLinearLayout.setOnClickListener(view -> { + Intent intent = new Intent(this, SubscribedThingListingActivity.class); + startActivity(intent); + }); - }); - } + settingsLinearLayout.setOnClickListener(view -> { - fab.setOnClickListener(view -> postTypeBottomSheetFragment.show(getSupportFragmentManager(), postTypeBottomSheetFragment.getTag())); + }); } - private void loadUserData() { + private void loadUserData(String accessToken) { if (!mFetchUserInfoSuccess) { - FetchMyInfo.fetchMyInfo(mOauthRetrofit, mAuthInfoSharedPreferences, new FetchMyInfo.FetchUserMyListener() { + FetchMyInfo.fetchMyInfo(mOauthRetrofit, accessToken, new FetchMyInfo.FetchUserMyListener() { @Override public void onFetchMyInfoSuccess(String response) { ParseMyInfo.parseMyInfo(response, new ParseMyInfo.ParseMyInfoListener() { @@ -306,7 +328,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe case R.id.action_refresh_main_activity: sectionsPagerAdapter.refresh(viewPager.getCurrentItem()); mFetchUserInfoSuccess = false; - loadUserData(); + loadUserData(mAccessToken); return true; case R.id.action_lazy_mode_main_activity: /*MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_main_activity); @@ -343,6 +365,8 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe super.onSaveInstanceState(outState); outState.putBoolean(FETCH_USER_INFO_STATE, mFetchUserInfoSuccess); outState.putBoolean(IS_IN_LAZY_MODE_STATE, isInLazyMode); + outState.putBoolean(NULL_ACCESS_TOKEN_STATE, mNullAccessToken); + outState.putString(ACCESS_TOKEN_STATE, mAccessToken); } @Override @@ -390,6 +414,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostDataSource.TYPE_FRONT_PAGE); bundle.putString(PostFragment.EXTRA_SORT_TYPE, PostDataSource.SORT_TYPE_BEST); bundle.putInt(PostFragment.EXTRA_FILTER, PostFragment.EXTRA_NO_FILTER); + bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken); fragment.setArguments(bundle); return fragment; } else if(position == 1) { @@ -399,6 +424,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe bundle.putString(PostFragment.EXTRA_NAME, "popular"); bundle.putString(PostFragment.EXTRA_SORT_TYPE, PostDataSource.SORT_TYPE_HOT); bundle.putInt(PostFragment.EXTRA_FILTER, PostFragment.EXTRA_NO_FILTER); + bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken); fragment.setArguments(bundle); return fragment; } else { @@ -408,6 +434,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe bundle.putString(PostFragment.EXTRA_NAME, "all"); bundle.putString(PostFragment.EXTRA_SORT_TYPE, PostDataSource.SORT_TYPE_HOT); bundle.putInt(PostFragment.EXTRA_FILTER, PostFragment.EXTRA_NO_FILTER); + bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken); fragment.setArguments(bundle); return fragment; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/ParseAndInsertAccount.java b/app/src/main/java/ml/docilealligator/infinityforreddit/ParseAndInsertNewAccountAsyncTask.java index e86fbada..f5a99d5d 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/ParseAndInsertAccount.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/ParseAndInsertNewAccountAsyncTask.java @@ -5,7 +5,7 @@ import android.os.AsyncTask; import Account.Account; import Account.AccountDao; -class ParseAndInsertAccount extends AsyncTask<Void, Void, Void> { +class ParseAndInsertNewAccountAsyncTask extends AsyncTask<Void, Void, Void> { interface ParseAndInsertAccountListener { void success(); @@ -21,9 +21,9 @@ class ParseAndInsertAccount extends AsyncTask<Void, Void, Void> { private AccountDao accountDao; private ParseAndInsertAccountListener parseAndInsertAccountListener; - ParseAndInsertAccount(String username, String accessToken, String refreshToken, String profileImageUrl, String bannerImageUrl, - int karma, String code, AccountDao accountDao, - ParseAndInsertAccountListener parseAndInsertAccountListener) { + ParseAndInsertNewAccountAsyncTask(String username, String accessToken, String refreshToken, String profileImageUrl, String bannerImageUrl, + int karma, String code, AccountDao accountDao, + ParseAndInsertAccountListener parseAndInsertAccountListener) { this.username = username; this.accessToken = accessToken; this.refreshToken = refreshToken; @@ -39,6 +39,7 @@ class ParseAndInsertAccount extends AsyncTask<Void, Void, Void> { protected Void doInBackground(Void... voids) { Account account = new Account(username, accessToken, refreshToken, code, profileImageUrl, bannerImageUrl, karma, true); + accountDao.markAllAccountsNonCurrent(); accountDao.insert(account); return null; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubscribedThing.java b/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubscribedThing.java index fc69c82b..5121fc3b 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubscribedThing.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubscribedThing.java @@ -22,16 +22,18 @@ class ParseSubscribedThing { void onParseSubscribedSubredditsFail(); } - static void parseSubscribedSubreddits(String response, ArrayList<SubscribedSubredditData> subscribedSubredditData, - ArrayList<SubscribedUserData> subscribedUserData, - ArrayList<SubredditData> subredditData, - ParseSubscribedSubredditsListener parseSubscribedSubredditsListener) { - new ParseSubscribedSubredditsAsyncTask(response, subscribedSubredditData, subscribedUserData, subredditData, + static void parseSubscribedSubreddits(String response, String accountName, + ArrayList<SubscribedSubredditData> subscribedSubredditData, + ArrayList<SubscribedUserData> subscribedUserData, + ArrayList<SubredditData> subredditData, + ParseSubscribedSubredditsListener parseSubscribedSubredditsListener) { + new ParseSubscribedSubredditsAsyncTask(response, accountName, subscribedSubredditData, subscribedUserData, subredditData, parseSubscribedSubredditsListener).execute(); } private static class ParseSubscribedSubredditsAsyncTask extends AsyncTask<Void, Void, Void> { private JSONObject jsonResponse; + private String accountName; private boolean parseFailed; private String lastItem; private ArrayList<SubscribedSubredditData> subscribedSubredditData; @@ -42,12 +44,13 @@ class ParseSubscribedThing { private ArrayList<SubredditData> newSubredditData; private ParseSubscribedSubredditsListener parseSubscribedSubredditsListener; - ParseSubscribedSubredditsAsyncTask(String response, ArrayList<SubscribedSubredditData> subscribedSubredditData, + ParseSubscribedSubredditsAsyncTask(String response, String accountName, ArrayList<SubscribedSubredditData> subscribedSubredditData, ArrayList<SubscribedUserData> subscribedUserData, ArrayList<SubredditData> subredditData, ParseSubscribedSubredditsListener parseSubscribedSubredditsListener){ try { jsonResponse = new JSONObject(response); + this.accountName = accountName; parseFailed = false; this.subscribedSubredditData = subscribedSubredditData; this.subscribedUserData = subscribedUserData; @@ -94,12 +97,12 @@ class ParseSubscribedThing { if(data.getString(JSONUtils.SUBREDDIT_TYPE_KEY) .equals(JSONUtils.SUBREDDIT_TYPE_VALUE_USER)) { //It's a user - newSubscribedUserData.add(new SubscribedUserData(name.substring(2), iconUrl)); + newSubscribedUserData.add(new SubscribedUserData(name.substring(2), iconUrl, accountName)); } else { String subredditFullName = data.getString(JSONUtils.DISPLAY_NAME); String description = data.getString(JSONUtils.PUBLIC_DESCRIPTION_KEY).trim(); int nSubscribers = data.getInt(JSONUtils.SUBSCRIBERS_KEY); - newSubscribedSubredditData.add(new SubscribedSubredditData(id, name, iconUrl)); + newSubscribedSubredditData.add(new SubscribedSubredditData(id, name, iconUrl, accountName)); newSubredditData.add(new SubredditData(id, subredditFullName, iconUrl, bannerImageUrl, description, nSubscribers)); } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PostFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PostFragment.java index dce8680f..6c75d4dc 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PostFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/PostFragment.java @@ -4,7 +4,6 @@ package ml.docilealligator.infinityforreddit; import android.app.Activity; import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; @@ -53,6 +52,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator { static final String EXTRA_SORT_TYPE = "EST"; static final String EXTRA_FILTER = "EF"; static final int EXTRA_NO_FILTER = -1; + static final String EXTRA_ACCESS_TOKEN = "EAT"; private static final String IS_IN_LAZY_MODE_STATE = "IILMS"; @@ -87,8 +87,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator { @Inject @Named("oauth") Retrofit mOauthRetrofit; - @Inject @Named("auth_info") - SharedPreferences mSharedPreferences; + @Inject + RedditDataRoomDatabase redditDataRoomDatabase; public PostFragment() { // Required empty public constructor @@ -173,9 +173,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator { int postType = getArguments().getInt(EXTRA_POST_TYPE); String sortType = getArguments().getString(EXTRA_SORT_TYPE); int filter = getArguments().getInt(EXTRA_FILTER); - - String accessToken = activity.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE) - .getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); + String accessToken = getArguments().getString(EXTRA_ACCESS_TOKEN); PostViewModel.Factory factory; @@ -183,8 +181,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator { String subredditName = getArguments().getString(EXTRA_NAME); String query = getArguments().getString(EXTRA_QUERY); - mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, - mSharedPreferences, postType, true, new PostRecyclerViewAdapter.Callback() { + mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, redditDataRoomDatabase, + accessToken, postType, true, new PostRecyclerViewAdapter.Callback() { @Override public void retryLoadingMore() { mPostViewModel.retryLoadingMore(); @@ -221,8 +219,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator { String subredditName = getArguments().getString(EXTRA_NAME); boolean displaySubredditName = subredditName.equals("popular") || subredditName.equals("all"); - mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, - mSharedPreferences, postType, displaySubredditName, new PostRecyclerViewAdapter.Callback() { + mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, redditDataRoomDatabase, + accessToken, postType, displaySubredditName, new PostRecyclerViewAdapter.Callback() { @Override public void retryLoadingMore() { mPostViewModel.retryLoadingMore(); @@ -261,8 +259,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator { String username = getArguments().getString(EXTRA_USER_NAME); - mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, - mSharedPreferences, postType, true, new PostRecyclerViewAdapter.Callback() { + mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, redditDataRoomDatabase, + accessToken, postType, true, new PostRecyclerViewAdapter.Callback() { @Override public void retryLoadingMore() { mPostViewModel.retryLoadingMore(); @@ -296,8 +294,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator { } }); } else { - mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, - mSharedPreferences, postType, true, new PostRecyclerViewAdapter.Callback() { + mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, redditDataRoomDatabase, + accessToken, postType, true, new PostRecyclerViewAdapter.Callback() { @Override public void retryLoadingMore() { mPostViewModel.retryLoadingMore(); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PostImageActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PostImageActivity.java index 74e19f3a..927e33d7 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PostImageActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/PostImageActivity.java @@ -1,7 +1,6 @@ package ml.docilealligator.infinityforreddit; import android.content.Intent; -import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.Bundle; @@ -39,7 +38,6 @@ import java.io.IOException; import javax.inject.Inject; import javax.inject.Named; -import SubredditDatabase.SubredditRoomDatabase; import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; @@ -110,12 +108,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS Retrofit mUploadMediaRetrofit; @Inject - @Named("user_info") - SharedPreferences mUserInfoSharedPreferences; - - @Inject - @Named("auth_info") - SharedPreferences sharedPreferences; + RedditDataRoomDatabase redditDataRoomDatabase; @Override protected void onCreate(Bundle savedInstanceState) { @@ -299,7 +292,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS } private void loadSubredditIcon() { - new LoadSubredditIconAsyncTask(SubredditRoomDatabase.getDatabase(this).subredditDao(), + new LoadSubredditIconAsyncTask(redditDataRoomDatabase.subredditDao(), subredditName, mRetrofit, iconImageUrl -> { iconUrl = iconImageUrl; displaySubredditIcon(); @@ -441,11 +434,13 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS public void onSubmitImagePostEvent(SubmitImagePostEvent submitImagePostEvent) { isPosting = false; if(submitImagePostEvent.postSuccess) { - Intent intent = new Intent(this, ViewUserDetailActivity.class); - intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, - mUserInfoSharedPreferences.getString(SharedPreferencesUtils.USER_KEY, "")); - startActivity(intent); - finish(); + new GetCurrentAccountAsyncTask(redditDataRoomDatabase.accountDao(), account -> { + Intent intent = new Intent(PostImageActivity.this, ViewUserDetailActivity.class); + intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, + account.getUsername()); + startActivity(intent); + finish(); + }).execute(); } else { mPostingSnackbar.dismiss(); mMemu.getItem(R.id.action_send_post_image_activity).setEnabled(true); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PostLinkActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PostLinkActivity.java index ed537d78..f0f866ff 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PostLinkActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/PostLinkActivity.java @@ -1,7 +1,6 @@ package ml.docilealligator.infinityforreddit; import android.content.Intent; -import android.content.SharedPreferences; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; @@ -28,7 +27,6 @@ import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import javax.inject.Named; -import SubredditDatabase.SubredditRoomDatabase; import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; @@ -48,6 +46,8 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh private static final String FLAIR_STATE = "FS"; private static final String IS_SPOILER_STATE = "ISS"; private static final String IS_NSFW_STATE = "INS"; + private static final String NULL_ACCOUNT_NAME_STATE = "NATS"; + private static final String ACCOUNT_NAME_STATE = "ANS"; private static final int SUBREDDIT_SELECTION_REQUEST_CODE = 0; @@ -62,6 +62,8 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh @BindView(R.id.post_title_edit_text_post_link_activity) EditText titleEditText; @BindView(R.id.post_link_edit_text_post_link_activity) EditText contentEditText; + private boolean mNullAccountName = false; + private String mAccountName; private String iconUrl; private String subredditName; private boolean subredditSelected = false; @@ -87,8 +89,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh Retrofit mOauthRetrofit; @Inject - @Named("auth_info") - SharedPreferences sharedPreferences; + RedditDataRoomDatabase mRedditDataRoomDatabase; @Override protected void onCreate(Bundle savedInstanceState) { @@ -215,6 +216,16 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh }); } + private void getCurrentAccountName() { + new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> { + if(account == null) { + mNullAccountName = true; + } else { + mAccountName = account.getUsername(); + } + }).execute(); + } + private void displaySubredditIcon() { if(iconUrl != null && !iconUrl.equals("")) { mGlide.load(iconUrl) @@ -230,7 +241,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh } private void loadSubredditIcon() { - new LoadSubredditIconAsyncTask(SubredditRoomDatabase.getDatabase(this).subredditDao(), + new LoadSubredditIconAsyncTask(mRedditDataRoomDatabase.subredditDao(), subredditName, mRetrofit, iconImageUrl -> { iconUrl = iconImageUrl; displaySubredditIcon(); @@ -304,6 +315,8 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh outState.putString(FLAIR_STATE, flair); outState.putBoolean(IS_SPOILER_STATE, isSpoiler); outState.putBoolean(IS_NSFW_STATE, isNSFW); + outState.putBoolean(NULL_ACCOUNT_NAME_STATE, mNullAccountName); + outState.putString(ACCOUNT_NAME_STATE, mAccountName); } @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java index 79759c6c..3519633e 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java @@ -2,7 +2,6 @@ package ml.docilealligator.infinityforreddit; import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.graphics.ColorFilter; import android.graphics.drawable.Drawable; import android.net.Uri; @@ -43,9 +42,7 @@ import org.greenrobot.eventbus.EventBus; import CustomView.AspectRatioGifImageView; import SubredditDatabase.SubredditDao; -import SubredditDatabase.SubredditRoomDatabase; import User.UserDao; -import User.UserRoomDatabase; import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.glide.transformations.BlurTransformation; @@ -60,20 +57,20 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo private Context mContext; private Retrofit mOauthRetrofit; private Retrofit mRetrofit; - private SharedPreferences mSharedPreferences; - private RequestManager glide; - private SubredditDao subredditDao; - private UserDao userDao; + private String mAccessToken; + private RequestManager mGlide; + private SubredditDao mSubredditDao; + private UserDao mUserDao; private boolean canStartActivity = true; - private int postType; - private boolean displaySubredditName; + private int mPostType; + private boolean mDisplaySubredditName; private static final int VIEW_TYPE_DATA = 0; private static final int VIEW_TYPE_ERROR = 1; private static final int VIEW_TYPE_LOADING = 2; private NetworkState networkState; - private Callback callback; + private Callback mCallback; interface Callback { void retryLoadingMore(); @@ -81,20 +78,21 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo } PostRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, Retrofit retrofit, - SharedPreferences sharedPreferences, int postType, + RedditDataRoomDatabase redditDataRoomDatabase, + String accessToken, int postType, boolean displaySubredditName, Callback callback) { super(DIFF_CALLBACK); if(context != null) { mContext = context; mOauthRetrofit = oauthRetrofit; mRetrofit = retrofit; - mSharedPreferences = sharedPreferences; - this.postType = postType; - this.displaySubredditName = displaySubredditName; - glide = Glide.with(mContext.getApplicationContext()); - subredditDao = SubredditRoomDatabase.getDatabase(mContext.getApplicationContext()).subredditDao(); - userDao = UserRoomDatabase.getDatabase(mContext.getApplicationContext()).userDao(); - this.callback = callback; + mAccessToken = accessToken; + mPostType = postType; + mDisplaySubredditName = displaySubredditName; + mGlide = Glide.with(mContext.getApplicationContext()); + mSubredditDao = redditDataRoomDatabase.subredditDao(); + mUserDao = redditDataRoomDatabase.userDao(); + mCallback = callback; } } @@ -161,19 +159,19 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo } }); - if(displaySubredditName) { + if(mDisplaySubredditName) { if(authorPrefixed.equals(subredditNamePrefixed)) { if(post.getAuthorIconUrl() == null) { - new LoadUserDataAsyncTask(userDao, post.getAuthor(), mRetrofit, iconImageUrl -> { + new LoadUserDataAsyncTask(mUserDao, post.getAuthor(), mRetrofit, iconImageUrl -> { if(mContext != null && getItemCount() > 0) { if(iconImageUrl == null || iconImageUrl.equals("")) { - glide.load(R.drawable.subreddit_default_icon) + mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) .into(((DataViewHolder) holder).iconGifImageView); } else { - glide.load(iconImageUrl) + mGlide.load(iconImageUrl) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) - .error(glide.load(R.drawable.subreddit_default_icon) + .error(mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))) .into(((DataViewHolder) holder).iconGifImageView); } @@ -184,29 +182,29 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo } }).execute(); } else if(!post.getAuthorIconUrl().equals("")) { - glide.load(post.getAuthorIconUrl()) + mGlide.load(post.getAuthorIconUrl()) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) - .error(glide.load(R.drawable.subreddit_default_icon) + .error(mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))) .into(((DataViewHolder) holder).iconGifImageView); } else { - glide.load(R.drawable.subreddit_default_icon) + mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) .into(((DataViewHolder) holder).iconGifImageView); } } else { if(post.getSubredditIconUrl() == null) { - new LoadSubredditIconAsyncTask(subredditDao, subredditName, mRetrofit, + new LoadSubredditIconAsyncTask(mSubredditDao, subredditName, mRetrofit, iconImageUrl -> { if(mContext != null && getItemCount() > 0) { if(iconImageUrl == null || iconImageUrl.equals("")) { - glide.load(R.drawable.subreddit_default_icon) + mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) .into(((DataViewHolder) holder).iconGifImageView); } else { - glide.load(iconImageUrl) + mGlide.load(iconImageUrl) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) - .error(glide.load(R.drawable.subreddit_default_icon) + .error(mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))) .into(((DataViewHolder) holder).iconGifImageView); } @@ -217,13 +215,13 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo } }).execute(); } else if(!post.getSubredditIconUrl().equals("")) { - glide.load(post.getSubredditIconUrl()) + mGlide.load(post.getSubredditIconUrl()) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) - .error(glide.load(R.drawable.subreddit_default_icon) + .error(mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))) .into(((DataViewHolder) holder).iconGifImageView); } else { - glide.load(R.drawable.subreddit_default_icon) + mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) .into(((DataViewHolder) holder).iconGifImageView); } @@ -250,16 +248,16 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo }); } else { if(post.getAuthorIconUrl() == null) { - new LoadUserDataAsyncTask(userDao, post.getAuthor(), mRetrofit, iconImageUrl -> { + new LoadUserDataAsyncTask(mUserDao, post.getAuthor(), mRetrofit, iconImageUrl -> { if(mContext != null && getItemCount() > 0) { if(iconImageUrl == null || iconImageUrl.equals("")) { - glide.load(R.drawable.subreddit_default_icon) + mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) .into(((DataViewHolder) holder).iconGifImageView); } else { - glide.load(iconImageUrl) + mGlide.load(iconImageUrl) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) - .error(glide.load(R.drawable.subreddit_default_icon) + .error(mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))) .into(((DataViewHolder) holder).iconGifImageView); } @@ -270,13 +268,13 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo } }).execute(); } else if(!post.getAuthorIconUrl().equals("")) { - glide.load(post.getAuthorIconUrl()) + mGlide.load(post.getAuthorIconUrl()) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) - .error(glide.load(R.drawable.subreddit_default_icon) + .error(mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))) .into(((DataViewHolder) holder).iconGifImageView); } else { - glide.load(R.drawable.subreddit_default_icon) + mGlide.load(R.drawable.subreddit_default_icon) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) .into(((DataViewHolder) holder).iconGifImageView); } @@ -300,7 +298,7 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo if(gilded > 0) { ((DataViewHolder) holder).gildedImageView.setVisibility(View.VISIBLE); - glide.load(R.drawable.gold).into(((DataViewHolder) holder).gildedImageView); + mGlide.load(R.drawable.gold).into(((DataViewHolder) holder).gildedImageView); ((DataViewHolder) holder).gildedNumberTextView.setVisibility(View.VISIBLE); String gildedNumber = mContext.getResources().getString(R.string.gilded, gilded); ((DataViewHolder) holder).gildedNumberTextView.setText(gildedNumber); @@ -345,9 +343,9 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo loadImage(holder, post); } - if(postType == PostDataSource.TYPE_SUBREDDIT && post.isStickied()) { + if(mPostType == PostDataSource.TYPE_SUBREDDIT && post.isStickied()) { ((DataViewHolder) holder).stickiedPostImageView.setVisibility(View.VISIBLE); - glide.load(R.drawable.thumbtack).into(((DataViewHolder) holder).stickiedPostImageView); + mGlide.load(R.drawable.thumbtack).into(((DataViewHolder) holder).stickiedPostImageView); } if(isArchived) { @@ -362,7 +360,7 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo } if(!(mContext instanceof FilteredPostsActivity)) { - ((DataViewHolder) holder).typeChip.setOnClickListener(view -> callback.typeChipClicked(post.getPostType())); + ((DataViewHolder) holder).typeChip.setOnClickListener(view -> mCallback.typeChipClicked(post.getPostType())); } switch (post.getPostType()) { @@ -481,7 +479,7 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() + post.getVoteType())); - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { + VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() { @Override public void onVoteThingSuccess(int position1) { if(newVoteType.equals(RedditUtils.DIR_UPVOTE)) { @@ -541,7 +539,7 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() + post.getVoteType())); - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { + VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() { @Override public void onVoteThingSuccess(int position1) { if(newVoteType.equals(RedditUtils.DIR_DOWNVOTE)) { @@ -584,7 +582,7 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo } private void loadImage(final RecyclerView.ViewHolder holder, final Post post) { - RequestBuilder imageRequestBuilder = glide.load(post.getPreviewUrl()).listener(new RequestListener<Drawable>() { + RequestBuilder imageRequestBuilder = mGlide.load(post.getPreviewUrl()).listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { ((DataViewHolder) holder).progressBar.setVisibility(View.GONE); @@ -699,7 +697,7 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo super(itemView); ButterKnife.bind(this, itemView); errorTextView.setText(R.string.load_posts_error); - retryButton.setOnClickListener(view -> callback.retryLoadingMore()); + retryButton.setOnClickListener(view -> mCallback.retryLoadingMore()); } } @@ -713,8 +711,8 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo @Override public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) { if(holder instanceof DataViewHolder) { - glide.clear(((DataViewHolder) holder).imageView); - glide.clear(((DataViewHolder) holder).iconGifImageView); + mGlide.clear(((DataViewHolder) holder).imageView); + mGlide.clear(((DataViewHolder) holder).iconGifImageView); ((DataViewHolder) holder).stickiedPostImageView.setVisibility(View.GONE); ((DataViewHolder) holder).relativeLayout.setVisibility(View.GONE); ((DataViewHolder) holder).gildedImageView.setVisibility(View.GONE); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PostTextActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PostTextActivity.java index d96dddc6..957360b1 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PostTextActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/PostTextActivity.java @@ -28,7 +28,6 @@ import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import javax.inject.Named; -import SubredditDatabase.SubredditRoomDatabase; import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; @@ -48,6 +47,8 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh private static final String FLAIR_STATE = "FS"; private static final String IS_SPOILER_STATE = "ISS"; private static final String IS_NSFW_STATE = "INS"; + private static final String NULL_ACCOUNT_NAME_STATE = "NATS"; + private static final String ACCOUNT_NAME_STATE = "ANS"; private static final int SUBREDDIT_SELECTION_REQUEST_CODE = 0; @@ -62,6 +63,8 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh @BindView(R.id.post_title_edit_text_post_text_activity) EditText titleEditText; @BindView(R.id.post_text_content_edit_text_post_text_activity) EditText contentEditText; + private boolean mNullAccountName = false; + private String mAccountName; private String iconUrl; private String subredditName; private boolean subredditSelected = false; @@ -90,6 +93,9 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh @Named("auth_info") SharedPreferences sharedPreferences; + @Inject + RedditDataRoomDatabase mRedditDataRoomDatabase; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -220,6 +226,16 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh }); } + private void getCurrentAccountName() { + new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> { + if(account == null) { + mNullAccountName = true; + } else { + mAccountName = account.getUsername(); + } + }).execute(); + } + private void displaySubredditIcon() { if(iconUrl != null && !iconUrl.equals("")) { mGlide.load(iconUrl) @@ -235,7 +251,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh } private void loadSubredditIcon() { - new LoadSubredditIconAsyncTask(SubredditRoomDatabase.getDatabase(this).subredditDao(), + new LoadSubredditIconAsyncTask(mRedditDataRoomDatabase.subredditDao(), subredditName, mRetrofit, iconImageUrl -> { iconUrl = iconImageUrl; displaySubredditIcon(); @@ -309,6 +325,8 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh outState.putString(FLAIR_STATE, flair); outState.putBoolean(IS_SPOILER_STATE, isSpoiler); outState.putBoolean(IS_NSFW_STATE, isNSFW); + outState.putBoolean(NULL_ACCOUNT_NAME_STATE, mNullAccountName); + outState.putString(ACCOUNT_NAME_STATE, mAccountName); } @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PostVideoActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PostVideoActivity.java index 6df6134a..0864c8ff 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PostVideoActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/PostVideoActivity.java @@ -1,7 +1,6 @@ package ml.docilealligator.infinityforreddit; import android.content.Intent; -import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.Bundle; @@ -34,7 +33,6 @@ import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import javax.inject.Named; -import SubredditDatabase.SubredditRoomDatabase; import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; @@ -55,6 +53,8 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS private static final String FLAIR_STATE = "FS"; private static final String IS_SPOILER_STATE = "ISS"; private static final String IS_NSFW_STATE = "INS"; + private static final String NULL_ACCOUNT_NAME_STATE = "NATS"; + private static final String ACCOUNT_NAME_STATE = "ANS"; private static final int SUBREDDIT_SELECTION_REQUEST_CODE = 0; private static final int PICK_VIDEO_REQUEST_CODE = 1; @@ -75,6 +75,8 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS @BindView(R.id.select_again_text_view_post_video_activity) TextView selectAgainTextView; @BindView(R.id.video_view_post_video_activity) VideoView videoView; + private boolean mNullAccountName = false; + private String mAccountName; private String iconUrl; private String subredditName; private boolean subredditSelected = false; @@ -109,12 +111,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS Retrofit mUploadVideoRetrofit; @Inject - @Named("user_info") - SharedPreferences mUserInfoSharedPreferences; - - @Inject - @Named("auth_info") - SharedPreferences sharedPreferences; + RedditDataRoomDatabase mRedditDataRoomDatabase; @Override protected void onCreate(Bundle savedInstanceState) { @@ -142,6 +139,12 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS flair = savedInstanceState.getString(FLAIR_STATE); isSpoiler = savedInstanceState.getBoolean(IS_SPOILER_STATE); isNSFW = savedInstanceState.getBoolean(IS_NSFW_STATE); + mNullAccountName = savedInstanceState.getBoolean(NULL_ACCOUNT_NAME_STATE); + mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE); + + if(!mNullAccountName && mAccountName == null) { + getCurrentAccountName(); + } if(savedInstanceState.getString(VIDEO_URI_STATE) != null) { videoUri = Uri.parse(savedInstanceState.getString(VIDEO_URI_STATE)); @@ -173,6 +176,8 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS nsfwTextView.setBackgroundColor(getResources().getColor(R.color.colorAccent)); } } else { + getCurrentAccountName(); + isPosting = false; if(getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) { @@ -272,6 +277,16 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS }); } + private void getCurrentAccountName() { + new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> { + if(account == null) { + mNullAccountName = true; + } else { + mAccountName = account.getUsername(); + } + }).execute(); + } + private void loadVideo() { constraintLayout.setVisibility(View.GONE); videoView.setVisibility(View.VISIBLE); @@ -295,7 +310,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS } private void loadSubredditIcon() { - new LoadSubredditIconAsyncTask(SubredditRoomDatabase.getDatabase(this).subredditDao(), + new LoadSubredditIconAsyncTask(mRedditDataRoomDatabase.subredditDao(), subredditName, mRetrofit, iconImageUrl -> { iconUrl = iconImageUrl; displaySubredditIcon(); @@ -387,6 +402,8 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS outState.putString(FLAIR_STATE, flair); outState.putBoolean(IS_SPOILER_STATE, isSpoiler); outState.putBoolean(IS_NSFW_STATE, isNSFW); + outState.putBoolean(NULL_ACCOUNT_NAME_STATE, mNullAccountName); + outState.putString(ACCOUNT_NAME_STATE, mAccountName); } @Override @@ -444,7 +461,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS if(submitVideoPostEvent.postSuccess) { Intent intent = new Intent(this, ViewUserDetailActivity.class); intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, - mUserInfoSharedPreferences.getString(SharedPreferencesUtils.USER_KEY, "")); + mAccountName); startActivity(intent); finish(); } else if(submitVideoPostEvent.errorProcessingVideo) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditDataRoomDatabase.java b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditDataRoomDatabase.java new file mode 100644 index 00000000..4ba61434 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditDataRoomDatabase.java @@ -0,0 +1,42 @@ +package ml.docilealligator.infinityforreddit; + +import android.content.Context; + +import androidx.room.Database; +import androidx.room.Room; +import androidx.room.RoomDatabase; + +import Account.Account; +import Account.AccountDao; +import SubredditDatabase.SubredditDao; +import SubredditDatabase.SubredditData; +import SubscribedSubredditDatabase.SubscribedSubredditDao; +import SubscribedSubredditDatabase.SubscribedSubredditData; +import SubscribedUserDatabase.SubscribedUserDao; +import SubscribedUserDatabase.SubscribedUserData; +import User.UserDao; +import User.UserData; + +@Database(entities = {Account.class, SubredditData.class, SubscribedSubredditData.class, UserData.class, SubscribedUserData.class}, version = 1) +public abstract class RedditDataRoomDatabase extends RoomDatabase { + private static RedditDataRoomDatabase INSTANCE; + + public abstract AccountDao accountDao(); + public abstract SubredditDao subredditDao(); + public abstract SubscribedSubredditDao subscribedSubredditDao(); + public abstract UserDao userDao(); + public abstract SubscribedUserDao subscribedUserDao(); + + public static RedditDataRoomDatabase getDatabase(final Context context) { + if(INSTANCE == null) { + synchronized (RedditDataRoomDatabase.class) { + if(INSTANCE == null) { + INSTANCE = Room.databaseBuilder(context.getApplicationContext(), + RedditDataRoomDatabase.class, "reddit_data") + .build(); + } + } + } + return INSTANCE; + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/SearchResultActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/SearchResultActivity.java index a06f0f6c..42cf85b1 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/SearchResultActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/SearchResultActivity.java @@ -16,6 +16,8 @@ import androidx.viewpager.widget.ViewPager; import com.google.android.material.tabs.TabLayout; +import javax.inject.Inject; + import butterknife.BindView; import butterknife.ButterKnife; @@ -24,6 +26,13 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos static final String EXTRA_QUERY = "QK"; static final String EXTRA_SUBREDDIT_NAME = "ESN"; + private static final String NULL_ACCESS_TOKEN_STATE = "NATS"; + private static final String ACCESS_TOKEN_STATE = "ATS"; + private static final String ACCOUNT_NAME_STATE = "ANS"; + + private boolean mNullAccessToken = false; + private String mAccessToken; + private String mAccountName; private String mQuery; private String mSubredditName; @@ -36,6 +45,9 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos private SearchPostSortTypeBottomSheetFragment searchPostSortTypeBottomSheetFragment; private SearchUserAndSubredditSortTypeBottomSheetFragment searchUserAndSubredditSortTypeBottomSheetFragment; + @Inject + RedditDataRoomDatabase mRedditDataRoomDatabase; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -43,14 +55,23 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos ButterKnife.bind(this); + ((Infinity) getApplication()).getmAppComponent().inject(this); + setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); - sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); - viewPager.setAdapter(sectionsPagerAdapter); - viewPager.setOffscreenPageLimit(2); - - tabLayout.setupWithViewPager(viewPager); + if(savedInstanceState == null) { + getCurrentAccountAndInitializeViewPager(); + } else { + mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE); + mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE); + mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE); + if(!mNullAccessToken && mAccessToken == null) { + getCurrentAccountAndInitializeViewPager(); + } else { + initializeViewPager(); + } + } searchPostSortTypeBottomSheetFragment = new SearchPostSortTypeBottomSheetFragment(); Bundle bundle = new Bundle(); @@ -72,6 +93,25 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos } } + private void getCurrentAccountAndInitializeViewPager() { + new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> { + if(account == null) { + mNullAccessToken = true; + } else { + mAccessToken = account.getAccessToken(); + mAccountName = account.getUsername(); + } + initializeViewPager(); + }).execute(); + } + + private void initializeViewPager() { + sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); + viewPager.setAdapter(sectionsPagerAdapter); + viewPager.setOffscreenPageLimit(2); + tabLayout.setupWithViewPager(viewPager); + } + @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_result_activity, menu); @@ -113,6 +153,14 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos } @Override + protected void onSaveInstanceState(@NonNull Bundle outState) { + super.onSaveInstanceState(outState); + outState.putBoolean(NULL_ACCESS_TOKEN_STATE, mNullAccessToken); + outState.putString(ACCESS_TOKEN_STATE, mAccessToken); + outState.putString(ACCOUNT_NAME_STATE, mAccountName); + } + + @Override public void searchSortTypeSelected(String sortType) { sectionsPagerAdapter.changeSortType(sortType, 0); } @@ -144,21 +192,26 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos bundle.putString(PostFragment.EXTRA_NAME, mSubredditName); bundle.putString(PostFragment.EXTRA_QUERY, mQuery); bundle.putInt(PostFragment.EXTRA_FILTER, PostFragment.EXTRA_NO_FILTER); + bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken); mFragment.setArguments(bundle); return mFragment; } case 1: { SubredditListingFragment mFragment = new SubredditListingFragment(); Bundle bundle = new Bundle(); - bundle.putString(SubredditListingFragment.EXTRA_QUERY_KEY, mQuery); + bundle.putString(SubredditListingFragment.EXTRA_QUERY, mQuery); bundle.putBoolean(SubredditListingFragment.EXTRA_IS_POSTING, false); + bundle.putString(SubredditListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken); + bundle.putString(SubredditListingFragment.EXTRA_ACCOUNT_NAME, mAccountName); mFragment.setArguments(bundle); return mFragment; } default: { UserListingFragment mFragment = new UserListingFragment(); Bundle bundle = new Bundle(); - bundle.putString(UserListingFragment.QUERY_KEY, mQuery); + bundle.putString(UserListingFragment.EXTRA_QUERY, mQuery); + bundle.putString(UserListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken); + bundle.putString(UserListingFragment.EXTRA_ACCOUNT_NAME, mAccountName); mFragment.setArguments(bundle); return mFragment; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/SearchSubredditsResultActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/SearchSubredditsResultActivity.java index 51003eae..aac45900 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/SearchSubredditsResultActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/SearchSubredditsResultActivity.java @@ -10,6 +10,8 @@ import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; +import javax.inject.Inject; + import butterknife.BindView; import butterknife.ButterKnife; @@ -19,12 +21,22 @@ public class SearchSubredditsResultActivity extends AppCompatActivity { static final String EXTRA_RETURN_SUBREDDIT_NAME = "ERSN"; static final String EXTRA_RETURN_SUBREDDIT_ICON_URL = "ERSIURL"; + private static final String NULL_ACCESS_TOKEN_STATE = "NATS"; + private static final String ACCESS_TOKEN_STATE = "ATS"; + private static final String ACCOUNT_NAME_STATE = "ANS"; private static final String FRAGMENT_OUT_STATE = "FOS"; @BindView(R.id.toolbar_search_subreddits_result_activity) Toolbar toolbar; + private boolean mNullAccessToken = false; + private String mAccessToken; + private String mAccountName; + Fragment mFragment; + @Inject + RedditDataRoomDatabase mRedditDataRoomDatabase; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -32,23 +44,46 @@ public class SearchSubredditsResultActivity extends AppCompatActivity { ButterKnife.bind(this); + ((Infinity) getApplication()).getmAppComponent().inject(this); + setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); String query = getIntent().getExtras().getString(EXTRA_QUERY); if(savedInstanceState == null) { + getCurrentAccountAndInitializeFragment(query); + } else { + mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE); + mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE); + mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE); + if(!mNullAccessToken && mAccessToken == null) { + getCurrentAccountAndInitializeFragment(query); + } else { + mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE); + getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_search_subreddits_result_activity, mFragment).commit(); + } + } + } + + private void getCurrentAccountAndInitializeFragment(String query) { + new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> { + if(account == null) { + mNullAccessToken = true; + } else { + mAccessToken = account.getAccessToken(); + mAccountName = account.getUsername(); + } + mFragment = new SubredditListingFragment(); Bundle bundle = new Bundle(); - bundle.putString(SubredditListingFragment.EXTRA_QUERY_KEY, query); + bundle.putString(SubredditListingFragment.EXTRA_QUERY, query); bundle.putBoolean(SubredditListingFragment.EXTRA_IS_POSTING, true); + bundle.putString(SubredditListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken); + bundle.putString(SubredditListingFragment.EXTRA_ACCOUNT_NAME, mAccountName); mFragment.setArguments(bundle); getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_search_subreddits_result_activity, mFragment).commit(); - } else { - mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE); - getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_search_subreddits_result_activity, mFragment).commit(); - - } + }).execute(); } void getSelectedSubreddit(String name, String iconUrl) { @@ -74,5 +109,8 @@ public class SearchSubredditsResultActivity extends AppCompatActivity { if (mFragment != null) { getSupportFragmentManager().putFragment(outState, FRAGMENT_OUT_STATE, mFragment); } + outState.putBoolean(NULL_ACCESS_TOKEN_STATE, mNullAccessToken); + outState.putString(ACCESS_TOKEN_STATE, mAccessToken); + outState.putString(ACCOUNT_NAME_STATE, mAccountName); } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditListingFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditListingFragment.java index 7c250cdf..e4930217 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditListingFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditListingFragment.java @@ -12,6 +12,7 @@ import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; +import androidx.annotation.NonNull; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; @@ -24,7 +25,6 @@ import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar; import javax.inject.Inject; import javax.inject.Named; -import SubscribedSubredditDatabase.SubscribedSubredditRoomDatabase; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; @@ -35,8 +35,10 @@ import retrofit2.Retrofit; */ public class SubredditListingFragment extends Fragment implements FragmentCommunicator { - static final String EXTRA_QUERY_KEY = "EQK"; + static final String EXTRA_QUERY = "EQ"; static final String EXTRA_IS_POSTING = "EIP"; + static final String EXTRA_ACCESS_TOKEN = "EAT"; + static final String EXTRA_ACCOUNT_NAME = "EAN"; @BindView(R.id.coordinator_layout_subreddit_listing_fragment) CoordinatorLayout mCoordinatorLayout; @BindView(R.id.recycler_view_subreddit_listing_fragment) RecyclerView mSubredditListingRecyclerView; @@ -60,13 +62,16 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun @Inject @Named("oauth") Retrofit mOauthRetrofit; + @Inject + RedditDataRoomDatabase redditDataRoomDatabase; + public SubredditListingFragment() { // Required empty public constructor } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, + public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_subreddit_listing, container, false); @@ -80,8 +85,10 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun mLinearLayoutManager = new LinearLayoutManager(getActivity()); mSubredditListingRecyclerView.setLayoutManager(mLinearLayoutManager); - String query = getArguments().getString(EXTRA_QUERY_KEY); + String query = getArguments().getString(EXTRA_QUERY); boolean isPosting = getArguments().getBoolean(EXTRA_IS_POSTING); + String accessToken = getArguments().getString(EXTRA_ACCESS_TOKEN); + String accountName = getArguments().getString(EXTRA_ACCOUNT_NAME); SubredditListingViewModel.Factory factory = new SubredditListingViewModel.Factory(mRetrofit, query, PostDataSource.SORT_TYPE_RELEVANCE, new SubredditListingDataSource.OnSubredditListingDataFetchedCallback() { @@ -99,9 +106,8 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun } }); - mAdapter = new SubredditListingRecyclerViewAdapter(getActivity(), mOauthRetrofit, mRetrofit, - mAuthInfoSharedPreferences, - SubscribedSubredditRoomDatabase.getDatabase(getContext()).subscribedSubredditDao(), + mAdapter = new SubredditListingRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, + accessToken, accountName, redditDataRoomDatabase.subscribedSubredditDao(), new SubredditListingRecyclerViewAdapter.Callback() { @Override public void retryLoadingMore() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditListingRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditListingRecyclerViewAdapter.java index d18e48b6..853ae296 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditListingRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditListingRecyclerViewAdapter.java @@ -1,7 +1,6 @@ package ml.docilealligator.infinityforreddit; import android.content.Context; -import android.content.SharedPreferences; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -44,21 +43,23 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred private Context context; private Retrofit oauthRetrofit; private Retrofit retrofit; - private SharedPreferences authInfoSharedPreferences; + private String accessToken; + private String accountName; private SubscribedSubredditDao subscribedSubredditDao; private NetworkState networkState; private Callback callback; SubredditListingRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, Retrofit retrofit, - SharedPreferences authInfoSharedPreferences, + String accessToken, String accountName, SubscribedSubredditDao subscribedSubredditDao, Callback callback) { super(DIFF_CALLBACK); this.context = context; this.oauthRetrofit = oauthRetrofit; this.retrofit = retrofit; - this.authInfoSharedPreferences = authInfoSharedPreferences; + this.accessToken = accessToken; + this.accountName = accountName; this.subscribedSubredditDao = subscribedSubredditDao; this.callback = callback; glide = Glide.with(context.getApplicationContext()); @@ -112,7 +113,7 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred ((DataViewHolder) holder).subredditNameTextView.setText(subredditData.getName()); - new CheckIsSubscribedToSubredditAsyncTask(subscribedSubredditDao, subredditData.getName(), + new CheckIsSubscribedToSubredditAsyncTask(subscribedSubredditDao, subredditData.getName(), accountName, new CheckIsSubscribedToSubredditAsyncTask.CheckIsSubscribedToSubredditListener() { @Override public void isSubscribed() { @@ -124,7 +125,7 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred ((DataViewHolder) holder).subscribeButton.setVisibility(View.VISIBLE); ((DataViewHolder) holder).subscribeButton.setOnClickListener(view -> { SubredditSubscription.subscribeToSubreddit(oauthRetrofit, retrofit, - authInfoSharedPreferences, subredditData.getName(), subscribedSubredditDao, + accessToken, accountName, subredditData.getName(), subscribedSubredditDao, new SubredditSubscription.SubredditSubscriptionListener() { @Override public void onSubredditSubscriptionSuccess() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditSubscription.java b/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditSubscription.java index ea72db55..c8517154 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditSubscription.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditSubscription.java @@ -1,16 +1,16 @@ package ml.docilealligator.infinityforreddit; -import android.content.SharedPreferences; import android.os.AsyncTask; import android.util.Log; +import androidx.annotation.NonNull; + import java.util.HashMap; import java.util.Map; import SubredditDatabase.SubredditData; import SubscribedSubredditDatabase.SubscribedSubredditDao; import SubscribedSubredditDatabase.SubscribedSubredditData; -import androidx.annotation.NonNull; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Retrofit; @@ -22,27 +22,27 @@ class SubredditSubscription { } static void subscribeToSubreddit(Retrofit oauthRetrofit, Retrofit retrofit, - SharedPreferences authInfoSharedPreferences, String subredditName, + String accessToken, String subredditName, String accountName, SubscribedSubredditDao subscribedSubredditDao, SubredditSubscriptionListener subredditSubscriptionListener) { - subredditSubscription(oauthRetrofit, retrofit, authInfoSharedPreferences, subredditName, "sub", + subredditSubscription(oauthRetrofit, retrofit, accessToken, subredditName, accountName, "sub", subscribedSubredditDao, subredditSubscriptionListener); } - static void unsubscribeToSubreddit(Retrofit oauthRetrofit, SharedPreferences authInfoSharedPreferences, - String subredditName, SubscribedSubredditDao subscribedSubredditDao, + static void unsubscribeToSubreddit(Retrofit oauthRetrofit, String accessToken, + String subredditName, String accountName, + SubscribedSubredditDao subscribedSubredditDao, SubredditSubscriptionListener subredditSubscriptionListener) { - subredditSubscription(oauthRetrofit, null, authInfoSharedPreferences, subredditName, "unsub", + subredditSubscription(oauthRetrofit, null, accessToken, subredditName, accountName, "unsub", subscribedSubredditDao,subredditSubscriptionListener); } - private static void subredditSubscription(Retrofit oauthRetrofit, Retrofit retrofit, SharedPreferences authInfoSharedPreferences, - String subredditName, String action, SubscribedSubredditDao subscribedSubredditDao, + private static void subredditSubscription(Retrofit oauthRetrofit, Retrofit retrofit, String accessToken, + String subredditName, String accountName, String action, + SubscribedSubredditDao subscribedSubredditDao, SubredditSubscriptionListener subredditSubscriptionListener) { RedditAPI api = oauthRetrofit.create(RedditAPI.class); - String accessToken = authInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); - Map<String, String> params = new HashMap<>(); params.put(RedditUtils.ACTION_KEY, action); params.put(RedditUtils.SR_NAME_KEY, subredditName); @@ -57,7 +57,7 @@ class SubredditSubscription { @Override public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { new UpdateSubscriptionAsyncTask(subscribedSubredditDao, - subredditData, true).execute(); + subredditData, accountName, true).execute(); } @Override @@ -66,7 +66,7 @@ class SubredditSubscription { } }); } else { - new UpdateSubscriptionAsyncTask(subscribedSubredditDao, subredditName, false).execute(); + new UpdateSubscriptionAsyncTask(subscribedSubredditDao, subredditName, accountName, false).execute(); } subredditSubscriptionListener.onSubredditSubscriptionSuccess(); } else { @@ -87,20 +87,24 @@ class SubredditSubscription { private SubscribedSubredditDao subscribedSubredditDao; private String subredditName; + private String accountName; private SubscribedSubredditData subscribedSubredditData; private boolean isSubscribing; UpdateSubscriptionAsyncTask(SubscribedSubredditDao subscribedSubredditDao, String subredditName, - boolean isSubscribing) { + String accountName, boolean isSubscribing) { this.subscribedSubredditDao = subscribedSubredditDao; this.subredditName = subredditName; + this.accountName = accountName; this.isSubscribing = isSubscribing; } - UpdateSubscriptionAsyncTask(SubscribedSubredditDao subscribedSubredditDao, SubscribedSubredditData subscribedSubredditData, - boolean isSubscribing) { + UpdateSubscriptionAsyncTask(SubscribedSubredditDao subscribedSubredditDao, SubredditData subredditData, + String accountName, boolean isSubscribing) { this.subscribedSubredditDao = subscribedSubredditDao; - this.subscribedSubredditData = subscribedSubredditData; + this.subscribedSubredditData = new SubscribedSubredditData(subredditData.getId(), subredditData.getName(), + subredditData.getIconUrl(), accountName); + this.accountName = accountName; this.isSubscribing = isSubscribing; } @@ -109,7 +113,7 @@ class SubredditSubscription { if(isSubscribing) { subscribedSubredditDao.insert(subscribedSubredditData); } else { - subscribedSubredditDao.deleteSubscribedSubreddit(subredditName);; + subscribedSubredditDao.deleteSubscribedSubreddit(subredditName, accountName); } return null; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedSubredditsListingFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedSubredditsListingFragment.java index 1e7304c6..21a7c894 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedSubredditsListingFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedSubredditsListingFragment.java @@ -2,7 +2,6 @@ package ml.docilealligator.infinityforreddit; import android.app.Activity; -import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; @@ -10,6 +9,7 @@ import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; +import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; @@ -19,7 +19,6 @@ import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; import javax.inject.Inject; -import javax.inject.Named; import SubscribedSubredditDatabase.SubscribedSubredditViewModel; import butterknife.BindView; @@ -31,6 +30,8 @@ import butterknife.ButterKnife; */ public class SubscribedSubredditsListingFragment extends Fragment { + static final String EXTRA_ACCOUNT_NAME = "EAT"; + static final String EXTRA_ACCOUNT_PROFILE_IMAGE_URL = "EAPIU"; static final String EXTRA_IS_SUBREDDIT_SELECTION = "EISS"; static final String EXTRA_EXTRA_CLEAR_SELECTION = "EECS"; @@ -45,15 +46,14 @@ public class SubscribedSubredditsListingFragment extends Fragment { private SubscribedSubredditViewModel mSubscribedSubredditViewModel; @Inject - @Named("user_info") - SharedPreferences sharedPreferences; + RedditDataRoomDatabase mRedditDataRoomDatabase; public SubscribedSubredditsListingFragment() { // Required empty public constructor } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, + public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_subscribed_subreddits_listing, container, false); @@ -63,8 +63,7 @@ public class SubscribedSubredditsListingFragment extends Fragment { ((Infinity) mActivity.getApplication()).getmAppComponent().inject(this); - String username = sharedPreferences.getString(SharedPreferencesUtils.USER_KEY, ""); - String userIconUrl = sharedPreferences.getString(SharedPreferencesUtils.PROFILE_IMAGE_URL_KEY, ""); + String accountName = getArguments().getString(EXTRA_ACCOUNT_NAME); mGlide = Glide.with(this); @@ -80,7 +79,9 @@ public class SubscribedSubredditsListingFragment extends Fragment { mRecyclerView.setAdapter(adapter); - mSubscribedSubredditViewModel = ViewModelProviders.of(this).get(SubscribedSubredditViewModel.class); + mSubscribedSubredditViewModel = ViewModelProviders.of(this, + new SubscribedSubredditViewModel.Factory(mActivity.getApplication(), mRedditDataRoomDatabase, accountName)) + .get(SubscribedSubredditViewModel.class); mSubscribedSubredditViewModel.getAllSubscribedSubreddits().observe(this, subscribedSubredditData -> { if (subscribedSubredditData == null || subscribedSubredditData.size() == 0) { mRecyclerView.setVisibility(View.GONE); @@ -91,7 +92,7 @@ public class SubscribedSubredditsListingFragment extends Fragment { mRecyclerView.setVisibility(View.VISIBLE); } - adapter.addUser(username, userIconUrl); + adapter.addUser(accountName, getArguments().getString(EXTRA_ACCOUNT_PROFILE_IMAGE_URL)); adapter.setSubscribedSubreddits(subscribedSubredditData); }); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedThingListingActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedThingListingActivity.java index 92568a9f..2ae3471f 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedThingListingActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedThingListingActivity.java @@ -1,6 +1,5 @@ package ml.docilealligator.infinityforreddit; -import android.content.SharedPreferences; import android.os.Bundle; import android.view.MenuItem; import android.view.ViewGroup; @@ -21,11 +20,8 @@ import javax.inject.Inject; import javax.inject.Named; import SubredditDatabase.SubredditData; -import SubredditDatabase.SubredditRoomDatabase; import SubscribedSubredditDatabase.SubscribedSubredditData; -import SubscribedSubredditDatabase.SubscribedSubredditRoomDatabase; import SubscribedUserDatabase.SubscribedUserData; -import SubscribedUserDatabase.SubscribedUserRoomDatabase; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; @@ -34,22 +30,28 @@ public class SubscribedThingListingActivity extends AppCompatActivity { private static final String INSERT_SUBSCRIBED_SUBREDDIT_STATE = "ISSS"; + private static final String NULL_ACCESS_TOKEN_STATE = "NATS"; + private static final String ACCESS_TOKEN_STATE = "ATS"; + private static final String ACCOUNT_NAME_STATE = "ANS"; + @BindView(R.id.toolbar_subscribed_thing_listing_activity) Toolbar toolbar; @BindView(R.id.tab_layout_subscribed_thing_listing_activity) TabLayout tabLayout; @BindView(R.id.view_pager_subscribed_thing_listing_activity) ViewPager viewPager; + private boolean mNullAccessToken = false; + private String mAccessToken; + private String mAccountName; private boolean mInsertSuccess = false; private SectionsPagerAdapter sectionsPagerAdapter; @Inject - @Named("auth_info") - SharedPreferences mAuthInfoSharedPreferences; - - @Inject @Named("oauth") Retrofit mOauthRetrofit; + @Inject + RedditDataRoomDatabase mRedditDataRoomDatabase; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -62,15 +64,39 @@ public class SubscribedThingListingActivity extends AppCompatActivity { setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if(savedInstanceState != null) { + mInsertSuccess = savedInstanceState.getBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE); + mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE); + mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE); + mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE); + if(!mNullAccessToken && mAccessToken == null) { + getCurrentAccountAndInitializeViewPager(); + } else { + initializeViewPagerAndLoadSubscriptions(); + } + } else { + getCurrentAccountAndInitializeViewPager(); + } + } + + private void getCurrentAccountAndInitializeViewPager() { + new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> { + if(account == null) { + mNullAccessToken = true; + } else { + mAccessToken = account.getAccessToken(); + mAccountName = account.getUsername(); + } + initializeViewPagerAndLoadSubscriptions(); + }).execute(); + } + + private void initializeViewPagerAndLoadSubscriptions() { sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(sectionsPagerAdapter); viewPager.setOffscreenPageLimit(2); tabLayout.setupWithViewPager(viewPager); - if(savedInstanceState != null) { - mInsertSuccess = savedInstanceState.getBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE); - } - loadSubscriptions(); } @@ -88,11 +114,14 @@ public class SubscribedThingListingActivity extends AppCompatActivity { protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE, mInsertSuccess); + outState.putBoolean(NULL_ACCESS_TOKEN_STATE, mNullAccessToken); + outState.putString(ACCESS_TOKEN_STATE, mAccessToken); + outState.putString(ACCOUNT_NAME_STATE, mAccountName); } private void loadSubscriptions() { if (!mInsertSuccess) { - FetchSubscribedThing.fetchSubscribedThing(mOauthRetrofit, mAuthInfoSharedPreferences, null, + FetchSubscribedThing.fetchSubscribedThing(mOauthRetrofit, mAccessToken, mAccountName, null, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new FetchSubscribedThing.FetchSubscribedThingListener() { @@ -101,9 +130,9 @@ public class SubscribedThingListingActivity extends AppCompatActivity { ArrayList<SubscribedUserData> subscribedUserData, ArrayList<SubredditData> subredditData) { new InsertSubscribedThingsAsyncTask( - SubscribedSubredditRoomDatabase.getDatabase(SubscribedThingListingActivity.this).subscribedSubredditDao(), - SubscribedUserRoomDatabase.getDatabase(SubscribedThingListingActivity.this).subscribedUserDao(), - SubredditRoomDatabase.getDatabase(SubscribedThingListingActivity.this).subredditDao(), + mRedditDataRoomDatabase.subscribedSubredditDao(), + mRedditDataRoomDatabase.subscribedUserDao(), + mRedditDataRoomDatabase.subredditDao(), subscribedSubredditData, subscribedUserData, subredditData, @@ -132,12 +161,17 @@ public class SubscribedThingListingActivity extends AppCompatActivity { SubscribedSubredditsListingFragment fragment = new SubscribedSubredditsListingFragment(); Bundle bundle = new Bundle(); bundle.putBoolean(SubscribedSubredditsListingFragment.EXTRA_IS_SUBREDDIT_SELECTION, false); + bundle.putString(SubscribedSubredditsListingFragment.EXTRA_ACCOUNT_NAME, mAccountName); fragment.setArguments(bundle); return fragment; } default: { - return new FollowedUsersListingFragment(); + FollowedUsersListingFragment fragment = new FollowedUsersListingFragment(); + Bundle bundle = new Bundle(); + bundle.putString(FollowedUsersListingFragment.EXTRA_ACCOUNT_NAME, mAccountName); + fragment.setArguments(bundle); + return fragment; } } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/UserFollowing.java b/app/src/main/java/ml/docilealligator/infinityforreddit/UserFollowing.java index 18fd09cb..cd7c4893 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/UserFollowing.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/UserFollowing.java @@ -1,6 +1,5 @@ package ml.docilealligator.infinityforreddit; -import android.content.SharedPreferences; import android.os.AsyncTask; import android.util.Log; @@ -23,31 +22,29 @@ class UserFollowing { } static void followUser(Retrofit oauthRetrofit, Retrofit retrofit, - SharedPreferences authInfoSharedPreferences, String userName, + String accessToken, String username, String accountName, SubscribedUserDao subscribedUserDao, UserFollowingListener userFollowingListener) { - userFollowing(oauthRetrofit, retrofit, authInfoSharedPreferences, userName, "sub", + userFollowing(oauthRetrofit, retrofit, accessToken, username, accountName, "sub", subscribedUserDao, userFollowingListener); } static void unfollowUser(Retrofit oauthRetrofit, Retrofit retrofit, - SharedPreferences authInfoSharedPreferences, String userName, + String accessToken, String username, String accountName, SubscribedUserDao subscribedUserDao, UserFollowingListener userFollowingListener) { - userFollowing(oauthRetrofit, retrofit, authInfoSharedPreferences, userName, "unsub", + userFollowing(oauthRetrofit, retrofit, accessToken, username, accountName, "unsub", subscribedUserDao, userFollowingListener); } - private static void userFollowing(Retrofit oauthRetrofit, Retrofit retrofit, SharedPreferences authInfoSharedPreferences, - String userName, String action, SubscribedUserDao subscribedUserDao, + private static void userFollowing(Retrofit oauthRetrofit, Retrofit retrofit, String accessToken, + String username, String accountName, String action, SubscribedUserDao subscribedUserDao, UserFollowingListener userFollowingListener) { RedditAPI api = oauthRetrofit.create(RedditAPI.class); - String accessToken = authInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); - Map<String, String> params = new HashMap<>(); params.put(RedditUtils.ACTION_KEY, action); - params.put(RedditUtils.SR_NAME_KEY, "u_" + userName); + params.put(RedditUtils.SR_NAME_KEY, "u_" + username); Call<String> subredditSubscriptionCall = api.subredditSubscription(RedditUtils.getOAuthHeader(accessToken), params); subredditSubscriptionCall.enqueue(new Callback<String>() { @@ -55,10 +52,10 @@ class UserFollowing { public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) { if(response.isSuccessful()) { if(action.equals("sub")) { - FetchUserData.fetchUserData(retrofit, userName, new FetchUserData.FetchUserDataListener() { + FetchUserData.fetchUserData(retrofit, username, new FetchUserData.FetchUserDataListener() { @Override public void onFetchUserDataSuccess(UserData userData) { - new UpdateSubscriptionAsyncTask(subscribedUserDao, userData, true).execute(); + new UpdateSubscriptionAsyncTask(subscribedUserDao, userData, accountName, true).execute(); } @Override @@ -67,7 +64,7 @@ class UserFollowing { } }); } else { - new UpdateSubscriptionAsyncTask(subscribedUserDao, userName, false).execute(); + new UpdateSubscriptionAsyncTask(subscribedUserDao, username, accountName, false).execute(); } userFollowingListener.onUserFollowingSuccess(); } else { @@ -87,21 +84,25 @@ class UserFollowing { private static class UpdateSubscriptionAsyncTask extends AsyncTask<Void, Void, Void> { private SubscribedUserDao subscribedUserDao; - private String userName; + private String username; + private String accountName; private SubscribedUserData subscribedUserData; private boolean isSubscribing; - UpdateSubscriptionAsyncTask(SubscribedUserDao subscribedUserDao, String userName, - boolean isSubscribing) { + UpdateSubscriptionAsyncTask(SubscribedUserDao subscribedUserDao, String username, + String accountName, boolean isSubscribing) { this.subscribedUserDao = subscribedUserDao; - this.userName = userName; + this.username = username; + this.accountName = accountName; this.isSubscribing = isSubscribing; } - UpdateSubscriptionAsyncTask(SubscribedUserDao subscribedUserDao, SubscribedUserData subscribedUserData, - boolean isSubscribing) { + UpdateSubscriptionAsyncTask(SubscribedUserDao subscribedUserDao, UserData userData, + String accountName, boolean isSubscribing) { this.subscribedUserDao = subscribedUserDao; - this.subscribedUserData = subscribedUserData; + this.subscribedUserData = new SubscribedUserData(userData.getName(), userData.getIconUrl(), + userData.getName()); + this.accountName = accountName; this.isSubscribing = isSubscribing; } @@ -110,7 +111,7 @@ class UserFollowing { if(isSubscribing) { subscribedUserDao.insert(subscribedUserData); } else { - subscribedUserDao.deleteSubscribedUser(userName); + subscribedUserDao.deleteSubscribedUser(username, accountName); } return null; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/UserListingFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/UserListingFragment.java index 4b111a51..ae6f7a66 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/UserListingFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/UserListingFragment.java @@ -22,7 +22,6 @@ import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar; import javax.inject.Inject; import javax.inject.Named; -import SubscribedUserDatabase.SubscribedUserRoomDatabase; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; @@ -32,20 +31,17 @@ import retrofit2.Retrofit; * A simple {@link Fragment} subclass. */ public class UserListingFragment extends Fragment implements FragmentCommunicator { - static final String QUERY_KEY = "QK"; - - @BindView(R.id.coordinator_layout_user_listing_fragment) - CoordinatorLayout mCoordinatorLayout; - @BindView(R.id.recycler_view_user_listing_fragment) - RecyclerView mUserListingRecyclerView; - @BindView(R.id.progress_bar_user_listing_fragment) - CircleProgressBar mProgressBar; - @BindView(R.id.fetch_user_listing_info_linear_layout_user_listing_fragment) - LinearLayout mFetchUserListingInfoLinearLayout; - @BindView(R.id.fetch_user_listing_info_image_view_user_listing_fragment) - ImageView mFetchUserListingInfoImageView; - @BindView(R.id.fetch_user_listing_info_text_view_user_listing_fragment) - TextView mFetchUserListingInfoTextView; + + static final String EXTRA_QUERY = "EQ"; + static final String EXTRA_ACCESS_TOKEN = "EAT"; + static final String EXTRA_ACCOUNT_NAME = "EAN"; + + @BindView(R.id.coordinator_layout_user_listing_fragment) CoordinatorLayout mCoordinatorLayout; + @BindView(R.id.recycler_view_user_listing_fragment) RecyclerView mUserListingRecyclerView; + @BindView(R.id.progress_bar_user_listing_fragment) CircleProgressBar mProgressBar; + @BindView(R.id.fetch_user_listing_info_linear_layout_user_listing_fragment) LinearLayout mFetchUserListingInfoLinearLayout; + @BindView(R.id.fetch_user_listing_info_image_view_user_listing_fragment) ImageView mFetchUserListingInfoImageView; + @BindView(R.id.fetch_user_listing_info_text_view_user_listing_fragment) TextView mFetchUserListingInfoTextView; private LinearLayoutManager mLinearLayoutManager; @@ -65,6 +61,9 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato @Inject @Named("oauth") Retrofit mOauthRetrofit; + @Inject + RedditDataRoomDatabase redditDataRoomDatabase; + public UserListingFragment() { // Required empty public constructor } @@ -83,7 +82,9 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato mLinearLayoutManager = new LinearLayoutManager(getActivity()); mUserListingRecyclerView.setLayoutManager(mLinearLayoutManager); - mQuery = getArguments().getString(QUERY_KEY); + mQuery = getArguments().getString(EXTRA_QUERY); + String accessToken = getArguments().getString(EXTRA_ACCESS_TOKEN); + String accountName = getArguments().getString(EXTRA_ACCOUNT_NAME); UserListingViewModel.Factory factory = new UserListingViewModel.Factory(mRetrofit, mQuery, PostDataSource.SORT_TYPE_RELEVANCE, new UserListingDataSource.OnUserListingDataFetchedCallback() { @@ -102,8 +103,7 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato }); mAdapter = new UserListingRecyclerViewAdapter(getActivity(), mOauthRetrofit, mRetrofit, - mAuthInfoSharedPreferences, - SubscribedUserRoomDatabase.getDatabase(getContext()).subscribedUserDao(), + accessToken, accountName, redditDataRoomDatabase.subscribedUserDao(), () -> mUserListingViewModel.retryLoadingMore()); mUserListingRecyclerView.setAdapter(mAdapter); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/UserListingRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/UserListingRecyclerViewAdapter.java index aa722fc6..415a6b41 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/UserListingRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/UserListingRecyclerViewAdapter.java @@ -2,7 +2,6 @@ package ml.docilealligator.infinityforreddit; import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -44,21 +43,22 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R private Context context; private Retrofit oauthRetrofit; private Retrofit retrofit; - private SharedPreferences authInfoSharedPreferences; + private String accessToken; + private String accountName; private SubscribedUserDao subscribedUserDao; private NetworkState networkState; private UserListingRecyclerViewAdapter.RetryLoadingMoreCallback retryLoadingMoreCallback; UserListingRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, Retrofit retrofit, - SharedPreferences authInfoSharedPreferences, - SubscribedUserDao subscribedUserDao, + String accessToken, String accountName, SubscribedUserDao subscribedUserDao, UserListingRecyclerViewAdapter.RetryLoadingMoreCallback retryLoadingMoreCallback) { super(DIFF_CALLBACK); this.context = context; this.oauthRetrofit = oauthRetrofit; this.retrofit = retrofit; - this.authInfoSharedPreferences = authInfoSharedPreferences; + this.accessToken = accessToken; + this.accountName = accountName; this.subscribedUserDao = subscribedUserDao; this.retryLoadingMoreCallback = retryLoadingMoreCallback; glide = Glide.with(context.getApplicationContext()); @@ -115,7 +115,7 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R ((UserListingRecyclerViewAdapter.DataViewHolder) holder).UserNameTextView.setText(userData.getName()); - new CheckIsFollowingUserAsyncTask(subscribedUserDao, userData.getName(), + new CheckIsFollowingUserAsyncTask(subscribedUserDao, userData.getName(), accountName, new CheckIsFollowingUserAsyncTask.CheckIsFollowingUserListener() { @Override public void isSubscribed() { @@ -127,7 +127,7 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R ((UserListingRecyclerViewAdapter.DataViewHolder) holder).subscribeButton.setVisibility(View.VISIBLE); ((UserListingRecyclerViewAdapter.DataViewHolder) holder).subscribeButton.setOnClickListener(view -> { UserFollowing.followUser(oauthRetrofit, retrofit, - authInfoSharedPreferences, userData.getName(), subscribedUserDao, + accessToken, userData.getName(), accountName, subscribedUserDao, new UserFollowing.UserFollowingListener() { @Override public void onUserFollowingSuccess() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewPostDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewPostDetailActivity.java index 87c4a380..a90e6d0a 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewPostDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewPostDetailActivity.java @@ -2,7 +2,6 @@ package ml.docilealligator.infinityforreddit; import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.Menu; @@ -60,6 +59,10 @@ public class ViewPostDetailActivity extends AppCompatActivity { private int postListPosition = -1; @State + boolean mNullAccessToken = false; + @State + String mAccessToken; + @State Post mPost; @State boolean isLoadingMoreChildren = false; @@ -94,8 +97,8 @@ public class ViewPostDetailActivity extends AppCompatActivity { @Inject @Named("oauth") Retrofit mOauthRetrofit; - @Inject @Named("auth_info") - SharedPreferences mSharedPreferences; + @Inject + RedditDataRoomDatabase mRedditDataRoomDatabase; @Override protected void onCreate(Bundle savedInstanceState) { @@ -121,6 +124,30 @@ public class ViewPostDetailActivity extends AppCompatActivity { orientation = getResources().getConfiguration().orientation; + if(!mNullAccessToken && mAccessToken == null) { + getCurrentAccountAndBindView(); + } else { + bindView(); + } + + if(getIntent().hasExtra(EXTRA_POST_LIST_POSITION)) { + postListPosition = getIntent().getExtras().getInt(EXTRA_POST_LIST_POSITION); + } + } + + private void getCurrentAccountAndBindView() { + new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> { + if(account == null) { + mNullAccessToken = true; + } else { + mAccessToken = account.getAccessToken(); + } + + bindView(); + }).execute(); + } + + private void bindView() { if(mPost == null) { mPost = getIntent().getExtras().getParcelable(EXTRA_POST_DATA); } @@ -130,7 +157,7 @@ public class ViewPostDetailActivity extends AppCompatActivity { fetchPostAndCommentsById(getIntent().getExtras().getString(EXTRA_POST_ID)); } else { mAdapter = new CommentAndPostRecyclerViewAdapter(ViewPostDetailActivity.this, mRetrofit, - mOauthRetrofit, mGlide, mSharedPreferences, mPost, + mOauthRetrofit, mRedditDataRoomDatabase, mGlide, mAccessToken, mPost, mPost.getSubredditNamePrefixed(), mLocale, mLoadSubredditIconAsyncTask, new CommentAndPostRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() { @Override @@ -163,12 +190,9 @@ public class ViewPostDetailActivity extends AppCompatActivity { } } } - - if(getIntent().hasExtra(EXTRA_POST_LIST_POSITION)) { - postListPosition = getIntent().getExtras().getInt(EXTRA_POST_LIST_POSITION); - } } + private void fetchPostAndCommentsById(String subredditId) { mFetchPostInfoLinearLayout.setVisibility(View.GONE); mGlide.clear(mFetchPostInfoImageView); @@ -190,7 +214,7 @@ public class ViewPostDetailActivity extends AppCompatActivity { mPost = post; mAdapter = new CommentAndPostRecyclerViewAdapter(ViewPostDetailActivity.this, mRetrofit, - mOauthRetrofit, mGlide, mSharedPreferences, mPost, + mOauthRetrofit, mRedditDataRoomDatabase, mGlide, mAccessToken, mPost, mPost.getSubredditNamePrefixed(), mLocale, mLoadSubredditIconAsyncTask, new CommentAndPostRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() { @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java index 6b7c67e9..287ebb5f 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java @@ -1,7 +1,6 @@ package ml.docilealligator.infinityforreddit; import android.content.Intent; -import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; @@ -31,10 +30,8 @@ import javax.inject.Named; import SubredditDatabase.SubredditDao; import SubredditDatabase.SubredditData; -import SubredditDatabase.SubredditRoomDatabase; import SubredditDatabase.SubredditViewModel; import SubscribedSubredditDatabase.SubscribedSubredditDao; -import SubscribedSubredditDatabase.SubscribedSubredditRoomDatabase; import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; @@ -48,6 +45,9 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So private static final String FRAGMENT_OUT_STATE_KEY = "FOSK"; private static final String IS_IN_LAZY_MODE_STATE = "IILMS"; + private static final String NULL_ACCESS_TOKEN_STATE = "NATS"; + private static final String ACCESS_TOKEN_STATE = "ATS"; + private static final String ACCOUNT_NAME_STATE = "ANS"; @BindView(R.id.coordinator_layout_view_subreddit_detail_activity) CoordinatorLayout coordinatorLayout; @BindView(R.id.appbar_layout_view_subreddit_detail) AppBarLayout appBarLayout; @@ -62,6 +62,9 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So @BindView(R.id.description_text_view_view_subreddit_detail_activity) TextView descriptionTextView; @BindView(R.id.fab_view_subreddit_detail_activity) FloatingActionButton fab; + private boolean mNullAccessToken = false; + private String mAccessToken; + private String mAccountName; private String subredditName; private boolean subscriptionReady = false; private boolean isInLazyMode = false; @@ -85,8 +88,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So Retrofit mOauthRetrofit; @Inject - @Named("auth_info") - SharedPreferences sharedPreferences; + RedditDataRoomDatabase mRedditDataRoomDatabase; @Override protected void onCreate(Bundle savedInstanceState) { @@ -97,6 +99,23 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So ((Infinity) getApplication()).getmAppComponent().inject(this); + if(savedInstanceState == null) { + getCurrentAccountAndBindView(); + } else { + mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE); + mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE); + mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE); + isInLazyMode = savedInstanceState.getBoolean(IS_IN_LAZY_MODE_STATE); + + if(!mNullAccessToken && mAccessToken == null) { + getCurrentAccountAndBindView(); + } else { + bindView(false); + mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE_KEY); + getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_view_subreddit_detail_activity, mFragment).commit(); + } + } + postTypeBottomSheetFragment = new PostTypeBottomSheetFragment(); sortTypeBottomSheetFragment = new SortTypeBottomSheetFragment(); @@ -123,10 +142,11 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) toolbar.getLayoutParams(); params.topMargin = statusBarHeight; - subscribedSubredditDao = SubscribedSubredditRoomDatabase.getDatabase(this).subscribedSubredditDao(); + subscribedSubredditDao = mRedditDataRoomDatabase.subscribedSubredditDao(); glide = Glide.with(this); - mSubredditViewModel = ViewModelProviders.of(this, new SubredditViewModel.Factory(getApplication(), subredditName)) + mSubredditViewModel = ViewModelProviders.of(this, + new SubredditViewModel.Factory(getApplication(), mRedditDataRoomDatabase, subredditName)) .get(SubredditViewModel.class); mSubredditViewModel.getSubredditLiveData().observe(this, subredditData -> { if(subredditData != null) { @@ -183,12 +203,44 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So } }); + FetchSubredditData.fetchSubredditData(mRetrofit, subredditName, new FetchSubredditData.FetchSubredditDataListener() { + @Override + public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { + new InsertSubredditDataAsyncTask(mRedditDataRoomDatabase, subredditData) + .execute(); + String nOnlineSubscribers = getString(R.string.online_subscribers_number_detail, nCurrentOnlineSubscribers); + nOnlineSubscribersTextView.setText(nOnlineSubscribers); + } + + @Override + public void onFetchSubredditDataFail() { + + } + }); + + fab.setOnClickListener(view -> postTypeBottomSheetFragment.show(getSupportFragmentManager(), postTypeBottomSheetFragment.getTag())); + } + + private void getCurrentAccountAndBindView() { + new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> { + if(account == null) { + mNullAccessToken = true; + } else { + mAccessToken = account.getAccessToken(); + mAccountName = account.getUsername(); + } + bindView(true); + }).execute(); + } + + private void bindView(boolean initializeFragment) { subscribeSubredditChip.setOnClickListener(view -> { if(subscriptionReady) { subscriptionReady = false; if(subscribeSubredditChip.getText().equals(getResources().getString(R.string.subscribe))) { - SubredditSubscription.subscribeToSubreddit(mOauthRetrofit, mRetrofit, sharedPreferences, - subredditName, subscribedSubredditDao, new SubredditSubscription.SubredditSubscriptionListener() { + SubredditSubscription.subscribeToSubreddit(mOauthRetrofit, mRetrofit, mAccessToken, + subredditName, mAccountName, subscribedSubredditDao, + new SubredditSubscription.SubredditSubscriptionListener() { @Override public void onSubredditSubscriptionSuccess() { subscribeSubredditChip.setText(R.string.unsubscribe); @@ -204,8 +256,9 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So } }); } else { - SubredditSubscription.unsubscribeToSubreddit(mOauthRetrofit, sharedPreferences, - subredditName, subscribedSubredditDao, new SubredditSubscription.SubredditSubscriptionListener() { + SubredditSubscription.unsubscribeToSubreddit(mOauthRetrofit, mAccessToken, + subredditName, mAccountName, subscribedSubredditDao, + new SubredditSubscription.SubredditSubscriptionListener() { @Override public void onSubredditSubscriptionSuccess() { subscribeSubredditChip.setText(R.string.subscribe); @@ -224,63 +277,34 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So } }); - new CheckIsSubscribedToSubredditAsyncTask(subscribedSubredditDao, subredditName, + new CheckIsSubscribedToSubredditAsyncTask(subscribedSubredditDao, subredditName, mAccountName, new CheckIsSubscribedToSubredditAsyncTask.CheckIsSubscribedToSubredditListener() { - @Override - public void isSubscribed() { - subscribeSubredditChip.setText(R.string.unsubscribe); - subscribeSubredditChip.setChipBackgroundColor(getResources().getColorStateList(R.color.colorAccent)); - subscriptionReady = true; - } - - @Override - public void isNotSubscribed() { - subscribeSubredditChip.setText(R.string.subscribe); - subscribeSubredditChip.setChipBackgroundColor(getResources().getColorStateList(R.color.backgroundColorPrimaryDark)); - subscriptionReady = true; - } - }).execute(); - - FetchSubredditData.fetchSubredditData(mRetrofit, subredditName, new FetchSubredditData.FetchSubredditDataListener() { - @Override - public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { - new InsertSubredditDataAsyncTask(SubredditRoomDatabase.getDatabase(ViewSubredditDetailActivity.this), subredditData) - .execute(); - String nOnlineSubscribers = getString(R.string.online_subscribers_number_detail, nCurrentOnlineSubscribers); - nOnlineSubscribersTextView.setText(nOnlineSubscribers); - } - - @Override - public void onFetchSubredditDataFail() { - - } - }); - - if(savedInstanceState == null) { + @Override + public void isSubscribed() { + subscribeSubredditChip.setText(R.string.unsubscribe); + subscribeSubredditChip.setChipBackgroundColor(getResources().getColorStateList(R.color.colorAccent)); + subscriptionReady = true; + } + + @Override + public void isNotSubscribed() { + subscribeSubredditChip.setText(R.string.subscribe); + subscribeSubredditChip.setChipBackgroundColor(getResources().getColorStateList(R.color.backgroundColorPrimaryDark)); + subscriptionReady = true; + } + }).execute(); + + if(initializeFragment) { mFragment = new PostFragment(); Bundle bundle = new Bundle(); bundle.putString(PostFragment.EXTRA_NAME, subredditName); bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostDataSource.TYPE_SUBREDDIT); bundle.putString(PostFragment.EXTRA_SORT_TYPE, PostDataSource.SORT_TYPE_BEST); bundle.putInt(PostFragment.EXTRA_FILTER, PostFragment.EXTRA_NO_FILTER); + bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken); mFragment.setArguments(bundle); getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_view_subreddit_detail_activity, mFragment).commit(); - } else { - mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE_KEY); - if(mFragment == null) { - mFragment = new PostFragment(); - Bundle bundle = new Bundle(); - bundle.putString(PostFragment.EXTRA_NAME, subredditName); - bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostDataSource.TYPE_SUBREDDIT); - bundle.putString(PostFragment.EXTRA_SORT_TYPE, PostDataSource.SORT_TYPE_BEST); - bundle.putInt(PostFragment.EXTRA_FILTER, PostFragment.EXTRA_NO_FILTER); - mFragment.setArguments(bundle); - } - isInLazyMode = savedInstanceState.getBoolean(IS_IN_LAZY_MODE_STATE); - getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_view_subreddit_detail_activity, mFragment).commit(); } - - fab.setOnClickListener(view -> postTypeBottomSheetFragment.show(getSupportFragmentManager(), postTypeBottomSheetFragment.getTag())); } @Override @@ -347,6 +371,9 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(IS_IN_LAZY_MODE_STATE, isInLazyMode); + outState.putBoolean(NULL_ACCESS_TOKEN_STATE, mNullAccessToken); + outState.putString(ACCESS_TOKEN_STATE, mAccessToken); + outState.putString(ACCOUNT_NAME_STATE, mAccountName); getSupportFragmentManager().putFragment(outState, FRAGMENT_OUT_STATE_KEY, mFragment); } @@ -390,8 +417,8 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So private SubredditDao mSubredditDao; private SubredditData subredditData; - InsertSubredditDataAsyncTask(SubredditRoomDatabase subredditDb, SubredditData subredditData) { - mSubredditDao = subredditDb.subredditDao(); + InsertSubredditDataAsyncTask(RedditDataRoomDatabase db, SubredditData subredditData) { + mSubredditDao = db.subredditDao(); this.subredditData = subredditData; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewUserDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewUserDetailActivity.java index 2381c59a..fc5f7264 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewUserDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewUserDetailActivity.java @@ -1,7 +1,6 @@ package ml.docilealligator.infinityforreddit; import android.content.Intent; -import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; @@ -33,10 +32,8 @@ import javax.inject.Inject; import javax.inject.Named; import SubscribedUserDatabase.SubscribedUserDao; -import SubscribedUserDatabase.SubscribedUserRoomDatabase; import User.UserDao; import User.UserData; -import User.UserRoomDatabase; import User.UserViewModel; import butterknife.BindView; import butterknife.ButterKnife; @@ -48,6 +45,9 @@ public class ViewUserDetailActivity extends AppCompatActivity { public static final String EXTRA_USER_NAME_KEY = "EUNK"; + private static final String NULL_ACCESS_TOKEN_STATE = "NATS"; + private static final String ACCESS_TOKEN_STATE = "ATS"; + private static final String ACCOUNT_NAME_STATE = "ANS"; private static final String IS_IN_LAZY_MODE_STATE = "IILMS"; @BindView(R.id.coordinator_layout_view_user_detail_activity) CoordinatorLayout coordinatorLayout; @@ -69,6 +69,9 @@ public class ViewUserDetailActivity extends AppCompatActivity { private Menu mMenu; private AppBarLayout.LayoutParams params; + private boolean mNullAccessToken = false; + private String mAccessToken; + private String mAccountName; private String username; private boolean subscriptionReady = false; private boolean isInLazyMode = false; @@ -88,8 +91,7 @@ public class ViewUserDetailActivity extends AppCompatActivity { Retrofit mOauthRetrofit; @Inject - @Named("auth_info") - SharedPreferences sharedPreferences; + RedditDataRoomDatabase mRedditDataRoomDatabase; @Override protected void onCreate(Bundle savedInstanceState) { @@ -100,6 +102,23 @@ public class ViewUserDetailActivity extends AppCompatActivity { ((Infinity) getApplication()).getmAppComponent().inject(this); + if(savedInstanceState == null) { + getCurrentAccountAndInitializeViewPager(); + } else { + mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE); + mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE); + mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE); + isInLazyMode = savedInstanceState.getBoolean(IS_IN_LAZY_MODE_STATE); + + if(!mNullAccessToken && mAccessToken == null) { + getCurrentAccountAndInitializeViewPager(); + } else { + initializeViewPager(); + } + } + + getCurrentAccountAndInitializeViewPager(); + params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams(); //Get status bar height @@ -120,11 +139,6 @@ public class ViewUserDetailActivity extends AppCompatActivity { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) toolbar.getLayoutParams(); params.topMargin = statusBarHeight; - sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); - viewPager.setAdapter(sectionsPagerAdapter); - viewPager.setOffscreenPageLimit(2); - tabLayout.setupWithViewPager(viewPager); - expandedTabTextColor = getResources().getColor(R.color.tabLayoutWithExpandedCollapsingToolbarTextColor); expandedTabBackgroundColor = getResources().getColor(R.color.tabLayoutWithExpandedCollapsingToolbarTabBackground); expandedTabIndicatorColor = getResources().getColor(R.color.tabLayoutWithExpandedCollapsingToolbarTabIndicator); @@ -148,10 +162,10 @@ public class ViewUserDetailActivity extends AppCompatActivity { } }); - subscribedUserDao = SubscribedUserRoomDatabase.getDatabase(this).subscribedUserDao(); + subscribedUserDao = mRedditDataRoomDatabase.subscribedUserDao(); glide = Glide.with(this); - userViewModel = ViewModelProviders.of(this, new UserViewModel.Factory(getApplication(), username)) + userViewModel = ViewModelProviders.of(this, new UserViewModel.Factory(getApplication(), mRedditDataRoomDatabase, username)) .get(UserViewModel.class); userViewModel.getUserLiveData().observe(this, userData -> { if(userData != null) { @@ -199,8 +213,8 @@ public class ViewUserDetailActivity extends AppCompatActivity { if(subscriptionReady) { subscriptionReady = false; if(subscribeUserChip.getText().equals(getResources().getString(R.string.follow))) { - UserFollowing.followUser(mOauthRetrofit, mRetrofit, sharedPreferences, - username, subscribedUserDao, new UserFollowing.UserFollowingListener() { + UserFollowing.followUser(mOauthRetrofit, mRetrofit, mAccessToken, + username, mAccountName, subscribedUserDao, new UserFollowing.UserFollowingListener() { @Override public void onUserFollowingSuccess() { subscribeUserChip.setText(R.string.unfollow); @@ -216,8 +230,8 @@ public class ViewUserDetailActivity extends AppCompatActivity { } }); } else { - UserFollowing.unfollowUser(mOauthRetrofit, mRetrofit, sharedPreferences, - username, subscribedUserDao, new UserFollowing.UserFollowingListener() { + UserFollowing.unfollowUser(mOauthRetrofit, mRetrofit, mAccessToken, + username, mAccountName, subscribedUserDao, new UserFollowing.UserFollowingListener() { @Override public void onUserFollowingSuccess() { subscribeUserChip.setText(R.string.follow); @@ -236,7 +250,7 @@ public class ViewUserDetailActivity extends AppCompatActivity { } }); - new CheckIsFollowingUserAsyncTask(subscribedUserDao, username, new CheckIsFollowingUserAsyncTask.CheckIsFollowingUserListener() { + new CheckIsFollowingUserAsyncTask(subscribedUserDao, username, mAccountName, new CheckIsFollowingUserAsyncTask.CheckIsFollowingUserListener() { @Override public void isSubscribed() { subscribeUserChip.setText(R.string.unfollow); @@ -268,7 +282,7 @@ public class ViewUserDetailActivity extends AppCompatActivity { FetchUserData.fetchUserData(mRetrofit, username, new FetchUserData.FetchUserDataListener() { @Override public void onFetchUserDataSuccess(UserData userData) { - new InsertUserDataAsyncTask(UserRoomDatabase.getDatabase(ViewUserDetailActivity.this).userDao(), userData).execute(); + new InsertUserDataAsyncTask(mRedditDataRoomDatabase.userDao(), userData).execute(); } @Override @@ -276,26 +290,25 @@ public class ViewUserDetailActivity extends AppCompatActivity { makeSnackbar(R.string.cannot_fetch_user_info); } }); + } - if(savedInstanceState == null) { - /*mFragment = new PostFragment(); - Bundle bundle = new Bundle(); - bundle.putString(PostFragment.EXTRA_NAME, username); - bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostDataSource.TYPE_USER); - mFragment.setArguments(bundle); - getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_view_user_detail_activity, mFragment).commit();*/ - } else { - /*mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE_KEY); - if(mFragment == null) { - mFragment = new PostFragment(); - Bundle bundle = new Bundle(); - bundle.putString(PostFragment.EXTRA_NAME, username); - bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostDataSource.TYPE_USER); - mFragment.setArguments(bundle); - }*/ - isInLazyMode = savedInstanceState.getBoolean(IS_IN_LAZY_MODE_STATE); - //getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_view_user_detail_activity, mFragment).commit(); - } + private void getCurrentAccountAndInitializeViewPager() { + new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> { + if(account == null) { + mNullAccessToken = true; + } else { + mAccessToken = account.getAccessToken(); + mAccountName = account.getUsername(); + } + initializeViewPager(); + }).execute(); + } + + private void initializeViewPager() { + sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); + viewPager.setAdapter(sectionsPagerAdapter); + viewPager.setOffscreenPageLimit(2); + tabLayout.setupWithViewPager(viewPager); } @Override @@ -318,7 +331,7 @@ public class ViewUserDetailActivity extends AppCompatActivity { } @Override - public boolean onOptionsItemSelected(MenuItem item) { + public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); @@ -359,7 +372,9 @@ public class ViewUserDetailActivity extends AppCompatActivity { protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(IS_IN_LAZY_MODE_STATE, isInLazyMode); - //getSupportFragmentManager().putFragment(outState, FRAGMENT_OUT_STATE_KEY, mFragment); + outState.putBoolean(NULL_ACCESS_TOKEN_STATE, mNullAccessToken); + outState.putString(ACCESS_TOKEN_STATE, mAccessToken); + outState.putString(ACCOUNT_NAME_STATE, mAccountName); } private void makeSnackbar(int resId) { @@ -438,12 +453,14 @@ public class ViewUserDetailActivity extends AppCompatActivity { bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostDataSource.TYPE_USER); bundle.putString(PostFragment.EXTRA_USER_NAME, username); bundle.putInt(PostFragment.EXTRA_FILTER, PostFragment.EXTRA_NO_FILTER); + bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken); fragment.setArguments(bundle); return fragment; } CommentsListingFragment fragment = new CommentsListingFragment(); Bundle bundle = new Bundle(); bundle.putString(CommentsListingFragment.EXTRA_USERNAME_KEY, username); + bundle.putString(CommentsListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken); fragment.setArguments(bundle); return fragment; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/VoteThing.java b/app/src/main/java/ml/docilealligator/infinityforreddit/VoteThing.java index c6f8bc12..4bd39936 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/VoteThing.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/VoteThing.java @@ -1,6 +1,5 @@ package ml.docilealligator.infinityforreddit; -import android.content.SharedPreferences; import android.util.Log; import androidx.annotation.NonNull; @@ -28,12 +27,11 @@ class VoteThing { void onVoteThingFail(); } - static void voteThing(final Retrofit retrofit, SharedPreferences authInfoSharedPreferences, + static void voteThing(final Retrofit retrofit, String accessToken, final VoteThingListener voteThingListener, final String fullName, final String point, final int position) { RedditAPI api = retrofit.create(RedditAPI.class); - String accessToken = authInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); Map<String, String> params = new HashMap<>(); params.put(RedditUtils.DIR_KEY, point); params.put(RedditUtils.ID_KEY, fullName); @@ -58,12 +56,11 @@ class VoteThing { }); } - static void voteThing(final Retrofit retrofit, SharedPreferences authInfoSharedPreferences, + static void voteThing(final Retrofit retrofit, String accessToken, final VoteThingWithoutPositionListener voteThingWithoutPositionListener, final String fullName, final String point) { RedditAPI api = retrofit.create(RedditAPI.class); - String accessToken = authInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); Map<String, String> params = new HashMap<>(); params.put(RedditUtils.DIR_KEY, point); params.put(RedditUtils.ID_KEY, fullName); |