From 3fa625742862f55e50799ec346fa35e81aedcd20 Mon Sep 17 00:00:00 2001 From: Alex Ning Date: Wed, 29 Aug 2018 12:54:05 +0800 Subject: Use Retrofit to fetch posts. Delete PaginationRequestQueueSynchronizer because there is no need to pass request queue between PostFragment and PostPaginationScrollListener. Delete and rewrite some code. --- .../infinityforreddit/MainActivity.java | 11 +- .../PaginationRequestQueueSynchronizer.java | 7 - .../infinityforreddit/PaginationSynchronizer.java | 9 - .../infinityforreddit/PostFragment.java | 295 +++++++++------------ .../PostPaginationScrollListener.java | 210 +++++++-------- .../infinityforreddit/PostRecyclerViewAdapter.java | 6 +- .../infinityforreddit/RedditAPI.java | 6 + .../infinityforreddit/RedditUtils.java | 5 - .../ViewSubredditDetailActivity.java | 6 +- 9 files changed, 233 insertions(+), 322 deletions(-) delete mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/PaginationRequestQueueSynchronizer.java (limited to 'app/src/main') diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/MainActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/MainActivity.java index 181602e5..1ea0c809 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/MainActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/MainActivity.java @@ -5,7 +5,6 @@ import android.arch.lifecycle.ViewModelProviders; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; -import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; @@ -32,6 +31,8 @@ import de.hdodenhof.circleimageview.CircleImageView; public class MainActivity extends AppCompatActivity { + private static final String FRAGMENT_OUT_STATE_KEY = "FOSK"; + private String nameState = "NS"; private String profileImageUrlState = "PIUS"; private String bannerImageUrlState = "BIUS"; @@ -77,16 +78,12 @@ public class MainActivity extends AppCompatActivity { } else { if(savedInstanceState == null) { mFragment = new PostFragment(); - Uri uri = Uri.parse(RedditUtils.OAUTH_API_BASE_URI + RedditUtils.BEST_POST_SUFFIX) - .buildUpon().appendQueryParameter(RedditUtils.RAW_JSON_KEY, RedditUtils.RAW_JSON_VALUE) - .build(); Bundle bundle = new Bundle(); - bundle.putString(PostFragment.QUERY_POST_URL_KEY, uri.toString()); bundle.putBoolean(PostFragment.IS_BEST_POST_KEY, true); mFragment.setArguments(bundle); getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_content_main, mFragment).commit(); } else { - mFragment = getSupportFragmentManager().getFragment(savedInstanceState, "outStateFragment"); + mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE_KEY); getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_content_main, mFragment).commit(); } @@ -271,7 +268,7 @@ public class MainActivity extends AppCompatActivity { protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if(mFragment != null) { - getSupportFragmentManager().putFragment(outState, "outStateFragment", mFragment); + getSupportFragmentManager().putFragment(outState, FRAGMENT_OUT_STATE_KEY, mFragment); } outState.putString(nameState, mName); outState.putString(profileImageUrlState, mProfileImageUrl); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationRequestQueueSynchronizer.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationRequestQueueSynchronizer.java deleted file mode 100644 index bd81e4a3..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationRequestQueueSynchronizer.java +++ /dev/null @@ -1,7 +0,0 @@ -package ml.docilealligator.infinityforreddit; - -import com.android.volley.RequestQueue; - -interface PaginationRequestQueueSynchronizer { - void passQueue(RequestQueue q); -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationSynchronizer.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationSynchronizer.java index 38cc7bef..83fa6b10 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationSynchronizer.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationSynchronizer.java @@ -9,7 +9,6 @@ class PaginationSynchronizer implements Parcelable { private PaginationNotifier paginationNotifier; private PaginationRetryNotifier paginationRetryNotifier; private LastItemSynchronizer lastItemSynchronizer; - private PaginationRequestQueueSynchronizer paginationRequestQueueSynchronizer; PaginationSynchronizer() { loadingState = false; @@ -74,14 +73,6 @@ class PaginationSynchronizer implements Parcelable { return lastItemSynchronizer; } - public void setPaginationRequestQueueSynchronizer(PaginationRequestQueueSynchronizer paginationRequestQueueSynchronizer) { - this.paginationRequestQueueSynchronizer = paginationRequestQueueSynchronizer; - } - - public PaginationRequestQueueSynchronizer getPaginationRequestQueueSynchronizer() { - return paginationRequestQueueSynchronizer; - } - @Override public int describeContents() { return 0; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PostFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PostFragment.java index 585bd85f..dc262abe 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.content.ClipData; import android.content.ClipboardManager; import android.content.Context; -import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; @@ -20,16 +19,12 @@ import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; -import com.android.volley.AuthFailureError; -import com.android.volley.Request; -import com.android.volley.RequestQueue; -import com.android.volley.Response; -import com.android.volley.VolleyError; -import com.android.volley.toolbox.StringRequest; -import com.android.volley.toolbox.Volley; - import java.util.ArrayList; -import java.util.Map; + +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Retrofit; +import retrofit2.converter.scalars.ScalarsConverterFactory; /** @@ -37,7 +32,7 @@ import java.util.Map; */ public class PostFragment extends Fragment { - static final String QUERY_POST_URL_KEY = "QPUK"; + static final String SUBREDDIT_NAME_KEY = "SNK"; static final String IS_BEST_POST_KEY = "IBPK"; private CoordinatorLayout mCoordinatorLayout; @@ -50,16 +45,11 @@ public class PostFragment extends Fragment { private PostRecyclerViewAdapter mAdapter; private boolean mIsBestPost; - private String mQueryPostUrl; + private String mSubredditName; private String PostDataParcelableState = "BPDPS"; private String lastItemState = "LIS"; private String paginationSynchronizerState = "PSS"; - private RequestQueue mRequestQueue; - private RequestQueue mPaginationRequestQueue; - private RequestQueue mAcquireAccessTokenRequestQueue; - private RequestQueue mVoteThingRequestQueue; - public PostFragment() { // Required empty public constructor } @@ -71,20 +61,19 @@ public class PostFragment extends Fragment { if(savedInstanceState.containsKey(PostDataParcelableState)) { mPostData = savedInstanceState.getParcelableArrayList(PostDataParcelableState); mLastItem = savedInstanceState.getString(lastItemState); - mAdapter = new PostRecyclerViewAdapter(getActivity(), mPostData, mPaginationSynchronizer, mVoteThingRequestQueue); + mAdapter = new PostRecyclerViewAdapter(getActivity(), mPostData, mPaginationSynchronizer); mPostRecyclerView.setAdapter(mAdapter); mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener( getActivity(), mLinearLayoutManager, mAdapter, mLastItem, mPostData, - mPaginationSynchronizer, mAcquireAccessTokenRequestQueue, - mQueryPostUrl, mIsBestPost, + mPaginationSynchronizer, mSubredditName, mIsBestPost, mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(), getResources().getConfiguration().locale)); mProgressBar.setVisibility(View.GONE); } else { if(mIsBestPost) { - queryBestPost(1); + fetchBestPost(1); } else { - fetchPost(mQueryPostUrl, 1); + fetchPost(mSubredditName, 1); } } } @@ -94,22 +83,6 @@ public class PostFragment extends Fragment { public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); - if(mRequestQueue != null) { - mRequestQueue.cancelAll(this); - } - - if(mAcquireAccessTokenRequestQueue != null) { - mAcquireAccessTokenRequestQueue.cancelAll(RefreshAccessToken.class); - } - - if(mVoteThingRequestQueue != null) { - mVoteThingRequestQueue.cancelAll(VoteThing.class); - } - - if(mPaginationRequestQueue != null) { - mPaginationRequestQueue.cancelAll(PostPaginationScrollListener.class); - } - if(mPostData != null) { outState.putParcelableArrayList(PostDataParcelableState, mPostData); outState.putString(lastItemState, mLastItem); @@ -144,21 +117,19 @@ public class PostFragment extends Fragment { } });*/ - mRequestQueue = Volley.newRequestQueue(getActivity()); - mAcquireAccessTokenRequestQueue = Volley.newRequestQueue(getActivity()); - mVoteThingRequestQueue = Volley.newRequestQueue(getActivity()); - mIsBestPost = getArguments().getBoolean(IS_BEST_POST_KEY); - mQueryPostUrl = getArguments().getString(QUERY_POST_URL_KEY); + if(!mIsBestPost) { + mSubredditName = getArguments().getString(SUBREDDIT_NAME_KEY); + } if(savedInstanceState != null && savedInstanceState.getParcelable(paginationSynchronizerState) != null) { mPaginationSynchronizer = savedInstanceState.getParcelable(paginationSynchronizerState); } else { mPaginationSynchronizer = new PaginationSynchronizer(); if(mIsBestPost) { - queryBestPost(1); + fetchBestPost(1); } else { - fetchPost(mQueryPostUrl, 1); + fetchPost(mSubredditName, 1); } } @@ -170,18 +141,10 @@ public class PostFragment extends Fragment { }; mPaginationSynchronizer.setLastItemSynchronizer(lastItemSynchronizer); - PaginationRequestQueueSynchronizer paginationRequestQueueSynchronizer = new PaginationRequestQueueSynchronizer() { - @Override - public void passQueue(RequestQueue q) { - mPaginationRequestQueue = q; - } - }; - mPaginationSynchronizer.setPaginationRequestQueueSynchronizer(paginationRequestQueueSynchronizer); - return rootView; } - private void queryBestPost(final int refreshTime) { + private void fetchBestPost(final int refreshTime) { if(refreshTime < 0) { showErrorSnackbar(); return; @@ -189,71 +152,75 @@ public class PostFragment extends Fragment { mProgressBar.setVisibility(View.VISIBLE); - StringRequest postRequest = new StringRequest(Request.Method.GET, mQueryPostUrl, new Response.Listener() { + Retrofit retrofit = new Retrofit.Builder() + .baseUrl(RedditUtils.OAUTH_API_BASE_URI) + .addConverterFactory(ScalarsConverterFactory.create()) + .build(); + + RedditAPI api = retrofit.create(RedditAPI.class); + + String accessToken = getActivity().getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE) + .getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); + Call bestPost = api.getBestPost(mLastItem, RedditUtils.getOAuthHeader(accessToken)); + bestPost.enqueue(new Callback() { @Override - public void onResponse(String response) { + public void onResponse(Call call, retrofit2.Response response) { if(getActivity() != null) { - ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip = ClipData.newPlainText("response", response); - clipboard.setPrimaryClip(clip); - //new ParsePostDataAsyncTask(response, accessToken).execute(); - ParsePost.parsePost(response, new ArrayList(), - getResources().getConfiguration().locale, new ParsePost.ParsePostListener() { - @Override - public void onParsePostSuccess(ArrayList postData, String lastItem) { - mPostData = postData; - mLastItem = lastItem; - mAdapter = new PostRecyclerViewAdapter(getActivity(), postData, mPaginationSynchronizer, mVoteThingRequestQueue); - - mPostRecyclerView.setAdapter(mAdapter); - mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener( - getActivity(), mLinearLayoutManager, mAdapter, lastItem, postData, - mPaginationSynchronizer, mAcquireAccessTokenRequestQueue, - mQueryPostUrl, mIsBestPost, - mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(), - getResources().getConfiguration().locale)); - mProgressBar.setVisibility(View.GONE); - } - - @Override - public void onParsePostFail() { - Toast.makeText(getActivity(), "Error parsing data", Toast.LENGTH_SHORT).show(); - Log.i("Post fetch error", "Error parsing data"); - mProgressBar.setVisibility(View.GONE); - } - }); - } - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - if (error instanceof AuthFailureError) { - // Error indicating that there was an Authentication Failure while performing the request - // Access token expired - RefreshAccessToken.refreshAccessToken(getActivity(), - new RefreshAccessToken.RefreshAccessTokenListener() { - @Override - public void onRefreshAccessTokenSuccess() { - queryBestPost(refreshTime - 1); - } - - @Override - public void onRefreshAccessTokenFail() {} - }); - } else { - Log.i("Post fetch error", error.toString()); - showErrorSnackbar(); + + if(response.isSuccessful()) { + ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = ClipData.newPlainText("response", response.body()); + clipboard.setPrimaryClip(clip); + + ParsePost.parsePost(response.body(), new ArrayList(), + getResources().getConfiguration().locale, new ParsePost.ParsePostListener() { + @Override + public void onParsePostSuccess(ArrayList postData, String lastItem) { + mPostData = postData; + mLastItem = lastItem; + mAdapter = new PostRecyclerViewAdapter(getActivity(), postData, mPaginationSynchronizer); + + mPostRecyclerView.setAdapter(mAdapter); + mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener( + getActivity(), mLinearLayoutManager, mAdapter, lastItem, postData, + mPaginationSynchronizer, mSubredditName, mIsBestPost, + mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(), + getResources().getConfiguration().locale)); + mProgressBar.setVisibility(View.GONE); + } + + @Override + public void onParsePostFail() { + Toast.makeText(getActivity(), "Error parsing data", Toast.LENGTH_SHORT).show(); + Log.i("Post fetch error", "Error parsing data"); + mProgressBar.setVisibility(View.GONE); + } + }); + } else if(response.code() == 401) { + // Error indicating that there was an Authentication Failure while performing the request + // Access token expired + RefreshAccessToken.refreshAccessToken(getActivity(), + new RefreshAccessToken.RefreshAccessTokenListener() { + @Override + public void onRefreshAccessTokenSuccess() { + fetchBestPost(refreshTime - 1); + } + + @Override + public void onRefreshAccessTokenFail() {} + }); + } else { + Log.i("Post fetch error", response.message()); + showErrorSnackbar(); + } } } - }) { + @Override - public Map getHeaders() { - String accessToken = getActivity().getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE).getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); - return RedditUtils.getOAuthHeader(accessToken); + public void onFailure(Call call, Throwable t) { + showErrorSnackbar(); } - }; - postRequest.setTag(PostFragment.class); - mRequestQueue.add(postRequest); + }); } private void fetchPost(final String queryPostUrl, final int refreshTime) { @@ -264,69 +231,59 @@ public class PostFragment extends Fragment { mProgressBar.setVisibility(View.VISIBLE); - Uri uri = Uri.parse(RedditUtils.OAUTH_API_BASE_URI + RedditUtils.BEST_POST_SUFFIX) - .buildUpon().appendQueryParameter(RedditUtils.RAW_JSON_KEY, RedditUtils.RAW_JSON_VALUE) + Retrofit retrofit = new Retrofit.Builder() + .baseUrl(RedditUtils.API_BASE_URI) + .addConverterFactory(ScalarsConverterFactory.create()) .build(); - StringRequest postRequest = new StringRequest(Request.Method.GET, queryPostUrl, new Response.Listener() { + RedditAPI api = retrofit.create(RedditAPI.class); + Call getPost = api.getPost(mSubredditName, mLastItem); + getPost.enqueue(new Callback() { @Override - public void onResponse(String response) { + public void onResponse(Call call, retrofit2.Response response) { if(getActivity() != null) { - ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip = ClipData.newPlainText("response", response); - clipboard.setPrimaryClip(clip); - //new ParsePostDataAsyncTask(response, accessToken).execute(); - ParsePost.parsePost(response, new ArrayList(), - getResources().getConfiguration().locale, new ParsePost.ParsePostListener() { - @Override - public void onParsePostSuccess(ArrayList postData, String lastItem) { - mPostData = postData; - mLastItem = lastItem; - mAdapter = new PostRecyclerViewAdapter(getActivity(), postData, mPaginationSynchronizer, mVoteThingRequestQueue); - - mPostRecyclerView.setAdapter(mAdapter); - mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener( - getActivity(), mLinearLayoutManager, mAdapter, lastItem, postData, - mPaginationSynchronizer, mAcquireAccessTokenRequestQueue, - mQueryPostUrl, mIsBestPost, - mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(), - getResources().getConfiguration().locale)); - mProgressBar.setVisibility(View.GONE); - } - - @Override - public void onParsePostFail() { - Toast.makeText(getActivity(), "Error parsing data", Toast.LENGTH_SHORT).show(); - Log.i("Post fetch error", "Error parsing data"); - mProgressBar.setVisibility(View.GONE); - } - }); + Log.i("response_code", Integer.toString(response.code())); + if(response.isSuccessful()) { + ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = ClipData.newPlainText("response", response.body()); + clipboard.setPrimaryClip(clip); + + ParsePost.parsePost(response.body(), new ArrayList(), + getResources().getConfiguration().locale, new ParsePost.ParsePostListener() { + @Override + public void onParsePostSuccess(ArrayList postData, String lastItem) { + mPostData = postData; + mLastItem = lastItem; + mAdapter = new PostRecyclerViewAdapter(getActivity(), postData, mPaginationSynchronizer); + + mPostRecyclerView.setAdapter(mAdapter); + mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener( + getActivity(), mLinearLayoutManager, mAdapter, lastItem, postData, + mPaginationSynchronizer, mSubredditName, mIsBestPost, + mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(), + getResources().getConfiguration().locale)); + mProgressBar.setVisibility(View.GONE); + } + + @Override + public void onParsePostFail() { + Toast.makeText(getActivity(), "Error parsing data", Toast.LENGTH_SHORT).show(); + Log.i("Post fetch error", "Error parsing data"); + mProgressBar.setVisibility(View.GONE); + } + }); + } else { + Log.i("Post fetch error", response.message()); + showErrorSnackbar(); + } } } - }, new Response.ErrorListener() { + @Override - public void onErrorResponse(VolleyError error) { - if (error instanceof AuthFailureError) { - // Error indicating that there was an Authentication Failure while performing the request - // Access token expired - RefreshAccessToken.refreshAccessToken(getActivity(), - new RefreshAccessToken.RefreshAccessTokenListener() { - @Override - public void onRefreshAccessTokenSuccess() { - fetchPost(queryPostUrl, refreshTime - 1); - } - - @Override - public void onRefreshAccessTokenFail() {} - }); - } else { - Log.i("Post fetch error", error.toString()); - showErrorSnackbar(); - } + public void onFailure(Call call, Throwable t) { + showErrorSnackbar(); } }); - postRequest.setTag(PostFragment.class); - mRequestQueue.add(postRequest); } private void showErrorSnackbar() { @@ -336,9 +293,9 @@ public class PostFragment extends Fragment { @Override public void onClick(View view) { if(mIsBestPost) { - queryBestPost(1); + fetchBestPost(1); } else { - fetchPost(mQueryPostUrl, 1); + fetchPost(mSubredditName, 1); } } }); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PostPaginationScrollListener.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PostPaginationScrollListener.java index 57712c6c..39d26a5d 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PostPaginationScrollListener.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/PostPaginationScrollListener.java @@ -3,24 +3,19 @@ package ml.docilealligator.infinityforreddit; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; -import android.net.Uri; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.Toast; -import com.android.volley.AuthFailureError; -import com.android.volley.Request; -import com.android.volley.RequestQueue; -import com.android.volley.Response; -import com.android.volley.VolleyError; -import com.android.volley.toolbox.StringRequest; -import com.android.volley.toolbox.Volley; - import java.util.ArrayList; import java.util.Locale; -import java.util.Map; + +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Retrofit; +import retrofit2.converter.scalars.ScalarsConverterFactory; /** * Created by alex on 3/12/18. @@ -34,21 +29,18 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener { private PaginationSynchronizer mPaginationSynchronizer; private PaginationRetryNotifier mPaginationRetryNotifier; private LastItemSynchronizer mLastItemSynchronizer; - private PaginationRequestQueueSynchronizer mPaginationRequestQueueSynchronizer; - private String mQueryPostUrl; + private String mSubredditName; private boolean isBestPost; private boolean isLoading; private boolean loadSuccess; private Locale locale; private String mLastItem; - private RequestQueue mRequestQueue; - private RequestQueue mAcquireAccessTokenRequestQueue; PostPaginationScrollListener(Context context, LinearLayoutManager layoutManager, PostRecyclerViewAdapter adapter, String lastItem, ArrayList postData, PaginationSynchronizer paginationSynchronizer, - RequestQueue acquireAccessTokenRequestQueue, final String queryPostUrl, - final boolean isBestPost, boolean isLoading, boolean loadSuccess, Locale locale) { + final String subredditName, final boolean isBestPost, boolean isLoading, + boolean loadSuccess, Locale locale) { if(context != null) { this.mContext = context; this.mLayoutManager = layoutManager; @@ -56,29 +48,24 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener { this.mLastItem = lastItem; this.mPostData = postData; this.mPaginationSynchronizer = paginationSynchronizer; - this.mAcquireAccessTokenRequestQueue = acquireAccessTokenRequestQueue; - this.mQueryPostUrl = queryPostUrl; + this.mSubredditName = subredditName; this.isBestPost = isBestPost; this.isLoading = isLoading; this.loadSuccess = loadSuccess; this.locale = locale; - mRequestQueue = Volley.newRequestQueue(mContext); - mAcquireAccessTokenRequestQueue = Volley.newRequestQueue(mContext); mPaginationRetryNotifier = new PaginationRetryNotifier() { @Override public void retry() { if(isBestPost) { - fetchBestPost(queryPostUrl, 1); + fetchBestPost(1); } else { - fetchPost(queryPostUrl, 1); + fetchPost(subredditName, 1); } } }; mPaginationSynchronizer.setPaginationRetryNotifier(mPaginationRetryNotifier); mLastItemSynchronizer = mPaginationSynchronizer.getLastItemSynchronizer(); - mPaginationRequestQueueSynchronizer = mPaginationSynchronizer.getPaginationRequestQueueSynchronizer(); - mPaginationRequestQueueSynchronizer.passQueue(mRequestQueue); } } @@ -92,16 +79,16 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener { if((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) { if(isBestPost) { - fetchBestPost(mQueryPostUrl, 1); + fetchBestPost(1); } else { - fetchPost(mQueryPostUrl, 1); + fetchPost(mSubredditName, 1); } } } } - private void fetchBestPost(final String queryPostUrl, final int refreshTime) { + private void fetchBestPost(final int refreshTime) { if(refreshTime < 0) { loadFailed(); return; @@ -111,46 +98,50 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener { loadSuccess = false; mPaginationSynchronizer.setLoading(true); - Uri uri = Uri.parse(queryPostUrl) - .buildUpon().appendQueryParameter(RedditUtils.AFTER_KEY, mLastItem).build(); + Retrofit retrofit = new Retrofit.Builder() + .baseUrl(RedditUtils.OAUTH_API_BASE_URI) + .addConverterFactory(ScalarsConverterFactory.create()) + .build(); - StringRequest bestPostRequest = new StringRequest(Request.Method.GET, uri.toString(), new Response.Listener() { - @Override - public void onResponse(String response) { - ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip = ClipData.newPlainText("response", response); - clipboard.setPrimaryClip(clip); - ParsePost.parsePost(response, mPostData, locale, new ParsePost.ParsePostListener() { - @Override - public void onParsePostSuccess(ArrayList bestPostData, String lastItem) { - mAdapter.notifyDataSetChanged(); - mLastItem = lastItem; - mLastItemSynchronizer.lastItemChanged(mLastItem); - - isLoading = false; - loadSuccess = true; - mPaginationSynchronizer.setLoading(false); - mPaginationSynchronizer.setLoadingState(true); - } + RedditAPI api = retrofit.create(RedditAPI.class); - @Override - public void onParsePostFail() { - Toast.makeText(mContext, "Error parsing data", Toast.LENGTH_SHORT).show(); - Log.i("Best post", "Error parsing data"); - loadFailed(); - } - }); - } - }, new Response.ErrorListener() { + String accessToken = mContext.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE) + .getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); + Call bestPost = api.getBestPost(mLastItem, RedditUtils.getOAuthHeader(accessToken)); + bestPost.enqueue(new Callback() { @Override - public void onErrorResponse(VolleyError error) { - if (error instanceof AuthFailureError) { + public void onResponse(Call call, retrofit2.Response response) { + if(response.isSuccessful()) { + ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = ClipData.newPlainText("response", response.body()); + clipboard.setPrimaryClip(clip); + ParsePost.parsePost(response.body(), mPostData, locale, new ParsePost.ParsePostListener() { + @Override + public void onParsePostSuccess(ArrayList bestPostData, String lastItem) { + mAdapter.notifyDataSetChanged(); + mLastItem = lastItem; + mLastItemSynchronizer.lastItemChanged(mLastItem); + + isLoading = false; + loadSuccess = true; + mPaginationSynchronizer.setLoading(false); + mPaginationSynchronizer.setLoadingState(true); + } + + @Override + public void onParsePostFail() { + Toast.makeText(mContext, "Error parsing data", Toast.LENGTH_SHORT).show(); + Log.i("Best post", "Error parsing data"); + loadFailed(); + } + }); + } else if(response.code() == 401) { //Access token expired RefreshAccessToken.refreshAccessToken(mContext, new RefreshAccessToken.RefreshAccessTokenListener() { @Override public void onRefreshAccessTokenSuccess() { - fetchBestPost(queryPostUrl, refreshTime - 1); + fetchBestPost(refreshTime - 1); } @Override @@ -159,22 +150,19 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener { }); } else { Toast.makeText(mContext, "Error getting best post", Toast.LENGTH_SHORT).show(); - Log.i("best post", error.toString()); + Log.i("best post", response.message()); loadFailed(); } } - }) { + @Override - public Map getHeaders() { - String accessToken = mContext.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE).getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); - return RedditUtils.getOAuthHeader(accessToken); + public void onFailure(Call call, Throwable t) { + loadFailed(); } - }; - bestPostRequest.setTag(PostPaginationScrollListener.class); - mRequestQueue.add(bestPostRequest); + }); } - private void fetchPost(final String queryPostUrl, final int refreshTime) { + private void fetchPost(final String subredditName, final int refreshTime) { if(refreshTime < 0) { loadFailed(); return; @@ -184,61 +172,53 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener { loadSuccess = false; mPaginationSynchronizer.setLoading(true); - Uri uri = Uri.parse(queryPostUrl) - .buildUpon().appendQueryParameter(RedditUtils.AFTER_KEY, mLastItem).build(); + Retrofit retrofit = new Retrofit.Builder() + .baseUrl(RedditUtils.API_BASE_URI) + .addConverterFactory(ScalarsConverterFactory.create()) + .build(); - StringRequest bestPostRequest = new StringRequest(Request.Method.GET, uri.toString(), new Response.Listener() { + RedditAPI api = retrofit.create(RedditAPI.class); + Call getPost = api.getPost(subredditName, mLastItem); + getPost.enqueue(new Callback() { @Override - public void onResponse(String response) { - ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip = ClipData.newPlainText("response", response); - clipboard.setPrimaryClip(clip); - ParsePost.parsePost(response, mPostData, locale, new ParsePost.ParsePostListener() { - @Override - public void onParsePostSuccess(ArrayList bestPostData, String lastItem) { - mAdapter.notifyDataSetChanged(); - mLastItem = lastItem; - mLastItemSynchronizer.lastItemChanged(mLastItem); - - isLoading = false; - loadSuccess = true; - mPaginationSynchronizer.setLoading(false); - mPaginationSynchronizer.setLoadingState(true); - } - - @Override - public void onParsePostFail() { - Toast.makeText(mContext, "Error parsing data", Toast.LENGTH_SHORT).show(); - Log.i("Best post", "Error parsing data"); - loadFailed(); - } - }); - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - if (error instanceof AuthFailureError) { - //Access token expired - RefreshAccessToken.refreshAccessToken(mContext, - new RefreshAccessToken.RefreshAccessTokenListener() { - @Override - public void onRefreshAccessTokenSuccess() { - fetchPost(queryPostUrl, refreshTime - 1); - } - - @Override - public void onRefreshAccessTokenFail() { - } - }); + public void onResponse(Call call, retrofit2.Response response) { + if(response.isSuccessful()) { + ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = ClipData.newPlainText("response", response.body()); + clipboard.setPrimaryClip(clip); + ParsePost.parsePost(response.body(), mPostData, locale, new ParsePost.ParsePostListener() { + @Override + public void onParsePostSuccess(ArrayList bestPostData, String lastItem) { + mAdapter.notifyDataSetChanged(); + mLastItem = lastItem; + mLastItemSynchronizer.lastItemChanged(mLastItem); + + isLoading = false; + loadSuccess = true; + mPaginationSynchronizer.setLoading(false); + mPaginationSynchronizer.setLoadingState(true); + } + + @Override + public void onParsePostFail() { + Toast.makeText(mContext, "Error parsing data", Toast.LENGTH_SHORT).show(); + Log.i("Best post", "Error parsing data"); + loadFailed(); + } + }); } else { Toast.makeText(mContext, "Error getting best post", Toast.LENGTH_SHORT).show(); - Log.i("best post", error.toString()); + Log.i("best post", response.message()); loadFailed(); } } + + @Override + public void onFailure(Call call, Throwable t) { + Toast.makeText(mContext, "Error getting best post", Toast.LENGTH_SHORT).show(); + loadFailed(); + } }); - bestPostRequest.setTag(PostPaginationScrollListener.class); - mRequestQueue.add(bestPostRequest); } private void loadFailed() { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java index e1efc0e6..f0021f33 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java @@ -23,7 +23,6 @@ import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; -import com.android.volley.RequestQueue; import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; import com.bumptech.glide.load.DataSource; @@ -43,7 +42,6 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter mPostData; private Context mContext; private PaginationSynchronizer mPaginationSynchronizer; - private RequestQueue mVoteThingRequestQueue; private RequestManager glide; private SubredditDao subredditDao; private boolean isLoadingMorePostSuccess; @@ -53,13 +51,11 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter postData, PaginationSynchronizer paginationSynchronizer, - RequestQueue voteThingRequestQueue) { + PostRecyclerViewAdapter(Context context, ArrayList postData, PaginationSynchronizer paginationSynchronizer) { if(context != null) { mContext = context; mPostData = postData; mPaginationSynchronizer = paginationSynchronizer; - mVoteThingRequestQueue = voteThingRequestQueue; isLoadingMorePostSuccess = true; canStartActivity = true; glide = Glide.with(mContext); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditAPI.java b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditAPI.java index a0985428..20df642c 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditAPI.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditAPI.java @@ -31,4 +31,10 @@ public interface RedditAPI { @FormUrlEncoded @POST("api/vote") Call voteThing(@HeaderMap Map headers, @FieldMap Map params); + + @GET("best?raw_json=1") + Call getBestPost(@Query("after") String lastItem, @HeaderMap Map headers); + + @GET("r/{subredditName}.json?raw_json=1") + Call getPost(@Path("subredditName") String subredditName, @Query("after") String lastItem); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditUtils.java b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditUtils.java index f6833ee8..8cb98c4c 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditUtils.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditUtils.java @@ -13,9 +13,6 @@ class RedditUtils { static final String OAUTH_URL ="https://www.reddit.com/api/v1/authorize.compact"; static final String OAUTH_API_BASE_URI = "https://oauth.reddit.com"; static final String API_BASE_URI = "https://www.reddit.com"; - static final String RAW_JSON_KEY ="raw_json"; - static final String RAW_JSON_VALUE = "1"; - static final String BEST_POST_SUFFIX = "/best"; static final String CLIENT_ID_KEY = "client_id"; static final String CLIENT_ID = ""; @@ -49,8 +46,6 @@ class RedditUtils { static final String DIR_DOWNVOTE = "-1"; static final String RANK = "10"; - static final String AFTER_KEY = "after"; - static Map getHttpBasicAuthHeader() { Map params = new HashMap<>(); String credentials = String.format("%s:%s", RedditUtils.CLIENT_ID, ""); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java index f169ad8b..d754b5af 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java @@ -3,7 +3,6 @@ package ml.docilealligator.infinityforreddit; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; -import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; @@ -165,11 +164,8 @@ public class ViewSubredditDetailActivity extends AppCompatActivity { if(savedInstanceState == null) { mFragment = new PostFragment(); - Uri uri = Uri.parse(RedditUtils.getQuerySubredditPostUrl(subredditName)) - .buildUpon().appendQueryParameter(RedditUtils.RAW_JSON_KEY, RedditUtils.RAW_JSON_VALUE) - .build(); Bundle bundle = new Bundle(); - bundle.putString(PostFragment.QUERY_POST_URL_KEY, uri.toString()); + bundle.putString(PostFragment.SUBREDDIT_NAME_KEY, subredditName); bundle.putBoolean(PostFragment.IS_BEST_POST_KEY, false); mFragment.setArguments(bundle); getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_view_subreddit_detail_activity, mFragment).commit(); -- cgit v1.2.3