Fetch the subreddit info and save it to the database. Solve a bug that cannot create a instance of SubredditViewModel.

This commit is contained in:
Alex Ning 2018-08-05 12:26:50 +08:00
parent 9334d3860e
commit c6026e5659
10 changed files with 158 additions and 53 deletions

View File

@ -62,4 +62,5 @@ class JSONUtils {
static final String SUBSCRIBERS_KEY = "subscribers"; static final String SUBSCRIBERS_KEY = "subscribers";
static final String PUBLIC_DESCRIPTION = "public_description"; static final String PUBLIC_DESCRIPTION = "public_description";
static final String ACTIVE_USER_COUNT = "active_user_count"; static final String ACTIVE_USER_COUNT = "active_user_count";
static final String DISPLAY_NAME_PREFIXED = "display_name_prefixed";
} }

View File

@ -202,10 +202,6 @@ public class MainActivity extends AppCompatActivity {
SubscribedUserRoomDatabase.getDatabase(MainActivity.this), SubscribedUserRoomDatabase.getDatabase(MainActivity.this),
subscribedSubredditData, subscribedSubredditData,
subscribedUserData).execute(); subscribedUserData).execute();
/*new InsertSubscribedUsersAsyncTask(
SubscribedUserRoomDatabase.getDatabase(MainActivity.this),
subscribedUserData).execute();*/
} }
@Override @Override
@ -282,23 +278,4 @@ public class MainActivity extends AppCompatActivity {
return null; return null;
} }
} }
/*private static class InsertSubscribedUsersAsyncTask extends AsyncTask<Void, Void, Void> {
private final SubscribedUserDao mDao;
private List<SubscribedUserData> subscribedUserData;
InsertSubscribedUsersAsyncTask(SubscribedUserRoomDatabase db, List<SubscribedUserData> subscribedUserData) {
mDao = db.subscribedUserDao();
this.subscribedUserData = subscribedUserData;
}
@Override
protected Void doInBackground(final Void... params) {
for(SubscribedUserData s : subscribedUserData) {
mDao.insert(s);
}
return null;
}
}*/
} }

View File

@ -8,7 +8,7 @@ import org.json.JSONObject;
class ParseSubredditData { class ParseSubredditData {
interface ParseSubredditDataListener { interface ParseSubredditDataListener {
void onParseSubredditDataSuccess(); void onParseSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers);
void onParseSubredditDataFail(); void onParseSubredditDataFail();
} }
@ -23,6 +23,8 @@ class ParseSubredditData {
private JSONObject jsonResponse; private JSONObject jsonResponse;
private boolean parseFailed; private boolean parseFailed;
private ParseSubredditDataListener parseSubredditDataListener; private ParseSubredditDataListener parseSubredditDataListener;
private SubredditData subredditData;
private int mNCurrentOnlineSubscribers;
ParseSubredditDataAsyncTask(String response, ParseSubredditDataListener parseSubredditDataListener){ ParseSubredditDataAsyncTask(String response, ParseSubredditDataListener parseSubredditDataListener){
this.parseSubredditDataListener = parseSubredditDataListener; this.parseSubredditDataListener = parseSubredditDataListener;
@ -40,11 +42,14 @@ class ParseSubredditData {
try { try {
JSONObject data = jsonResponse.getJSONObject(JSONUtils.DATA_KEY); JSONObject data = jsonResponse.getJSONObject(JSONUtils.DATA_KEY);
String id = data.getString(JSONUtils.NAME_KEY); String id = data.getString(JSONUtils.NAME_KEY);
String subredditFullName = data.getString(JSONUtils.DISPLAY_NAME_PREFIXED);
String description = data.getString(JSONUtils.PUBLIC_DESCRIPTION); String description = data.getString(JSONUtils.PUBLIC_DESCRIPTION);
String bannerImageUrl = data.getString(JSONUtils.BANNER_IMG_KEY); String bannerImageUrl = data.getString(JSONUtils.BANNER_IMG_KEY);
String iconImageUrl = data.getString(JSONUtils.ICON_IMG_KEY); String iconImageUrl = data.getString(JSONUtils.ICON_IMG_KEY);
int nSubscribers = data.getInt(JSONUtils.SUBSCRIBERS_KEY); int nSubscribers = data.getInt(JSONUtils.SUBSCRIBERS_KEY);
int nCurrentOnlineSubscribers = data.getInt(JSONUtils.ACTIVE_USER_COUNT); int nCurrentOnlineSubscribers = data.getInt(JSONUtils.ACTIVE_USER_COUNT);
subredditData = new SubredditData(id, subredditFullName, iconImageUrl, bannerImageUrl, description, nSubscribers);
mNCurrentOnlineSubscribers = nCurrentOnlineSubscribers;
} catch (JSONException e) { } catch (JSONException e) {
parseFailed = true; parseFailed = true;
Log.i("parse", "SubredditData error"); Log.i("parse", "SubredditData error");
@ -56,7 +61,7 @@ class ParseSubredditData {
@Override @Override
protected void onPostExecute(Void aVoid) { protected void onPostExecute(Void aVoid) {
if(!parseFailed) { if(!parseFailed) {
parseSubredditDataListener.onParseSubredditDataSuccess(); parseSubredditDataListener.onParseSubredditDataSuccess(subredditData, mNCurrentOnlineSubscribers);
} else { } else {
parseSubredditDataListener.onParseSubredditDataFail(); parseSubredditDataListener.onParseSubredditDataFail();
} }

View File

@ -57,7 +57,7 @@ class SubredditData {
return description; return description;
} }
public int getnSubscribers() { public int getNSubscribers() {
return nSubscribers; return nSubscribers;
} }
} }

View File

@ -3,6 +3,9 @@ package ml.docilealligator.infinityforreddit;
import android.app.Application; import android.app.Application;
import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData; import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProvider;
import android.support.annotation.NonNull;
public class SubredditViewModel extends AndroidViewModel { public class SubredditViewModel extends AndroidViewModel {
private SubredditRepository mSubredditRepository; private SubredditRepository mSubredditRepository;
@ -21,4 +24,23 @@ public class SubredditViewModel extends AndroidViewModel {
public void insert(SubredditData subredditData) { public void insert(SubredditData subredditData) {
mSubredditRepository.insert(subredditData); mSubredditRepository.insert(subredditData);
} }
public static class Factory extends ViewModelProvider.NewInstanceFactory {
@NonNull
private final Application mApplication;
private final String id;
public Factory(@NonNull Application application, String id) {
mApplication = application;
this.id = id;
}
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
//noinspection unchecked
return (T) new SubredditViewModel(mApplication, id);
}
}
} }

View File

@ -33,11 +33,13 @@ class SubscribedSubredditRecyclerViewAdapter extends RecyclerView.Adapter<Recycl
} }
@Override @Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) { public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, final int i) {
viewHolder.itemView.setOnClickListener(new View.OnClickListener() { viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
Intent intent = new Intent(mContext, ViewSubredditDetailActivity.class); Intent intent = new Intent(mContext, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME, mSubscribedSubredditData.get(viewHolder.getAdapterPosition()).getName());
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_ID, mSubscribedSubredditData.get(viewHolder.getAdapterPosition()).getId());
mContext.startActivity(intent); mContext.startActivity(intent);
} }
}); });

View File

@ -1,16 +1,31 @@
package ml.docilealligator.infinityforreddit; package ml.docilealligator.infinityforreddit;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout; import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.View; import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import de.hdodenhof.circleimageview.CircleImageView;
public class ViewSubredditDetailActivity extends AppCompatActivity { public class ViewSubredditDetailActivity extends AppCompatActivity {
static final String EXTRA_SUBREDDIT_NAME = "ESN";
static final String EXTRA_SUBREDDIT_ID = "ESI";
private SubredditViewModel mSubredditViewModel;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
@ -18,6 +33,8 @@ public class ViewSubredditDetailActivity extends AppCompatActivity {
Toolbar toolbar = findViewById(R.id.toolbar); Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
String id = getIntent().getExtras().getString(EXTRA_SUBREDDIT_ID);
final String subredditName = getIntent().getExtras().getString(EXTRA_SUBREDDIT_NAME);
final CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar_layout_view_subreddit_detail_activity); final CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar_layout_view_subreddit_detail_activity);
AppBarLayout appBarLayout = findViewById(R.id.app_bar_layout_view_subreddit_detail_activity); AppBarLayout appBarLayout = findViewById(R.id.app_bar_layout_view_subreddit_detail_activity);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@ -30,7 +47,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity {
scrollRange = appBarLayout.getTotalScrollRange(); scrollRange = appBarLayout.getTotalScrollRange();
} }
if (scrollRange + verticalOffset == 0) { if (scrollRange + verticalOffset == 0) {
collapsingToolbarLayout.setTitle(getString(R.string.title_activity_view_subreddit_detail)); collapsingToolbarLayout.setTitle(subredditName);
isShow = true; isShow = true;
} else if(isShow) { } else if(isShow) {
collapsingToolbarLayout.setTitle(" ");//carefull there should a space between double quote otherwise it wont work collapsingToolbarLayout.setTitle(" ");//carefull there should a space between double quote otherwise it wont work
@ -39,13 +56,78 @@ public class ViewSubredditDetailActivity extends AppCompatActivity {
} }
}); });
FloatingActionButton fab = findViewById(R.id.fab); final ImageView bannerImageView = findViewById(R.id.banner_image_view_view_subreddit_detail_activity);
fab.setOnClickListener(new View.OnClickListener() { final CircleImageView iconCircleImageView = findViewById(R.id.icon_circle_image_view_view_subreddit_detail_activity);
final TextView subredditNameTextView = findViewById(R.id.subreddit_name_text_view_view_subreddit_detail_activity);
final TextView nSubscribersTextView = findViewById(R.id.subscriber_count_text_view_view_subreddit_detail_activity);
final TextView nOnlineSubscribersTextView = findViewById(R.id.online_subscriber_count_text_view_view_subreddit_detail_activity);
final TextView descriptionTextView = findViewById(R.id.description_text_view_view_subreddit_detail_activity);
final RequestManager glide = Glide.with(ViewSubredditDetailActivity.this);
SubredditViewModel.Factory factory = new SubredditViewModel.Factory(getApplication(), id);
mSubredditViewModel = ViewModelProviders.of(this, factory).get(SubredditViewModel.class);
mSubredditViewModel.getSubredditData().observe(this, new Observer<SubredditData>() {
@Override @Override
public void onClick(View view) { public void onChanged(@Nullable SubredditData subredditData) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) if(subredditData != null) {
.setAction("Action", null).show(); if(!subredditData.getBannerUrl().equals("") && !subredditData.getBannerUrl().equals("null")) {
glide.load(subredditData.getBannerUrl()).into(bannerImageView);
}
if(subredditData.getIconUrl().equals("") || subredditData.getIconUrl().equals("null")) {
glide.load(getDrawable(R.drawable.subreddit_default_icon)).into(iconCircleImageView);
} else {
glide.load(subredditData.getIconUrl()).into(iconCircleImageView);
}
subredditNameTextView.setText(subredditData.getName());
String nSubscribers = getString(R.string.subscribers_number_detail, subredditData.getNSubscribers());
nSubscribersTextView.setText(nSubscribers);
descriptionTextView.setText(subredditData.getDescription());
}
}
});
new FetchSubredditData(Volley.newRequestQueue(this), subredditName).querySubredditData(new FetchSubredditData.FetchSubredditDataListener() {
@Override
public void onFetchSubredditDataSuccess(String response) {
new ParseSubredditData().parseComment(response, new ParseSubredditData.ParseSubredditDataListener() {
@Override
public void onParseSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) {
new InsertSubredditDataAsyncTask(SubredditRoomDatabase.getDatabase(ViewSubredditDetailActivity.this), subredditData)
.execute();
String nOnlineSubscribers = getString(R.string.online_subscribers_number_detail, nCurrentOnlineSubscribers);
nOnlineSubscribersTextView.setText(nOnlineSubscribers);
}
@Override
public void onParseSubredditDataFail() {
Toast.makeText(ViewSubredditDetailActivity.this, "Cannot fetch subreddit info", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onFetchSubredditDataFail() {
} }
}); });
} }
private static class InsertSubredditDataAsyncTask extends AsyncTask<Void, Void, Void> {
private final SubredditDao mSubredditDao;
private SubredditData subredditData;
InsertSubredditDataAsyncTask(SubredditRoomDatabase subredditDb, SubredditData subredditData) {
mSubredditDao = subredditDb.subredditDao();
this.subredditData = subredditData;
}
@Override
protected Void doInBackground(final Void... params) {
mSubredditDao.insert(subredditData);
return null;
}
}
} }

View File

@ -29,13 +29,12 @@
<ImageView <ImageView
android:id="@+id/banner_image_view_view_subreddit_detail_activity" android:id="@+id/banner_image_view_view_subreddit_detail_activity"
android:src="@drawable/subreddit_default_icon"
android:layout_width="match_parent" android:layout_width="match_parent"
android:scaleType="centerCrop" android:scaleType="centerCrop"
android:layout_height="180dp" /> android:layout_height="180dp" />
<de.hdodenhof.circleimageview.CircleImageView <de.hdodenhof.circleimageview.CircleImageView
android:src="@drawable/subreddit_default_icon" android:id="@+id/icon_circle_image_view_view_subreddit_detail_activity"
android:layout_width="72dp" android:layout_width="72dp"
android:layout_height="72dp" android:layout_height="72dp"
android:layout_marginTop="-36dp" android:layout_marginTop="-36dp"
@ -53,22 +52,46 @@
android:background="@android:color/white"> android:background="@android:color/white">
<TextView <TextView
android:id="@+id/name_text_view_view_subreddit_detail_activity" android:id="@+id/subreddit_name_text_view_view_subreddit_detail_activity"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="36dp" android:layout_marginTop="36dp"
android:layout_marginStart="16dp" android:layout_marginStart="16dp"
android:layout_marginEnd="16dp" android:layout_marginEnd="16dp"
android:textColor="@android:color/black" android:textSize="18sp"
android:text="Dummy"/> android:textColor="@color/colorAccent"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/subscriber_count_text_view_view_subreddit_detail_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:textColor="@android:color/black" />
<TextView
android:id="@+id/online_subscriber_count_text_view_view_subreddit_detail_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_alignParentEnd="true"
android:textColor="@android:color/black" />
</RelativeLayout>
<TextView <TextView
android:id="@+id/subscriber_count_text_view_view_subreddit_detail_activity" android:id="@+id/description_text_view_view_subreddit_detail_activity"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_margin="16dp" android:layout_margin="16dp"
android:textColor="@android:color/black" android:textColor="@android:color/black" />
android:text="Subscriber: 10000"/>
</LinearLayout> </LinearLayout>
@ -86,13 +109,4 @@
<include layout="@layout/content_view_subreddit_detail" /> <include layout="@layout/content_view_subreddit_detail" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/fab_margin"
app:layout_anchor="@id/app_bar_layout_view_subreddit_detail_activity"
app:layout_anchorGravity="bottom|end"
app:srcCompat="@drawable/baseline_add_white_24" />
</android.support.design.widget.CoordinatorLayout> </android.support.design.widget.CoordinatorLayout>

View File

@ -20,6 +20,8 @@
<string name="following">Following</string> <string name="following">Following</string>
<string name="subscriptions">Subscriptions</string> <string name="subscriptions">Subscriptions</string>
<string name="title_activity_view_subreddit_detail">ViewSubredditDetailActivity</string> <string name="title_activity_view_subreddit_detail">ViewSubredditDetailActivity</string>
<string name="subscribers_number_detail">Subscribers: %1$d</string>
<string name="online_subscribers_number_detail">Online: %1$d</string>
<string name="large_text"> <string name="large_text">
"Material is the metaphor.\n\n" "Material is the metaphor.\n\n"