Use Dagger 2 to inject the Retrofit singleton to classes. Minor bugs fixed.

This commit is contained in:
Alex Ning 2018-10-12 23:52:23 +08:00
parent 11ac14a3f1
commit 8b52810d7c
23 changed files with 238 additions and 134 deletions

View File

@ -33,9 +33,10 @@
</option>
<option name="values">
<map>
<entry key="assetSourceType" value="FILE" />
<entry key="color" value="ffffff" />
<entry key="outputName" value="ic_error_outline_white_24dp" />
<entry key="sourceFile" value="$USER_HOME$" />
<entry key="outputName" value="ic_pin_outline" />
<entry key="sourceFile" value="$USER_HOME$/Downloads/if_pin-outline_216358.svg" />
</map>
</option>
</PersistentState>

Binary file not shown.

View File

@ -62,4 +62,7 @@ dependencies {
implementation 'com.muditsen.multilevelrecyclerview:multilevelview:1.0.0'
implementation 'com.google.dagger:dagger:2.17'
annotationProcessor 'com.google.dagger:dagger-compiler:2.17'
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}

View File

@ -12,6 +12,7 @@
<application
android:allowBackup="true"
android:name=".Infinity"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"

View File

@ -23,19 +23,25 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import retrofit2.Retrofit;
class CommentMultiLevelRecyclerViewAdapter extends MultiLevelAdapter {
private Context mContext;
private Retrofit mRetrofit;
private Retrofit mOauthRetrofit;
private ArrayList<CommentData> mCommentData;
private MultiLevelRecyclerView mMultiLevelRecyclerView;
private String subredditNamePrefixed;
private String article;
private Locale locale;
CommentMultiLevelRecyclerViewAdapter(Context context, ArrayList<CommentData> commentData,
CommentMultiLevelRecyclerViewAdapter(Context context, Retrofit retrofit, Retrofit oauthRetrofit, ArrayList<CommentData> commentData,
MultiLevelRecyclerView multiLevelRecyclerView,
String subredditNamePrefixed, String article, Locale locale) {
super(commentData);
mContext = context;
mRetrofit = retrofit;
mOauthRetrofit = oauthRetrofit;
mCommentData = commentData;
mMultiLevelRecyclerView = multiLevelRecyclerView;
this.subredditNamePrefixed = subredditNamePrefixed;
@ -71,7 +77,7 @@ class CommentMultiLevelRecyclerViewAdapter extends MultiLevelAdapter {
setExpandButton(((CommentViewHolder) holder).expandButton, commentItem.isExpanded());
} else {
((CommentViewHolder) holder).loadMoreCommentsProgressBar.setVisibility(View.VISIBLE);
FetchComment.fetchComment(subredditNamePrefixed, article, commentItem.getId(),
FetchComment.fetchComment(mRetrofit, subredditNamePrefixed, article, commentItem.getId(),
new FetchComment.FetchCommentListener() {
@Override
public void onFetchCommentSuccess(String response) {
@ -130,7 +136,7 @@ class CommentMultiLevelRecyclerViewAdapter extends MultiLevelAdapter {
((CommentViewHolder) holder).scoreTextView.setText(Integer.toString(commentItem.getScore() + 1));
}
VoteThing.voteThing(mContext, new VoteThing.VoteThingListener() {
VoteThing.voteThing(mContext, mOauthRetrofit, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position) {
commentItem.setVoteType(1);
@ -154,7 +160,7 @@ class CommentMultiLevelRecyclerViewAdapter extends MultiLevelAdapter {
((CommentViewHolder) holder).upvoteButton.clearColorFilter();
((CommentViewHolder) holder).scoreTextView.setText(Integer.toString(commentItem.getScore() - 1));
VoteThing.voteThing(mContext, new VoteThing.VoteThingListener() {
VoteThing.voteThing(mContext, mOauthRetrofit, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position) {
commentItem.setVoteType(0);
@ -189,7 +195,7 @@ class CommentMultiLevelRecyclerViewAdapter extends MultiLevelAdapter {
((CommentViewHolder) holder).scoreTextView.setText(Integer.toString(commentItem.getScore() - 1));
}
VoteThing.voteThing(mContext, new VoteThing.VoteThingListener() {
VoteThing.voteThing(mContext, mOauthRetrofit, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position) {
commentItem.setVoteType(-1);
@ -213,7 +219,7 @@ class CommentMultiLevelRecyclerViewAdapter extends MultiLevelAdapter {
((CommentViewHolder) holder).downvoteButton.clearColorFilter();
((CommentViewHolder) holder).scoreTextView.setText(Integer.toString(commentItem.getScore() + 1));
VoteThing.voteThing(mContext, new VoteThing.VoteThingListener() {
VoteThing.voteThing(mContext, mOauthRetrofit, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position) {
commentItem.setVoteType(0);

View File

@ -7,7 +7,6 @@ import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
class FetchComment {
interface FetchCommentListener {
@ -15,13 +14,8 @@ class FetchComment {
void onFetchCommentFail();
}
static void fetchComment(String subredditNamePrefixed, String article, String comment,
static void fetchComment(Retrofit retrofit, String subredditNamePrefixed, String article, String comment,
final FetchCommentListener fetchCommentListener) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditUtils.API_BASE_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> comments = api.getComments(subredditNamePrefixed, article, comment);

View File

@ -7,7 +7,6 @@ import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
class FetchSubredditData {
interface FetchSubredditDataListener {
@ -15,12 +14,7 @@ class FetchSubredditData {
void onFetchSubredditDataFail();
}
static void fetchSubredditData(String subredditName, final FetchSubredditDataListener fetchSubredditDataListener) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditUtils.API_BASE_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
static void fetchSubredditData(Retrofit retrofit, String subredditName, final FetchSubredditDataListener fetchSubredditDataListener) {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> subredditData = api.getSubredditData(subredditName);

View File

@ -10,7 +10,6 @@ import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
class FetchSubscribedThing {
interface FetchSubscribedThingListener {
@ -20,7 +19,7 @@ class FetchSubscribedThing {
void onFetchSubscribedThingFail();
}
static void fetchSubscribedThing(final Context context, final String lastItem,
static void fetchSubscribedThing(final Context context, final Retrofit retrofit, final String lastItem,
final ArrayList<SubscribedSubredditData> subscribedSubredditData,
final ArrayList<SubscribedUserData> subscribedUserData,
final ArrayList<SubredditData> subredditData,
@ -30,11 +29,6 @@ class FetchSubscribedThing {
return;
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditUtils.OAUTH_API_BASE_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
RedditAPI api = retrofit.create(RedditAPI.class);
String accessToken = context.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE)
@ -58,7 +52,7 @@ class FetchSubscribedThing {
fetchSubscribedThingListener.onFetchSubscribedThingSuccess(
subscribedSubredditData, subscribedUserData, subredditData);
} else {
fetchSubscribedThing(context, lastItem, subscribedSubredditData,
fetchSubscribedThing(context, retrofit, lastItem, subscribedSubredditData,
subscribedUserData, subredditData,
fetchSubscribedThingListener, refreshTime);
}
@ -73,7 +67,7 @@ class FetchSubscribedThing {
RefreshAccessToken.refreshAccessToken(context, new RefreshAccessToken.RefreshAccessTokenListener() {
@Override
public void onRefreshAccessTokenSuccess() {
fetchSubscribedThing(context, lastItem, subscribedSubredditData,
fetchSubscribedThing(context, retrofit, lastItem, subscribedSubredditData,
subscribedUserData, subredditData, fetchSubscribedThingListener, refreshTime - 1);
}

View File

@ -7,25 +7,20 @@ import android.util.Log;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
class FetchUserInfo {
interface FetchUserInfoListener {
void onFetchUserInfoSuccess(String response);
void onFetchUserInfoFail();
}
static void fetchUserInfo(final Context context, final FetchUserInfoListener fetchUserInfoListener, final int refreshTime) {
static void fetchUserInfo(final Retrofit retrofit, final Context context, final FetchUserInfoListener fetchUserInfoListener, final int refreshTime) {
if(refreshTime < 0) {
fetchUserInfoListener.onFetchUserInfoFail();
return;
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditUtils.OAUTH_API_BASE_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
RedditAPI api = retrofit.create(RedditAPI.class);
String accessToken = context.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE)
@ -40,7 +35,7 @@ class FetchUserInfo {
RefreshAccessToken.refreshAccessToken(context, new RefreshAccessToken.RefreshAccessTokenListener() {
@Override
public void onRefreshAccessTokenSuccess() {
fetchUserInfo(context, fetchUserInfoListener, refreshTime - 1);
fetchUserInfo(retrofit, context, fetchUserInfoListener, refreshTime - 1);
}
@Override

View File

@ -0,0 +1,18 @@
package ml.docilealligator.infinityforreddit;
import android.app.Application;
public class Infinity extends Application {
private NetworkComponent mNetworkComponent;
@Override
public void onCreate() {
super.onCreate();
mNetworkComponent = DaggerNetworkComponent.create();
}
public NetworkComponent getmNetworkComponent() {
return mNetworkComponent;
}
}

View File

@ -29,7 +29,11 @@ import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
@ -61,10 +65,17 @@ public class MainActivity extends AppCompatActivity {
private SubscribedSubredditViewModel mSubscribedSubredditViewModel;
private SubscribedUserViewModel mSubscribedUserViewModel;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((Infinity) getApplication()).getmNetworkComponent().inject(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
@ -180,7 +191,7 @@ public class MainActivity extends AppCompatActivity {
private void loadUserData(Bundle savedInstanceState) {
if (savedInstanceState == null) {
if (!mFetchUserInfoSuccess) {
FetchUserInfo.fetchUserInfo(this, new FetchUserInfo.FetchUserInfoListener() {
FetchUserInfo.fetchUserInfo(mOauthRetrofit, this, new FetchUserInfo.FetchUserInfoListener() {
@Override
public void onFetchUserInfoSuccess(String response) {
ParseUserInfo.parseUserInfo(response, new ParseUserInfo.ParseUserInfoListener() {
@ -225,7 +236,7 @@ public class MainActivity extends AppCompatActivity {
}
if (!mInsertSuccess) {
FetchSubscribedThing.fetchSubscribedThing(this, null,
FetchSubscribedThing.fetchSubscribedThing(this, mOauthRetrofit, null,
new ArrayList<SubscribedSubredditData>(), new ArrayList<SubscribedUserData>(),
new ArrayList<SubredditData>(),
new FetchSubscribedThing.FetchSubscribedThingListener() {

View File

@ -1,8 +0,0 @@
package ml.docilealligator.infinityforreddit;
import dagger.Component;
@Component(modules = NetworkModule.class)
interface Network {
}

View File

@ -0,0 +1,14 @@
package ml.docilealligator.infinityforreddit;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = NetworkModule.class)
interface NetworkComponent {
void inject(MainActivity mainActivity);
void inject(PostFragment postFragment);
void inject(ViewPostDetailActivity viewPostDetailActivity);
void inject(ViewSubredditDetailActivity viewSubredditDetailActivity);
}

View File

@ -1,15 +1,17 @@
package ml.docilealligator.infinityforreddit;
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
@Module
class NetworkModule {
@Provides
@Provides @Named("oauth")
@Singleton
Retrofit provideOauthRetrofit() {
return new Retrofit.Builder()
@ -18,7 +20,7 @@ class NetworkModule {
.build();
}
@Provides
@Provides @Named("no_oauth")
@Singleton
Retrofit provideRetrofit() {
return new Retrofit.Builder()
@ -26,4 +28,12 @@ class NetworkModule {
.addConverterFactory(ScalarsConverterFactory.create())
.build();
}
@Provides
@Singleton
OkHttpClient provideOkHttpClient() {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(new OkHttpInterceptor());
return okHttpClient;
}
}

View File

@ -0,0 +1,48 @@
package ml.docilealligator.infinityforreddit;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Response;
class OkHttpInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
/*Request request = chain.request();
//Build new request
Request.Builder builder = request.newBuilder();
builder.header("Accept", "application/json"); //if necessary, say to consume JSON
String token = settings.getAccessToken(); //save token of this request for future
setAuthHeader(builder, token); //write current token to request
request = builder.build(); //overwrite old request
Response response = chain.proceed(request); //perform request, here original request will be executed
if (response.code() == 401) { //if unauthorized
synchronized (this) { //perform all 401 in sync blocks, to avoid multiply token updates
String currentToken = settings.getAccessToken(); //get currently stored token
if(currentToken != null && currentToken.equals(token)) { //compare current token with token that was stored before, if it was not updated - do update
int code = refreshToken() / 100; //refresh token
if(code != 2) { //if refresh token failed for some reason
if(code == 4) //only if response is 400, 500 might mean that token was not updated
logout(); //go to login screen
return response; //if token refresh failed - show error to user
}
}
if(settings.getAccessToken() != null) { //retry requires new auth token,
setAuthHeader(builder, settings.getAccessToken()); //set auth token to updated
request = builder.build();
return chain.proceed(request); //repeat request with new token
}
}
}
return response;*/
return null;
}
}

View File

@ -23,10 +23,12 @@ import com.bumptech.glide.Glide;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.inject.Named;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
/**
@ -56,6 +58,15 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private boolean mIsBestPost;
private String mSubredditName;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
public PostFragment() {
// Required empty public constructor
}
@ -84,6 +95,9 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_post, container, false);
((Infinity) getActivity().getApplication()).getmNetworkComponent().inject(this);
mCoordinatorLayout = rootView.findViewById(R.id.coordinator_layout_post_fragment);
mPostRecyclerView = rootView.findViewById(R.id.recycler_view_post_fragment);
mLinearLayoutManager = new LinearLayoutManager(getActivity());
@ -127,14 +141,24 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
});
mPaginationSynchronizer.setLoadSuccess(savedInstanceState.getBoolean(LOAD_SUCCESS_STATE));
mPaginationSynchronizer.setLoadingState(savedInstanceState.getBoolean(LOADING_STATE_STATE));
PostRecyclerViewAdapter adapter = new PostRecyclerViewAdapter(getActivity(), mPostData, mPaginationSynchronizer, mIsBestPost);
PostRecyclerViewAdapter adapter = new PostRecyclerViewAdapter(getActivity(), mOauthRetrofit,
mPostData, mPaginationSynchronizer, mIsBestPost);
mPostRecyclerView.setAdapter(adapter);
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mLinearLayoutManager, adapter, mLastItem, mPostData,
mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(),
getResources().getConfiguration().locale));
mProgressBar.setVisibility(View.GONE);
if(mIsBestPost) {
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mOauthRetrofit, mLinearLayoutManager, adapter, mLastItem, mPostData,
mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(),
getResources().getConfiguration().locale));
mProgressBar.setVisibility(View.GONE);
} else {
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mRetrofit, mLinearLayoutManager, adapter, mLastItem, mPostData,
mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(),
getResources().getConfiguration().locale));
mProgressBar.setVisibility(View.GONE);
}
} else {
mPaginationSynchronizer = new PaginationSynchronizer(new LastItemSynchronizer() {
@Override
@ -157,16 +181,16 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
showErrorView();
return;
}
Log.i("fetch best post", "start" + refreshTime);
mFetchPostErrorLinearLayout.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
Retrofit retrofit = new Retrofit.Builder()
/*Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditUtils.OAUTH_API_BASE_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
.build();*/
RedditAPI api = retrofit.create(RedditAPI.class);
RedditAPI api = mOauthRetrofit.create(RedditAPI.class);
String accessToken = getActivity().getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE)
.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, "");
@ -176,6 +200,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if(getActivity() != null) {
if(response.isSuccessful()) {
Log.i("response", "success");
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("response", response.body());
clipboard.setPrimaryClip(clip);
@ -187,11 +212,11 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
if(isAdded() && getActivity() != null) {
mPostData = postData;
mLastItem = lastItem;
PostRecyclerViewAdapter adapter = new PostRecyclerViewAdapter(getActivity(), postData, mPaginationSynchronizer, mIsBestPost);
PostRecyclerViewAdapter adapter = new PostRecyclerViewAdapter(getActivity(), mOauthRetrofit, postData, mPaginationSynchronizer, mIsBestPost);
mPostRecyclerView.setAdapter(adapter);
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mLinearLayoutManager, adapter, lastItem, postData,
getActivity(), mOauthRetrofit, mLinearLayoutManager, adapter, lastItem, postData,
mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(),
getResources().getConfiguration().locale));
@ -236,12 +261,12 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
mFetchPostErrorLinearLayout.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
Retrofit retrofit = new Retrofit.Builder()
/*Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditUtils.API_BASE_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
.build();*/
RedditAPI api = retrofit.create(RedditAPI.class);
RedditAPI api = mRetrofit.create(RedditAPI.class);
Call<String> getPost = api.getPost(mSubredditName, mLastItem);
getPost.enqueue(new Callback<String>() {
@Override
@ -259,11 +284,11 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
if(isAdded() && getActivity() != null) {
mPostData = postData;
mLastItem = lastItem;
PostRecyclerViewAdapter adapter = new PostRecyclerViewAdapter(getActivity(), postData, mPaginationSynchronizer, mIsBestPost);
PostRecyclerViewAdapter adapter = new PostRecyclerViewAdapter(getActivity(), mRetrofit, postData, mPaginationSynchronizer, mIsBestPost);
mPostRecyclerView.setAdapter(adapter);
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mLinearLayoutManager, adapter, lastItem, postData,
getActivity(), mRetrofit, mLinearLayoutManager, adapter, lastItem, postData,
mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(),
getResources().getConfiguration().locale));

View File

@ -15,7 +15,6 @@ import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
/**
* Created by alex on 3/12/18.
@ -23,6 +22,7 @@ import retrofit2.converter.scalars.ScalarsConverterFactory;
class PostPaginationScrollListener extends RecyclerView.OnScrollListener {
private Context mContext;
private Retrofit mRetrofit;
private LinearLayoutManager mLayoutManager;
private PostRecyclerViewAdapter mAdapter;
private ArrayList<PostData> mPostData;
@ -35,12 +35,13 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener {
private Locale locale;
private String mLastItem;
PostPaginationScrollListener(Context context, LinearLayoutManager layoutManager, PostRecyclerViewAdapter adapter,
PostPaginationScrollListener(Context context, Retrofit retrofit, LinearLayoutManager layoutManager, PostRecyclerViewAdapter adapter,
String lastItem, ArrayList<PostData> postData, PaginationSynchronizer paginationSynchronizer,
final String subredditName, final boolean isBestPost, boolean isLoading,
boolean loadSuccess, Locale locale) {
if(context != null) {
this.mContext = context;
this.mRetrofit = retrofit;
this.mLayoutManager = layoutManager;
this.mAdapter = adapter;
this.mLastItem = lastItem;
@ -91,17 +92,17 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener {
loadFailed();
return;
}
Log.i("fetch best post pag", "start");
isLoading = true;
loadSuccess = false;
mPaginationSynchronizer.setLoadingState(true);
Retrofit retrofit = new Retrofit.Builder()
/*Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditUtils.OAUTH_API_BASE_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
.build();*/
RedditAPI api = retrofit.create(RedditAPI.class);
RedditAPI api = mRetrofit.create(RedditAPI.class);
String accessToken = mContext.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE)
.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, "");
@ -172,12 +173,12 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener {
loadSuccess = false;
mPaginationSynchronizer.setLoadingState(true);
Retrofit retrofit = new Retrofit.Builder()
/*Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditUtils.API_BASE_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
.build();*/
RedditAPI api = retrofit.create(RedditAPI.class);
RedditAPI api = mRetrofit.create(RedditAPI.class);
Call<String> getPost = api.getPost(subredditName, mLastItem);
getPost.enqueue(new Callback<String>() {
@Override

View File

@ -36,6 +36,7 @@ import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
import jp.wasabeef.glide.transformations.BlurTransformation;
import retrofit2.Retrofit;
/**
* Created by alex on 2/25/18.
@ -44,6 +45,7 @@ import jp.wasabeef.glide.transformations.BlurTransformation;
class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<PostData> mPostData;
private Context mContext;
private Retrofit mOauthRetrofit;
private PaginationSynchronizer mPaginationSynchronizer;
private RequestManager glide;
private SubredditDao subredditDao;
@ -55,9 +57,10 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
private static final int VIEW_TYPE_LOADING = 1;
PostRecyclerViewAdapter(Context context, ArrayList<PostData> postData, PaginationSynchronizer paginationSynchronizer, boolean hasMultipleSubreddits) {
PostRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, ArrayList<PostData> postData, PaginationSynchronizer paginationSynchronizer, boolean hasMultipleSubreddits) {
if(context != null) {
mContext = context;
mOauthRetrofit = oauthRetrofit;
mPostData = postData;
mPaginationSynchronizer = paginationSynchronizer;
this.hasMultipleSubreddits = hasMultipleSubreddits;
@ -321,7 +324,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
((DataViewHolder) holder).scoreTextView.setText(Integer.toString(mPostData.get(adapterPosition).getScore() + 1));
}
VoteThing.voteThing(mContext, new VoteThing.VoteThingListener() {
VoteThing.voteThing(mContext, mOauthRetrofit, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position) {
mPostData.get(position).setVoteType(1);
@ -345,7 +348,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
((DataViewHolder) holder).upvoteButton.clearColorFilter();
((DataViewHolder) holder).scoreTextView.setText(Integer.toString(mPostData.get(adapterPosition).getScore() - 1));
VoteThing.voteThing(mContext, new VoteThing.VoteThingListener() {
VoteThing.voteThing(mContext, mOauthRetrofit, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position) {
mPostData.get(position).setVoteType(0);
@ -379,7 +382,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
((DataViewHolder) holder).scoreTextView.setText(Integer.toString(mPostData.get(adapterPosition).getScore() - 1));
}
VoteThing.voteThing(mContext, new VoteThing.VoteThingListener() {
VoteThing.voteThing(mContext, mOauthRetrofit, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position) {
mPostData.get(position).setVoteType(-1);
@ -403,7 +406,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
((DataViewHolder) holder).downvoteButton.clearColorFilter();
((DataViewHolder) holder).scoreTextView.setText(Integer.toString(mPostData.get(adapterPosition).getScore() + 1));
VoteThing.voteThing(mContext, new VoteThing.VoteThingListener() {
VoteThing.voteThing(mContext, mOauthRetrofit, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position) {
mPostData.get(position).setVoteType(0);

View File

@ -52,12 +52,11 @@ class RefreshAccessToken {
String newAccessToken = jsonObject.getString(RedditUtils.ACCESS_TOKEN_KEY);
int expireIn = jsonObject.getInt(RedditUtils.EXPIRES_IN_KEY);
long queryAccessTokenTime = Calendar.getInstance().getTimeInMillis();
SharedPreferences.Editor editor = context.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE).edit();
editor.putString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, newAccessToken);
editor.putInt(SharedPreferencesUtils.ACCESS_TOKEN_EXPIRE_INTERVAL_KEY, expireIn);
editor.apply();
long queryAccessTokenTime = Calendar.getInstance().getTimeInMillis();
editor.putLong(SharedPreferencesUtils.QUERY_ACCESS_TOKEN_TIME_KEY, queryAccessTokenTime);
editor.apply();

View File

@ -24,7 +24,6 @@ import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
@ -178,12 +177,10 @@ public class ViewImageActivity extends AppCompatActivity {
.y(totalLengthY)
.setDuration(0)
.start();
Log.i("total length", Float.toString(totalLengthY));
}
@Override
public boolean onSwipedUp(final MotionEvent event) {
Log.i("total length", Float.toString(totalLengthY));
if (totalLengthY < -pxHeight / 8) {
mImageView.animate()
.y(-pxHeight)

View File

@ -37,8 +37,12 @@ import org.sufficientlysecure.htmltextview.HtmlTextView;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import de.hdodenhof.circleimageview.CircleImageView;
import jp.wasabeef.glide.transformations.BlurTransformation;
import retrofit2.Retrofit;
public class ViewPostDetailActivity extends AppCompatActivity {
@ -65,10 +69,21 @@ public class ViewPostDetailActivity extends AppCompatActivity {
private LoadSubredditIconAsyncTask mLoadSubredditIconAsyncTask;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_post_detail);
((Infinity) getApplication()).getmNetworkComponent().inject(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
orientation = getResources().getConfiguration().orientation;
@ -160,26 +175,6 @@ public class ViewPostDetailActivity extends AppCompatActivity {
relativeLayout.setVisibility(View.VISIBLE);
mImageView.setVisibility(View.VISIBLE);
loadImage();
/*RequestBuilder imageRequestBuilder = Glide.with(this).load(mPostData.getPreviewUrl()).listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
progressBar.setVisibility(View.GONE);
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
progressBar.setVisibility(View.GONE);
return false;
}
});
if(mPostData.isNSFW()) {
imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 3)))
.into(mImageView);
} else {
imageRequestBuilder.into(mImageView);
}*/
}
if(mPostData.isCrosspost()) {
@ -385,7 +380,7 @@ public class ViewPostDetailActivity extends AppCompatActivity {
scoreTextView.setText(Integer.toString(mPostData.getScore() + 1));
}
VoteThing.voteThing(ViewPostDetailActivity.this, new VoteThing.VoteThingWithoutPositionListener() {
VoteThing.voteThing(ViewPostDetailActivity.this, mOauthRetrofit, new VoteThing.VoteThingWithoutPositionListener() {
@Override
public void onVoteThingSuccess() {
mPostData.setVoteType(1);
@ -409,7 +404,7 @@ public class ViewPostDetailActivity extends AppCompatActivity {
upvoteButton.clearColorFilter();
scoreTextView.setText(Integer.toString(mPostData.getScore() - 1));
VoteThing.voteThing(ViewPostDetailActivity.this, new VoteThing.VoteThingWithoutPositionListener() {
VoteThing.voteThing(ViewPostDetailActivity.this, mOauthRetrofit, new VoteThing.VoteThingWithoutPositionListener() {
@Override
public void onVoteThingSuccess() {
mPostData.setVoteType(0);
@ -445,7 +440,7 @@ public class ViewPostDetailActivity extends AppCompatActivity {
scoreTextView.setText(Integer.toString(mPostData.getScore() - 1));
}
VoteThing.voteThing(ViewPostDetailActivity.this, new VoteThing.VoteThingWithoutPositionListener() {
VoteThing.voteThing(ViewPostDetailActivity.this, mOauthRetrofit, new VoteThing.VoteThingWithoutPositionListener() {
@Override
public void onVoteThingSuccess() {
mPostData.setVoteType(-1);
@ -469,7 +464,7 @@ public class ViewPostDetailActivity extends AppCompatActivity {
downvoteButton.clearColorFilter();
scoreTextView.setText(Integer.toString(mPostData.getScore() + 1));
VoteThing.voteThing(ViewPostDetailActivity.this, new VoteThing.VoteThingWithoutPositionListener() {
VoteThing.voteThing(ViewPostDetailActivity.this, mOauthRetrofit, new VoteThing.VoteThingWithoutPositionListener() {
@Override
public void onVoteThingSuccess() {
mPostData.setVoteType(0);
@ -492,7 +487,7 @@ public class ViewPostDetailActivity extends AppCompatActivity {
private void queryComment() {
mCommentProgressbar.setVisibility(View.VISIBLE);
mNoCommentWrapperLinearLayout.setVisibility(View.GONE);
FetchComment.fetchComment(mPostData.getSubredditNamePrefixed(), mPostData.getId(),
FetchComment.fetchComment(mRetrofit, mPostData.getSubredditNamePrefixed(), mPostData.getId(),
null, new FetchComment.FetchCommentListener() {
@Override
public void onFetchCommentSuccess(String response) {
@ -505,7 +500,8 @@ public class ViewPostDetailActivity extends AppCompatActivity {
mMoreCommentCount = moreCommentCount;
if (commentData.size() > 0) {
CommentMultiLevelRecyclerViewAdapter adapter = new CommentMultiLevelRecyclerViewAdapter(
ViewPostDetailActivity.this, (ArrayList<CommentData>) commentData,
ViewPostDetailActivity.this, mRetrofit, mOauthRetrofit,
(ArrayList<CommentData>) commentData,
mRecyclerView, mPostData.getSubredditNamePrefixed(),
mPostData.getId(), getResources().getConfiguration().locale);
mRecyclerView.removeItemClickListeners();

View File

@ -22,7 +22,11 @@ import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import javax.inject.Inject;
import javax.inject.Named;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Retrofit;
public class ViewSubredditDetailActivity extends AppCompatActivity {
@ -36,10 +40,17 @@ public class ViewSubredditDetailActivity extends AppCompatActivity {
private SubredditViewModel mSubredditViewModel;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_subreddit_detail);
((Infinity) getApplication()).getmNetworkComponent().inject(this);
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
@ -65,8 +76,6 @@ public class ViewSubredditDetailActivity extends AppCompatActivity {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
/*collapsingToolbarLayout.setExpandedTitleColor(Color.BLACK);
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.BLACK);*/
if(scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
} else {
@ -158,7 +167,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity {
}
});
FetchSubredditData.fetchSubredditData(subredditName, new FetchSubredditData.FetchSubredditDataListener() {
FetchSubredditData.fetchSubredditData(mRetrofit, subredditName, new FetchSubredditData.FetchSubredditDataListener() {
@Override
public void onFetchSubredditDataSuccess(String response) {
ParseSubredditData.parseComment(response, new ParseSubredditData.ParseSubredditDataListener() {

View File

@ -10,7 +10,6 @@ import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
/**
* Created by alex on 3/14/18.
@ -28,18 +27,15 @@ class VoteThing {
void onVoteThingFail();
}
static void voteThing(final Context context, final VoteThingListener voteThingListener, final String fullName, final String point, final int position, final int refreshTime) {
static void voteThing(final Context context, final Retrofit retrofit,
final VoteThingListener voteThingListener, final String fullName,
final String point, final int position, final int refreshTime) {
if(context != null) {
if(refreshTime < 0) {
voteThingListener.onVoteThingFail(position);
return;
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditUtils.OAUTH_API_BASE_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
RedditAPI api = retrofit.create(RedditAPI.class);
String accessToken = context.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE)
@ -63,7 +59,7 @@ class VoteThing {
new RefreshAccessToken.RefreshAccessTokenListener() {
@Override
public void onRefreshAccessTokenSuccess() {
voteThing(context, voteThingListener, fullName, point, position, refreshTime - 1);
voteThing(context, retrofit, voteThingListener, fullName, point, position, refreshTime - 1);
}
@Override
@ -75,18 +71,15 @@ class VoteThing {
}
}
static void voteThing(final Context context, final VoteThingWithoutPositionListener voteThingWithoutPositionListener, final String fullName, final String point, final int refreshTime) {
static void voteThing(final Context context, final Retrofit retrofit,
final VoteThingWithoutPositionListener voteThingWithoutPositionListener,
final String fullName, final String point, final int refreshTime) {
if(context != null) {
if(refreshTime < 0) {
voteThingWithoutPositionListener.onVoteThingFail();
return;
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditUtils.OAUTH_API_BASE_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
RedditAPI api = retrofit.create(RedditAPI.class);
String accessToken = context.getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE)
@ -110,7 +103,7 @@ class VoteThing {
new RefreshAccessToken.RefreshAccessTokenListener() {
@Override
public void onRefreshAccessTokenSuccess() {
voteThing(context, voteThingWithoutPositionListener, fullName, point, refreshTime - 1);
voteThing(context, retrofit, voteThingWithoutPositionListener, fullName, point, refreshTime - 1);
}
@Override