Fixed user icon and user banner not displaying after user login. LoginActivity will not show page not found error after login finish.

This commit is contained in:
Alex Ning 2019-02-26 21:56:51 +08:00
parent 8ae7ba334c
commit 9530e1f497
8 changed files with 113 additions and 109 deletions

Binary file not shown.

View File

@ -41,8 +41,6 @@ dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.2-alpha01'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.2-alpha01'
implementation 'com.android.volley:volley:1.1.0'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.google.android.exoplayer:exoplayer:2.7.0'
implementation 'com.google.android.exoplayer:exoplayer-dash:2.7.0'
implementation 'androidx.browser:browser:1.0.0'

View File

@ -12,27 +12,37 @@ import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class LoginActivity extends AppCompatActivity {
private String authCode;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
((Infinity) getApplication()).getmNetworkComponent().inject(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
WebView webView = findViewById(R.id.webview_login_activity);
@ -53,7 +63,68 @@ public class LoginActivity extends AppCompatActivity {
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if(url.contains("&code=") || url.contains("?code=")) {
Uri uri = Uri.parse(url);
String state = uri.getQueryParameter("state");
if(state.equals(RedditUtils.STATE)) {
authCode = uri.getQueryParameter("code");
SharedPreferences.Editor editor = getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE).edit();
editor.putString(SharedPreferencesUtils.AUTH_CODE_KEY, authCode);
editor.apply();
Map<String, String> params = new HashMap<>();
params.put(RedditUtils.GRANT_TYPE_KEY, "authorization_code");
params.put("code", authCode);
params.put("redirect_uri", RedditUtils.REDIRECT_URI);
RedditAPI api = mRetrofit.create(RedditAPI.class);
Call<String> accessTokenCall = api.getAccessToken(RedditUtils.getHttpBasicAuthHeader(), params);
accessTokenCall.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
try {
JSONObject responseJSON = new JSONObject(response.body());
String accessToken = responseJSON.getString(RedditUtils.ACCESS_TOKEN_KEY);
String refreshToken = responseJSON.getString(RedditUtils.REFRESH_TOKEN_KEY);
editor.putString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, accessToken);
editor.putString(SharedPreferencesUtils.REFRESH_TOKEN_KEY, refreshToken);
editor.apply();
Intent resultIntent = new Intent();
setResult(Activity.RESULT_OK, resultIntent);
finish();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginActivity.this, "Error occurred when parsing the JSON response", Toast.LENGTH_SHORT).show();
finish();
}
} else {
Toast.makeText(LoginActivity.this, "Error Retrieving the token", Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(LoginActivity.this, "Error Retrieving the token", Toast.LENGTH_SHORT).show();
finish();
}
});
} else {
Toast.makeText(LoginActivity.this, "Something went wrong. Try again later.", Toast.LENGTH_SHORT).show();
finish();
}
} else if (url.contains("error=access_denied")) {
Toast.makeText(LoginActivity.this, "Access denied", Toast.LENGTH_SHORT).show();
finish();
} else {
view.loadUrl(url);
}
return true;
}
@ -65,68 +136,6 @@ public class LoginActivity extends AppCompatActivity {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(url.contains("&code=") || url.contains("?code=")) {
Uri uri = Uri.parse(url);
String state = uri.getQueryParameter("state");
if(state.equals(RedditUtils.STATE)) {
authCode = uri.getQueryParameter("code");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("authCode", authCode);
final SharedPreferences.Editor editor = getSharedPreferences(SharedPreferencesUtils.AUTH_CODE_FILE_KEY, Context.MODE_PRIVATE).edit();
editor.putString(SharedPreferencesUtils.AUTH_CODE_KEY, authCode);
editor.apply();
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
String tokenRetrievalUrl = "https://www.reddit.com/api/v1/access_token";
StringRequest requestToken = new StringRequest(Request.Method.POST, tokenRetrievalUrl, response -> {
try {
JSONObject responseJSON = new JSONObject(response);
String accessToken = responseJSON.getString(RedditUtils.ACCESS_TOKEN_KEY);
String refreshToken = responseJSON.getString(RedditUtils.REFRESH_TOKEN_KEY);
editor.putString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, accessToken);
editor.putString(SharedPreferencesUtils.REFRESH_TOKEN_KEY, refreshToken);
editor.apply();
Intent resultIntent = new Intent();
setResult(Activity.RESULT_OK, resultIntent);
finish();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginActivity.this, "Error occurred when parsing the JSON response", Toast.LENGTH_SHORT).show();
finish();
}
}, error -> {
Toast.makeText(LoginActivity.this, "Error Retrieving the token", Toast.LENGTH_SHORT).show();
finish();
}){
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(RedditUtils.GRANT_TYPE_KEY, "authorization_code");
params.put("code", authCode);
params.put("redirect_uri", RedditUtils.REDIRECT_URI);
return params;
}
@Override
public Map<String, String> getHeaders() {
return RedditUtils.getHttpBasicAuthHeader();
}
};
queue.add(requestToken);
} else {
Toast.makeText(LoginActivity.this, "Something went wrong. Try again later.", Toast.LENGTH_SHORT).show();
finish();
}
} else if (url.contains("error=access_denied")) {
Toast.makeText(LoginActivity.this, "Access denied", Toast.LENGTH_SHORT).show();
finish();
}
}
});
}

View File

@ -14,6 +14,7 @@ import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import com.ferfalk.simplesearchview.SimpleSearchView;
import java.util.ArrayList;
@ -40,16 +41,13 @@ import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
private static final String FRAGMENT_OUT_STATE = "FOS";
private static final String NAME_STATE = "NS";
private static final String PROFILE_IMAGE_URL_STATE = "PIUS";
private static final String BANNER_IMAGE_URL_STATE = "BIUS";
private static final String KARMA_STATE = "KS";
private static final String FETCH_USER_INFO_STATE = "FUIS";
private static final String INSERT_SUBSCRIBED_SUBREDDIT_STATE = "ISSS";
@ -66,7 +64,7 @@ public class MainActivity extends AppCompatActivity {
private TextView mNameTextView;
private TextView mKarmaTextView;
private CircleImageView mProfileImageView;
private GifImageView mProfileImageView;
private ImageView mBannerImageView;
private Fragment mFragment;
@ -76,8 +74,8 @@ public class MainActivity extends AppCompatActivity {
private String mProfileImageUrl;
private String mBannerImageUrl;
private String mKarma;
private boolean mFetchUserInfoSuccess;
private boolean mInsertSuccess;
private boolean mFetchUserInfoSuccess = false;
private boolean mInsertSuccess = false;
private SubscribedSubredditViewModel mSubscribedSubredditViewModel;
private SubscribedUserViewModel mSubscribedUserViewModel;
@ -169,9 +167,12 @@ public class MainActivity extends AppCompatActivity {
} else {
mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_content_main, mFragment).commit();
mFetchUserInfoSuccess = savedInstanceState.getBoolean(FETCH_USER_INFO_STATE);
mInsertSuccess = savedInstanceState.getBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE);
}
loadUserData();
glide = Glide.with(this);
View header = findViewById(R.id.nav_header_main_activity);
mNameTextView = header.findViewById(R.id.name_text_view_nav_header_main);
@ -179,6 +180,8 @@ public class MainActivity extends AppCompatActivity {
mProfileImageView = header.findViewById(R.id.profile_image_view_nav_header_main);
mBannerImageView = header.findViewById(R.id.banner_image_view_nav_header_main);
loadUserData();
subscribedSubredditRecyclerView.setLayoutManager(new LinearLayoutManager(this));
subscribedSubredditRecyclerView.setNestedScrollingEnabled(false);
@ -192,10 +195,18 @@ public class MainActivity extends AppCompatActivity {
mNameTextView.setText(mName);
mKarmaTextView.setText(mKarma);
glide = Glide.with(this);
if (!mProfileImageUrl.equals("")) {
glide.load(mProfileImageUrl).into(mProfileImageView);
glide.load(mProfileImageUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(144, 0)))
.error(glide.load(R.drawable.subreddit_default_icon))
.into(mProfileImageView);
} else {
glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(144, 0)))
.into(mProfileImageView);
}
if (!mBannerImageUrl.equals("")) {
glide.load(mBannerImageUrl).into(mBannerImageView);
}
@ -245,10 +256,17 @@ public class MainActivity extends AppCompatActivity {
@Override
public void onParseMyInfoSuccess(String name, String profileImageUrl, String bannerImageUrl, int karma) {
mNameTextView.setText(name);
if (!mProfileImageUrl.equals("")) {
glide.load(profileImageUrl).into(mProfileImageView);
if (!profileImageUrl.equals("")) {
glide.load(profileImageUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(128, 0)))
.error(glide.load(R.drawable.subreddit_default_icon))
.into(mProfileImageView);
} else {
glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(128, 0)))
.into(mProfileImageView);
}
if (!mBannerImageUrl.equals("")) {
if (!bannerImageUrl.equals("")) {
glide.load(bannerImageUrl).into(mBannerImageView);
}
@ -368,30 +386,8 @@ public class MainActivity extends AppCompatActivity {
if (mFragment != null) {
getSupportFragmentManager().putFragment(outState, FRAGMENT_OUT_STATE, mFragment);
}
outState.putString(NAME_STATE, mName);
outState.putString(PROFILE_IMAGE_URL_STATE, mProfileImageUrl);
outState.putString(BANNER_IMAGE_URL_STATE, mBannerImageUrl);
outState.putString(KARMA_STATE, mKarma);
outState.putBoolean(FETCH_USER_INFO_STATE, mFetchUserInfoSuccess);
outState.putBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE, mInsertSuccess);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mName = savedInstanceState.getString(NAME_STATE);
mProfileImageUrl = savedInstanceState.getString(PROFILE_IMAGE_URL_STATE);
mBannerImageUrl = savedInstanceState.getString(BANNER_IMAGE_URL_STATE);
mKarma = savedInstanceState.getString(KARMA_STATE);
mFetchUserInfoSuccess = savedInstanceState.getBoolean(FETCH_USER_INFO_STATE);
mInsertSuccess = savedInstanceState.getBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE);
mNameTextView.setText(mName);
mKarmaTextView.setText(mKarma);
if (!mProfileImageUrl.equals("")) {
glide.load(mProfileImageUrl).into(mProfileImageView);
}
if (!mBannerImageUrl.equals("")) {
glide.load(mBannerImageUrl).into(mBannerImageView);
}
}
}

View File

@ -8,6 +8,7 @@ import dagger.Component;
@Component(modules = NetworkModule.class)
interface NetworkComponent {
void inject(MainActivity mainActivity);
void inject(LoginActivity loginActivity);
void inject(PostFragment postFragment);
void inject(SubredditListingFragment subredditListingFragment);
void inject(UserListingFragment userListingFragment);

View File

@ -14,7 +14,7 @@
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
<de.hdodenhof.circleimageview.CircleImageView
<pl.droidsonroids.gif.GifImageView
android:id="@+id/profile_image_view_nav_header_main"
android:layout_width="64dp"
android:layout_height="64dp"

View File

@ -15,5 +15,5 @@
android:orderInCategory="1"
android:title="@string/action_search"
android:icon="@drawable/ic_search_white_24dp"
app:showAsAction="always" />
app:showAsAction="ifRoom" />
</menu>