Added feature: View users' best posts.

This commit is contained in:
Alex Ning 2019-01-21 22:32:17 +08:00
parent ebc2cac0a6
commit 91e6174aa5
11 changed files with 306 additions and 184 deletions

View File

@ -67,4 +67,5 @@ public class JSONUtils {
static final String LINK_ID_KEY = "link_id"; static final String LINK_ID_KEY = "link_id";
public static final String IS_GOLD_KEY = "is_gold"; public static final String IS_GOLD_KEY = "is_gold";
public static final String IS_FRIEND_KEY = "is_friend"; public static final String IS_FRIEND_KEY = "is_friend";
static final String KIND_KEY = "kind";
} }

View File

@ -116,7 +116,7 @@ public class MainActivity extends AppCompatActivity {
if(savedInstanceState == null) { if(savedInstanceState == null) {
mFragment = new PostFragment(); mFragment = new PostFragment();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putBoolean(PostFragment.IS_BEST_POST_KEY, true); bundle.putInt(PostFragment.POST_TYPE_KEY, PostDataSource.TYPE_FRONT_PAGE);
mFragment.setArguments(bundle); mFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_content_main, mFragment).commit(); getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_content_main, mFragment).commit();
} else { } else {

View File

@ -55,6 +55,10 @@ class ParsePost {
lastItem = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.AFTER_KEY); lastItem = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.AFTER_KEY);
for(int i = 0; i < allData.length(); i++) { for(int i = 0; i < allData.length(); i++) {
String kind = allData.getJSONObject(i).getString(JSONUtils.KIND_KEY);
if(!kind.equals("t3")) {
continue;
}
JSONObject data = allData.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY); JSONObject data = allData.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY);
String id = data.getString(JSONUtils.ID_KEY); String id = data.getString(JSONUtils.ID_KEY);
String fullName = data.getString(JSONUtils.NAME_KEY); String fullName = data.getString(JSONUtils.NAME_KEY);

View File

@ -13,11 +13,14 @@ import retrofit2.Callback;
import retrofit2.Retrofit; import retrofit2.Retrofit;
class PostDataSource extends PageKeyedDataSource<String, Post> { class PostDataSource extends PageKeyedDataSource<String, Post> {
static final int TYPE_FRONT_PAGE = 0;
static final int TYPE_SUBREDDIT = 1;
static final int TYPE_USER = 2;
private Retrofit retrofit; private Retrofit retrofit;
private String accessToken; private String accessToken;
private Locale locale; private Locale locale;
private boolean isBestPost; private String name;
private String subredditName; private int postType;
private MutableLiveData<NetworkState> paginationNetworkStateLiveData; private MutableLiveData<NetworkState> paginationNetworkStateLiveData;
private MutableLiveData<NetworkState> initialLoadStateLiveData; private MutableLiveData<NetworkState> initialLoadStateLiveData;
@ -27,23 +30,22 @@ class PostDataSource extends PageKeyedDataSource<String, Post> {
private LoadParams<String> params; private LoadParams<String> params;
private LoadCallback<String, Post> callback; private LoadCallback<String, Post> callback;
PostDataSource(Retrofit retrofit, String accessToken, Locale locale, boolean isBestPost) { PostDataSource(Retrofit retrofit, String accessToken, Locale locale, int postType) {
this.retrofit = retrofit; this.retrofit = retrofit;
this.accessToken = accessToken; this.accessToken = accessToken;
this.locale = locale; this.locale = locale;
this.isBestPost = isBestPost;
paginationNetworkStateLiveData = new MutableLiveData(); paginationNetworkStateLiveData = new MutableLiveData();
initialLoadStateLiveData = new MutableLiveData(); initialLoadStateLiveData = new MutableLiveData();
this.postType = postType;
} }
PostDataSource(Retrofit retrofit, Locale locale, boolean isBestPost, String subredditName) { PostDataSource(Retrofit retrofit, Locale locale, String name, int postType) {
this.retrofit = retrofit; this.retrofit = retrofit;
this.locale = locale; this.locale = locale;
this.isBestPost = isBestPost; this.name = name;
this.subredditName = subredditName;
paginationNetworkStateLiveData = new MutableLiveData(); paginationNetworkStateLiveData = new MutableLiveData();
initialLoadStateLiveData = new MutableLiveData(); initialLoadStateLiveData = new MutableLiveData();
this.postType = postType;
} }
MutableLiveData getPaginationNetworkStateLiveData() { MutableLiveData getPaginationNetworkStateLiveData() {
@ -61,10 +63,47 @@ class PostDataSource extends PageKeyedDataSource<String, Post> {
initialLoadStateLiveData.postValue(NetworkState.LOADING); initialLoadStateLiveData.postValue(NetworkState.LOADING);
if(isBestPost) { switch (postType) {
case TYPE_FRONT_PAGE:
loadBestPostsInitial(callback);
break;
case TYPE_SUBREDDIT:
loadSubredditPostsInitial(callback);
break;
case TYPE_USER:
loadUserPostsInitial(callback);
break;
}
}
@Override
public void loadBefore(@NonNull LoadParams<String> params, @NonNull LoadCallback<String, Post> callback) {
}
@Override
public void loadAfter(@NonNull LoadParams<String> params, @NonNull final LoadCallback<String, Post> callback) {
this.params = params;
this.callback = callback;
paginationNetworkStateLiveData.postValue(NetworkState.LOADING);
switch (postType) {
case TYPE_FRONT_PAGE:
loadBestPostsAfter(params, callback);
break;
case TYPE_SUBREDDIT:
loadSubredditPostsAfter(params, callback);
break;
case TYPE_USER:
loadUserPostsAfter(params, callback);
}
}
private void loadBestPostsInitial(@NonNull final LoadInitialCallback<String, Post> callback) {
RedditAPI api = retrofit.create(RedditAPI.class); RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> bestPost = api.getBestPost(null, RedditUtils.getOAuthHeader(accessToken)); Call<String> bestPost = api.getBestPosts(null, RedditUtils.getOAuthHeader(accessToken));
bestPost.enqueue(new Callback<String>() { bestPost.enqueue(new Callback<String>() {
@Override @Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) { public void onResponse(Call<String> call, retrofit2.Response<String> response) {
@ -95,57 +134,11 @@ class PostDataSource extends PageKeyedDataSource<String, Post> {
initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, errorMessage)); initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, errorMessage));
} }
}); });
} else { }
private void loadBestPostsAfter(@NonNull LoadParams<String> params, @NonNull final LoadCallback<String, Post> callback) {
RedditAPI api = retrofit.create(RedditAPI.class); RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> getPost = api.getPost(subredditName, null); Call<String> bestPost = api.getBestPosts(params.key, RedditUtils.getOAuthHeader(accessToken));
getPost.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if(response.isSuccessful()) {
ParsePost.parsePost(response.body(), locale,
new ParsePost.ParsePostListener() {
@Override
public void onParsePostSuccess(ArrayList<Post> newPosts, String lastItem) {
callback.onResult(newPosts, null, lastItem);
initialLoadStateLiveData.postValue(NetworkState.LOADED);
}
@Override
public void onParsePostFail() {
Log.i("Post fetch error", "Error parsing data");
initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
}
});
} else {
Log.i("Post fetch error", response.message());
initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
String errorMessage = t == null ? "unknown error" : t.getMessage();
initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, errorMessage));
}
});
}
}
@Override
public void loadBefore(@NonNull LoadParams<String> params, @NonNull LoadCallback<String, Post> callback) {
}
@Override
public void loadAfter(@NonNull LoadParams<String> params, @NonNull final LoadCallback<String, Post> callback) {
this.params = params;
this.callback = callback;
paginationNetworkStateLiveData.postValue(NetworkState.LOADING);
if(isBestPost) {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> bestPost = api.getBestPost(params.key, RedditUtils.getOAuthHeader(accessToken));
bestPost.enqueue(new Callback<String>() { bestPost.enqueue(new Callback<String>() {
@Override @Override
@ -176,9 +169,46 @@ class PostDataSource extends PageKeyedDataSource<String, Post> {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, errorMessage)); paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, errorMessage));
} }
}); });
} else { }
private void loadSubredditPostsInitial(@NonNull final LoadInitialCallback<String, Post> callback) {
RedditAPI api = retrofit.create(RedditAPI.class); RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> getPost = api.getPost(subredditName, params.key); Call<String> getPost = api.getSubredditBestPosts(name, null);
getPost.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if(response.isSuccessful()) {
ParsePost.parsePost(response.body(), locale,
new ParsePost.ParsePostListener() {
@Override
public void onParsePostSuccess(ArrayList<Post> newPosts, String lastItem) {
callback.onResult(newPosts, null, lastItem);
initialLoadStateLiveData.postValue(NetworkState.LOADED);
}
@Override
public void onParsePostFail() {
Log.i("Post fetch error", "Error parsing data");
initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
}
});
} else {
Log.i("Post fetch error", response.message());
initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
String errorMessage = t == null ? "unknown error" : t.getMessage();
initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, errorMessage));
}
});
}
private void loadSubredditPostsAfter(@NonNull LoadParams<String> params, @NonNull final LoadCallback<String, Post> callback) {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> getPost = api.getSubredditBestPosts(name, params.key);
getPost.enqueue(new Callback<String>() { getPost.enqueue(new Callback<String>() {
@Override @Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) { public void onResponse(Call<String> call, retrofit2.Response<String> response) {
@ -209,6 +239,74 @@ class PostDataSource extends PageKeyedDataSource<String, Post> {
} }
}); });
} }
private void loadUserPostsInitial(@NonNull final LoadInitialCallback<String, Post> callback) {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> getPost = api.getUserBestPosts(name, null);
getPost.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if(response.isSuccessful()) {
ParsePost.parsePost(response.body(), locale,
new ParsePost.ParsePostListener() {
@Override
public void onParsePostSuccess(ArrayList<Post> newPosts, String lastItem) {
callback.onResult(newPosts, null, lastItem);
initialLoadStateLiveData.postValue(NetworkState.LOADED);
}
@Override
public void onParsePostFail() {
Log.i("Post fetch error", "Error parsing data");
initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
}
});
} else {
Log.i("Post fetch error", response.message());
initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
String errorMessage = t == null ? "unknown error" : t.getMessage();
initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, errorMessage));
}
});
}
private void loadUserPostsAfter(@NonNull LoadParams<String> params, @NonNull final LoadCallback<String, Post> callback) {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> getPost = api.getUserBestPosts(name, params.key);
getPost.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if(response.isSuccessful()) {
ParsePost.parsePost(response.body(), locale, new ParsePost.ParsePostListener() {
@Override
public void onParsePostSuccess(ArrayList<Post> newPosts, String lastItem) {
callback.onResult(newPosts, lastItem);
paginationNetworkStateLiveData.postValue(NetworkState.LOADED);
}
@Override
public void onParsePostFail() {
Log.i("Best post", "Error parsing data");
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
}
});
} else {
Log.i("Best post", response.message());
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
String errorMessage = t == null ? "unknown error" : t.getMessage();
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, errorMessage));
}
});
} }
void retry() { void retry() {

View File

@ -12,33 +12,33 @@ class PostDataSourceFactory extends DataSource.Factory {
private String accessToken; private String accessToken;
private Locale locale; private Locale locale;
private String subredditName; private String subredditName;
private boolean isBestPost; private int postType;
private PostDataSource postDataSource; private PostDataSource postDataSource;
private MutableLiveData<PostDataSource> postDataSourceLiveData; private MutableLiveData<PostDataSource> postDataSourceLiveData;
PostDataSourceFactory(Retrofit retrofit, String accessToken, Locale locale, boolean isBestPost) { PostDataSourceFactory(Retrofit retrofit, String accessToken, Locale locale, int postType) {
this.retrofit = retrofit; this.retrofit = retrofit;
this.accessToken = accessToken; this.accessToken = accessToken;
this.locale = locale; this.locale = locale;
postDataSourceLiveData = new MutableLiveData<>(); postDataSourceLiveData = new MutableLiveData<>();
this.isBestPost = isBestPost; this.postType = postType;
} }
PostDataSourceFactory(Retrofit retrofit, Locale locale, boolean isBestPost, String subredditName) { PostDataSourceFactory(Retrofit retrofit, Locale locale, String subredditName, int postType) {
this.retrofit = retrofit; this.retrofit = retrofit;
this.locale = locale; this.locale = locale;
this.subredditName = subredditName; this.subredditName = subredditName;
postDataSourceLiveData = new MutableLiveData<>(); postDataSourceLiveData = new MutableLiveData<>();
this.isBestPost = isBestPost; this.postType = postType;
} }
@Override @Override
public DataSource create() { public DataSource create() {
if(isBestPost) { if(postType == PostDataSource.TYPE_FRONT_PAGE) {
postDataSource = new PostDataSource(retrofit, accessToken, locale, isBestPost); postDataSource = new PostDataSource(retrofit, accessToken, locale, postType);
} else { } else {
postDataSource = new PostDataSource(retrofit, locale, isBestPost, subredditName); postDataSource = new PostDataSource(retrofit, locale, subredditName, postType);
} }
postDataSourceLiveData.postValue(postDataSource); postDataSourceLiveData.postValue(postDataSource);

View File

@ -31,8 +31,8 @@ import retrofit2.Retrofit;
*/ */
public class PostFragment extends Fragment implements FragmentCommunicator { public class PostFragment extends Fragment implements FragmentCommunicator {
static final String SUBREDDIT_NAME_KEY = "SNK"; static final String NAME_KEY = "NK";
static final String IS_BEST_POST_KEY = "IBPK"; static final String POST_TYPE_KEY = "PTK";
private CoordinatorLayout mCoordinatorLayout; private CoordinatorLayout mCoordinatorLayout;
private RecyclerView mPostRecyclerView; private RecyclerView mPostRecyclerView;
@ -41,8 +41,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private LinearLayout mFetchPostErrorLinearLayout; private LinearLayout mFetchPostErrorLinearLayout;
private ImageView mFetchPostErrorImageView; private ImageView mFetchPostErrorImageView;
private boolean mIsBestPost; private String mName;
private String mSubredditName; private int mPostType;
private PostRecyclerViewAdapter mAdapter; private PostRecyclerViewAdapter mAdapter;
@ -93,20 +93,20 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
} }
});*/ });*/
mIsBestPost = getArguments().getBoolean(IS_BEST_POST_KEY); mPostType = getArguments().getInt(POST_TYPE_KEY);
if(!mIsBestPost) { if(mPostType != PostDataSource.TYPE_FRONT_PAGE) {
mSubredditName = getArguments().getString(SUBREDDIT_NAME_KEY); mName = getArguments().getString(NAME_KEY);
} else { } else {
mFetchPostErrorLinearLayout.setOnClickListener(view -> mPostViewModel.retry()); mFetchPostErrorLinearLayout.setOnClickListener(view -> mPostViewModel.retry());
} }
if(mIsBestPost) { if(mPostType == PostDataSource.TYPE_FRONT_PAGE) {
mAdapter = new PostRecyclerViewAdapter(getActivity(), mOauthRetrofit, mAdapter = new PostRecyclerViewAdapter(getActivity(), mOauthRetrofit,
mSharedPreferences, mIsBestPost, () -> mPostViewModel.retryLoadingMore()); mSharedPreferences, mPostType, () -> mPostViewModel.retryLoadingMore());
} else { } else {
mAdapter = new PostRecyclerViewAdapter(getActivity(), mRetrofit, mAdapter = new PostRecyclerViewAdapter(getActivity(), mRetrofit,
mSharedPreferences, mIsBestPost, () -> mPostViewModel.retryLoadingMore()); mSharedPreferences, mPostType, () -> mPostViewModel.retryLoadingMore());
} }
mPostRecyclerView.setAdapter(mAdapter); mPostRecyclerView.setAdapter(mAdapter);
@ -114,12 +114,12 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); .getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, "");
PostViewModel.Factory factory; PostViewModel.Factory factory;
if(mIsBestPost) { if(mPostType == PostDataSource.TYPE_FRONT_PAGE) {
factory = new PostViewModel.Factory(mOauthRetrofit, accessToken, factory = new PostViewModel.Factory(mOauthRetrofit, accessToken,
getResources().getConfiguration().locale, mIsBestPost); getResources().getConfiguration().locale, mPostType);
} else { } else {
factory = new PostViewModel.Factory(mRetrofit, factory = new PostViewModel.Factory(mRetrofit,
getResources().getConfiguration().locale, mIsBestPost, mSubredditName); getResources().getConfiguration().locale, mName, mPostType);
} }
mPostViewModel = ViewModelProviders.of(this, factory).get(PostViewModel.class); mPostViewModel = ViewModelProviders.of(this, factory).get(PostViewModel.class);
mPostViewModel.getPosts().observe(this, posts -> mAdapter.submitList(posts)); mPostViewModel.getPosts().observe(this, posts -> mAdapter.submitList(posts));
@ -149,7 +149,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private void showErrorView() { private void showErrorView() {
mProgressBar.setVisibility(View.GONE); mProgressBar.setVisibility(View.GONE);
if(mIsBestPost) { if(mPostType == PostDataSource.TYPE_FRONT_PAGE) {
if(getActivity() != null && isAdded()) { if(getActivity() != null && isAdded()) {
mFetchPostErrorLinearLayout.setVisibility(View.VISIBLE); mFetchPostErrorLinearLayout.setVisibility(View.VISIBLE);
Glide.with(this).load(R.drawable.load_post_error_indicator).into(mFetchPostErrorImageView); Glide.with(this).load(R.drawable.load_post_error_indicator).into(mFetchPostErrorImageView);

View File

@ -60,7 +60,7 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo
private SubredditDao subredditDao; private SubredditDao subredditDao;
private UserDao userDao; private UserDao userDao;
private boolean canStartActivity = true; private boolean canStartActivity = true;
private boolean hasMultipleSubreddits; private int postType;
private static final int VIEW_TYPE_DATA = 0; private static final int VIEW_TYPE_DATA = 0;
private static final int VIEW_TYPE_ERROR = 1; private static final int VIEW_TYPE_ERROR = 1;
@ -73,14 +73,14 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo
void retryLoadingMore(); void retryLoadingMore();
} }
PostRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, SharedPreferences sharedPreferences, boolean hasMultipleSubreddits, PostRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, SharedPreferences sharedPreferences, int postType,
RetryLoadingMoreCallback retryLoadingMoreCallback) { RetryLoadingMoreCallback retryLoadingMoreCallback) {
super(DIFF_CALLBACK); super(DIFF_CALLBACK);
if(context != null) { if(context != null) {
mContext = context; mContext = context;
mOauthRetrofit = oauthRetrofit; mOauthRetrofit = oauthRetrofit;
mSharedPreferences = sharedPreferences; mSharedPreferences = sharedPreferences;
this.hasMultipleSubreddits = hasMultipleSubreddits; this.postType = postType;
glide = Glide.with(mContext.getApplicationContext()); glide = Glide.with(mContext.getApplicationContext());
subredditDao = SubredditRoomDatabase.getDatabase(mContext.getApplicationContext()).subredditDao(); subredditDao = SubredditRoomDatabase.getDatabase(mContext.getApplicationContext()).subredditDao();
userDao = UserRoomDatabase.getDatabase(mContext.getApplicationContext()).userDao(); userDao = UserRoomDatabase.getDatabase(mContext.getApplicationContext()).userDao();
@ -148,7 +148,7 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo
} }
}); });
if(hasMultipleSubreddits) { if(postType != PostDataSource.TYPE_SUBREDDIT) {
if(post.getSubredditIconUrl() == null) { if(post.getSubredditIconUrl() == null) {
new LoadSubredditIconAsyncTask(subredditDao, subredditName, new LoadSubredditIconAsyncTask(subredditDao, subredditName,
iconImageUrl -> { iconImageUrl -> {
@ -355,7 +355,7 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo
loadImage(holder, post); loadImage(holder, post);
} }
if(!hasMultipleSubreddits && post.isStickied()) { if(postType == PostDataSource.TYPE_SUBREDDIT && post.isStickied()) {
((DataViewHolder) holder).stickiedPostImageView.setVisibility(View.VISIBLE); ((DataViewHolder) holder).stickiedPostImageView.setVisibility(View.VISIBLE);
glide.load(R.drawable.thumbtack).into(((DataViewHolder) holder).stickiedPostImageView); glide.load(R.drawable.thumbtack).into(((DataViewHolder) holder).stickiedPostImageView);
} }

View File

@ -18,8 +18,8 @@ public class PostViewModel extends ViewModel {
private LiveData<NetworkState> initialLoadingState; private LiveData<NetworkState> initialLoadingState;
private LiveData<PagedList<Post>> posts; private LiveData<PagedList<Post>> posts;
public PostViewModel(Retrofit retrofit, String accessToken, Locale locale, boolean isBestPost) { public PostViewModel(Retrofit retrofit, String accessToken, Locale locale, int postType) {
postDataSourceFactory = new PostDataSourceFactory(retrofit, accessToken, locale, isBestPost); postDataSourceFactory = new PostDataSourceFactory(retrofit, accessToken, locale, postType);
initialLoadingState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(), initialLoadingState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
dataSource -> dataSource.getInitialLoadStateLiveData()); dataSource -> dataSource.getInitialLoadStateLiveData());
@ -34,8 +34,8 @@ public class PostViewModel extends ViewModel {
posts = (new LivePagedListBuilder(postDataSourceFactory, pagedListConfig)).build(); posts = (new LivePagedListBuilder(postDataSourceFactory, pagedListConfig)).build();
} }
public PostViewModel(Retrofit retrofit, Locale locale, boolean isBestPost, String subredditName) { public PostViewModel(Retrofit retrofit, Locale locale, String subredditName, int postType) {
postDataSourceFactory = new PostDataSourceFactory(retrofit, locale, isBestPost, subredditName); postDataSourceFactory = new PostDataSourceFactory(retrofit, locale, subredditName, postType);
initialLoadingState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(), initialLoadingState = Transformations.switchMap(postDataSourceFactory.getPostDataSourceLiveData(),
dataSource -> dataSource.getInitialLoadStateLiveData()); dataSource -> dataSource.getInitialLoadStateLiveData());
@ -79,30 +79,30 @@ public class PostViewModel extends ViewModel {
private Retrofit retrofit; private Retrofit retrofit;
private String accessToken; private String accessToken;
private Locale locale; private Locale locale;
private boolean isBestPost;
private String subredditName; private String subredditName;
private int postType;
public Factory(Retrofit retrofit, String accessToken, Locale locale, boolean isBestPost) { public Factory(Retrofit retrofit, String accessToken, Locale locale, int postType) {
this.retrofit = retrofit; this.retrofit = retrofit;
this.accessToken = accessToken; this.accessToken = accessToken;
this.locale = locale; this.locale = locale;
this.isBestPost = isBestPost; this.postType = postType;
} }
public Factory(Retrofit retrofit, Locale locale, boolean isBestPost, String subredditName) { public Factory(Retrofit retrofit, Locale locale, String subredditName, int postType) {
this.retrofit = retrofit; this.retrofit = retrofit;
this.locale = locale; this.locale = locale;
this.isBestPost = isBestPost;
this.subredditName = subredditName; this.subredditName = subredditName;
this.postType = postType;
} }
@NonNull @NonNull
@Override @Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if(isBestPost) { if(postType == PostDataSource.TYPE_FRONT_PAGE) {
return (T) new PostViewModel(retrofit, accessToken, locale, isBestPost); return (T) new PostViewModel(retrofit, accessToken, locale, postType);
} else { } else {
return (T) new PostViewModel(retrofit, locale, isBestPost, subredditName); return (T) new PostViewModel(retrofit, locale, subredditName, postType);
} }
} }
} }

View File

@ -36,10 +36,13 @@ public interface RedditAPI {
Call<String> voteThing(@HeaderMap Map<String, String> headers, @FieldMap Map<String, String> params); Call<String> voteThing(@HeaderMap Map<String, String> headers, @FieldMap Map<String, String> params);
@GET("best?raw_json=1") @GET("best?raw_json=1")
Call<String> getBestPost(@Query("after") String lastItem, @HeaderMap Map<String, String> headers); Call<String> getBestPosts(@Query("after") String lastItem, @HeaderMap Map<String, String> headers);
@GET("r/{subredditName}.json?raw_json=1&limit=25") @GET("r/{subredditName}.json?raw_json=1&limit=25")
Call<String> getPost(@Path("subredditName") String subredditName, @Query("after") String lastItem); Call<String> getSubredditBestPosts(@Path("subredditName") String subredditName, @Query("after") String lastItem);
@GET("user/{userName}.json?raw_json=1&limit=25")
Call<String> getUserBestPosts(@Path("userName") String userName, @Query("after") String lastItem);
@GET("user/{username}/about.json?raw_json=1") @GET("user/{username}/about.json?raw_json=1")
Call<String> getUserData(@Path("username") String username); Call<String> getUserData(@Path("username") String username);

View File

@ -293,8 +293,8 @@ public class ViewSubredditDetailActivity extends AppCompatActivity {
if(savedInstanceState == null) { if(savedInstanceState == null) {
mFragment = new PostFragment(); mFragment = new PostFragment();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString(PostFragment.SUBREDDIT_NAME_KEY, subredditName); bundle.putString(PostFragment.NAME_KEY, subredditName);
bundle.putBoolean(PostFragment.IS_BEST_POST_KEY, false); bundle.putInt(PostFragment.POST_TYPE_KEY, PostDataSource.TYPE_SUBREDDIT);
mFragment.setArguments(bundle); mFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_view_subreddit_detail_activity, mFragment).commit(); getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_view_subreddit_detail_activity, mFragment).commit();
} else { } else {

View File

@ -13,6 +13,7 @@ import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar; import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar; import android.support.v7.widget.Toolbar;
import android.view.MenuItem; import android.view.MenuItem;
@ -49,6 +50,8 @@ public class ViewUserDetailActivity extends AppCompatActivity {
static final String EXTRA_USER_NAME_KEY = "EUNK"; static final String EXTRA_USER_NAME_KEY = "EUNK";
private static final String FRAGMENT_OUT_STATE_KEY = "FOSK";
@BindView(R.id.coordinator_layout_view_user_detail_activity) CoordinatorLayout coordinatorLayout; @BindView(R.id.coordinator_layout_view_user_detail_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.banner_image_view_view_user_detail_activity) ImageView bannerImageView; @BindView(R.id.banner_image_view_view_user_detail_activity) ImageView bannerImageView;
@BindView(R.id.icon_gif_image_view_view_user_detail_activity) GifImageView iconGifImageView; @BindView(R.id.icon_gif_image_view_view_user_detail_activity) GifImageView iconGifImageView;
@ -56,6 +59,7 @@ public class ViewUserDetailActivity extends AppCompatActivity {
@BindView(R.id.subscribe_user_chip_view_user_detail_activity) Chip subscribeUserChip; @BindView(R.id.subscribe_user_chip_view_user_detail_activity) Chip subscribeUserChip;
@BindView(R.id.karma_text_view_view_user_detail_activity) TextView karmaTextView; @BindView(R.id.karma_text_view_view_user_detail_activity) TextView karmaTextView;
private Fragment mFragment;
private SubscribedUserDao subscribedUserDao; private SubscribedUserDao subscribedUserDao;
private RequestManager glide; private RequestManager glide;
private UserViewModel userViewModel; private UserViewModel userViewModel;
@ -268,6 +272,18 @@ public class ViewUserDetailActivity extends AppCompatActivity {
makeSnackbar(R.string.cannot_fetch_user_info); makeSnackbar(R.string.cannot_fetch_user_info);
} }
}); });
if(savedInstanceState == null) {
mFragment = new PostFragment();
Bundle bundle = new Bundle();
bundle.putString(PostFragment.NAME_KEY, userName);
bundle.putInt(PostFragment.POST_TYPE_KEY, 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);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_view_user_detail_activity, mFragment).commit();
}
} }
@Override @Override