-
-
Save anonymous/bd1b6afd21d27744a99970d3f51aa8a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.elgami.feed; | |
import android.Manifest; | |
import android.app.AlertDialog; | |
import android.app.ProgressDialog; | |
import android.content.ClipData; | |
import android.content.ClipboardManager; | |
import android.content.Context; | |
import android.content.DialogInterface; | |
import android.content.Intent; | |
import android.content.pm.PackageManager; | |
import android.graphics.Bitmap; | |
import android.graphics.drawable.BitmapDrawable; | |
import android.graphics.drawable.Drawable; | |
import android.net.Uri; | |
import android.os.AsyncTask; | |
import android.os.Build; | |
import android.os.Bundle; | |
import android.provider.MediaStore; | |
import android.support.annotation.NonNull; | |
import android.support.v4.app.ActivityCompat; | |
import android.support.v4.app.Fragment; | |
import android.support.v4.widget.SwipeRefreshLayout; | |
import android.support.v7.app.AppCompatActivity; | |
import android.support.v7.widget.LinearLayoutManager; | |
import android.support.v7.widget.RecyclerView; | |
import android.support.v7.widget.Toolbar; | |
import android.util.Log; | |
import android.view.Menu; | |
import android.view.MenuInflater; | |
import android.view.MenuItem; | |
import android.view.View; | |
import android.view.animation.AnimationUtils; | |
import android.widget.ImageView; | |
import android.widget.TextView; | |
import android.widget.Toast; | |
import com.elgami.cache.DesignImageFileCache; | |
import com.elgami.cache.FeedItemFileCache; | |
import com.elgami.cache.ImageLoader; | |
import com.elgami.comments.CommentsActivity; | |
import com.elgami.customizer.MainActivity; | |
import com.elgami.customizer.R; | |
import com.elgami.customizer.UserSettingsActivity; | |
import com.elgami.gallery.GalleryActivity; | |
import com.elgami.gallery.RemoveDesignFromGalleryAndFeedTask; | |
import com.elgami.market.MarketFeedActivity; | |
import com.elgami.network.api.RetrofitParseRequestManager; | |
import com.elgami.network.model.Comment; | |
import com.elgami.network.model.Feed; | |
import com.elgami.notifications.NotificationsActivity; | |
import com.elgami.parse.ParseConstants; | |
import com.elgami.preferences.UserStateProvider; | |
import com.elgami.utility.EndlessRecyclerOnScrollListener; | |
import com.elgami.utility.NetworkHelper; | |
import com.facebook.ads.Ad; | |
import com.facebook.ads.AdError; | |
import com.facebook.ads.AdListener; | |
import com.facebook.ads.NativeAd; | |
import com.facebook.ads.NativeAdsManager; | |
import com.parse.ParseAnonymousUtils; | |
import com.parse.ParseException; | |
import com.parse.ParseInstallation; | |
import com.parse.ParseObject; | |
import com.parse.ParsePush; | |
import com.parse.ParseQuery; | |
import com.parse.ParseUser; | |
import com.parse.ui.ParseLoginActivity; | |
import java.util.ArrayList; | |
import java.util.Date; | |
import java.util.List; | |
import rx.Subscription; | |
import rx.android.schedulers.AndroidSchedulers; | |
import rx.functions.Func1; | |
import rx.schedulers.Schedulers; | |
public class FeedActivityV2 extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, ActivityCompat.OnRequestPermissionsResultCallback { | |
private static final int RESULT_SETTINGS = 1; | |
private static final int RESULT_MARKETPLACE = 1; | |
private List<Feed> feedItems; // create the new list to be represented in the listview | |
public NativeAd nativeAd; | |
public NativeAdsManager manager; | |
private boolean isUpdating = true; | |
private boolean moreRecords = true; | |
private final static String TAG = "FeedActivity"; | |
private Date latestPostTime; | |
private Date setEndPostTime; | |
private Date lastRefresh; | |
private RecyclerView recyclerView; | |
private FeedRecyclerAdapter feedRecyclerAdapter; | |
private LinearLayoutManager layoutManager; | |
ImageLoader designImageLoader; | |
private ProgressDialog progress; | |
private enum CustomizerLaunchPage { | |
DESIGNER, | |
TEMPLATE | |
} | |
@Override | |
protected void onResume() { | |
Log.d(TAG, "onResume"); | |
super.onResume(); | |
designImageLoader = new ImageLoader(new DesignImageFileCache(this)); | |
} | |
@Override | |
protected void onPause() { | |
Log.d(TAG, "onPause"); | |
super.onPause(); | |
} | |
@Override | |
protected void onStop() { | |
Log.d(TAG, "onStop"); | |
super.onStop(); | |
} | |
@Override | |
protected void onDestroy() { | |
Log.d(TAG, "onDestroy"); | |
if (mFeedDesignsSubscription != null && !mFeedDesignsSubscription.isUnsubscribed()) { | |
Log.d(TAG, "onDestroy killing feed design subscription"); | |
mFeedDesignsSubscription.unsubscribe(); | |
} | |
super.onDestroy(); | |
} | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
Log.d(TAG, "onCreate"); | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_feed); | |
// TODO what the heck is this doing? do we need it? | |
if (ParseUser.getCurrentUser() != null) { | |
ParseUser user = ParseUser.getCurrentUser(); | |
ParseInstallation installation = ParseInstallation.getCurrentInstallation(); | |
installation.put("username", user.getUsername()); | |
if (user.get("profilePicture") != null) { | |
installation.put("profilePicture", user.get("profilePicture")); | |
} | |
installation.put("userId", user.getObjectId()); | |
installation.saveInBackground(); | |
} | |
ImageView networkHelper = (ImageView) findViewById(R.id.networkOffline); | |
networkHelper.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
networkHelper.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.image_click)); | |
} | |
}); | |
setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); | |
getSupportActionBar().setDisplayShowTitleEnabled(false); | |
SwipeRefreshLayout swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); | |
swipeLayout.setOnRefreshListener(this); | |
feedItems = new ArrayList<>(); | |
recyclerView = (RecyclerView) findViewById(R.id.recycler_view); | |
feedRecyclerAdapter = new FeedRecyclerAdapter(this, feedItems, new ImageLoader(new FeedItemFileCache(this)), nativeAd, manager); | |
layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); | |
layoutManager.setOrientation(LinearLayoutManager.VERTICAL); | |
recyclerView.setLayoutManager(layoutManager); | |
recyclerView.setHasFixedSize(true); | |
recyclerView.setAdapter(feedRecyclerAdapter); | |
recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) { | |
@Override | |
public void onLoadMore() { | |
if (!isUpdating && moreRecords) { | |
isUpdating = true; | |
getFeedDesigns(setEndPostTime); | |
} | |
} | |
}); | |
AddRecyclerAdapterClickListeners(); | |
mRetrofitParseRequestManager = RetrofitParseRequestManager.getInstance(); | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) { | |
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); | |
} else { | |
if (NetworkHelper.isOnline(this)) { | |
getFeedDesigns(null); | |
} | |
} | |
} | |
@Override | |
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { | |
super.onRequestPermissionsResult(requestCode, permissions, grantResults); | |
TextView checkFilePermission = (TextView) findViewById(R.id.checkFilePermission); | |
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){ | |
if(NetworkHelper.isOnline(this)) { | |
getFeedDesigns(null); | |
} | |
checkFilePermission.setVisibility(View.GONE); | |
} else { | |
checkFilePermission.setVisibility(View.VISIBLE); | |
} | |
} | |
public void enableFilePermission(View view) { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) { | |
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); | |
} else { | |
if (NetworkHelper.isOnline(this)) { | |
getFeedDesigns(null); | |
} | |
} | |
} | |
@Override | |
public boolean onCreateOptionsMenu(Menu menu) { | |
MenuInflater inflater = getMenuInflater(); | |
inflater.inflate(R.menu.settings_hypercycle, menu); | |
if (ParseAnonymousUtils.isLinked(ParseUser.getCurrentUser())) //1 is true, 0 is false | |
{ | |
menu.findItem(R.id.action_settings).setVisible(false); | |
} | |
return super.onCreateOptionsMenu(menu); | |
} | |
@Override | |
public boolean onOptionsItemSelected(MenuItem item) { | |
switch (item.getItemId()) { | |
case R.id.action_settings: | |
Intent settingsIntent = new Intent(this, UserSettingsActivity.class); | |
startActivityForResult(settingsIntent, RESULT_SETTINGS); | |
return true; | |
case R.id.action_market: | |
Intent marketIntent = new Intent(this, MarketFeedActivity.class); | |
startActivityForResult(marketIntent, RESULT_MARKETPLACE); | |
return true; | |
default: | |
return super.onOptionsItemSelected(item); | |
} | |
} | |
private void AddRecyclerAdapterClickListeners() { | |
feedRecyclerAdapter.setFeedItemClickListener(new FeedItemClickListener() { | |
@Override | |
public void onTrashClicked(final Feed feedDesign) { | |
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(FeedActivityV2.this); | |
dialogBuilder.setTitle("Confirm Deletion"); | |
dialogBuilder.setMessage("Delete this design?"); | |
dialogBuilder.setPositiveButton("Delete", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
new RemoveDesignFromGalleryAndFeedTask().execute(feedDesign.getDesign().getObjectId()); | |
RemoveFeedDesignFromList(feedDesign.getObjectId()); | |
} | |
}); | |
dialogBuilder.setNegativeButton("Don't Delete", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
} | |
}); | |
AlertDialog alertDialog = dialogBuilder.create(); | |
alertDialog.show(); | |
} | |
@Override | |
public void onSocialShareClicked(Feed feedDesign) { | |
ImageView imageView = (ImageView) recyclerView.findViewById(R.id.image); | |
Drawable mDrawable = imageView.getDrawable(); | |
Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap(); | |
String path = MediaStore.Images.Media.insertImage(getContentResolver(), | |
mBitmap, "Design", null); | |
Uri uri = Uri.parse(path); | |
Intent share = new Intent(Intent.ACTION_SEND); | |
share.setType("image/*"); | |
share.putExtra(Intent.EXTRA_STREAM, uri); | |
share.putExtra(Intent.EXTRA_TEXT, "I found something cool on Hypercycle! " + "http://www.hypercycle.co/"); | |
// Add text to clipboard for social media that does not allow auto-population | |
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); | |
ClipData clip = ClipData.newPlainText("Social Share", "I found something cool on Hypercycle! " + "http://www.hypercycle.co/"); | |
clipboard.setPrimaryClip(clip); | |
Toast.makeText(FeedActivityV2.this, "Copied to clipboard", Toast.LENGTH_LONG).show(); | |
startActivity(Intent.createChooser(share, "Share Your Design!")); | |
} | |
@Override | |
public void onMarketFeedImageLongPressed(Feed feedDesign, Feed.DisplayedSide displayedSide) { | |
switch(displayedSide) { | |
case FRONT: | |
display(feedDesign.getDesign().getCompressedImage().getUrl()); | |
break; | |
case BACK: | |
display(feedDesign.getDesign().getCompressedBackImage().getUrl()); | |
break; | |
} | |
} | |
@Override | |
public void onMarkteFeedImageLongPressed_Release() { | |
remove_fragment(); | |
} | |
@Override | |
public void onBuyClicked(final Feed feedDesign) { | |
} | |
@Override | |
public void onSaveClicked(final Feed feedDesign, final FeedItemView feedItemView) { | |
determineIfRemixable(feedDesign, feedItemView); | |
} | |
@Override | |
public void onLikeClicked(Feed feedDesign, FeedItemView feedItemView) { | |
new LikeDesignTask(getSharedPreferences(MarketFeedActivity.PREFS_NAME, 0)).execute(new LikeDesignWrapper(feedDesign, feedItemView, FeedActivityV2.this)); | |
} | |
// This can stay here because we are not concerned with a SuccessCallback in this case | |
protected ParseObject createEditingMessage(Feed feedDesign) { | |
ParseObject notification = new ParseObject(ParseConstants.CLASS_NOTIFICATIONS); | |
notification.put(ParseConstants.KEY_SENDER_ID, ParseUser.getCurrentUser().getObjectId()); | |
notification.put(ParseConstants.KEY_SENDER_NAME, ParseUser.getCurrentUser().getUsername()); | |
notification.put(ParseConstants.KEY_RECIPIENT_ID, feedDesign.getDesign().getAuthor().getObjectId()); | |
notification.put(ParseConstants.KEY_NOTIFICATION_TEXT, " played with your design."); | |
notification.put(ParseConstants.KEY_SENDER_FEED_OBJECT_ID, feedDesign.getDesign().getObjectId()); | |
notification.put(ParseConstants.KEY_FEED_TYPE, ParseConstants.TYPE_DESIGN); | |
if (ParseUser.getCurrentUser().getParseFile("profilePicture") != null) { | |
notification.put(ParseConstants.KEY_SENDER_PROFILE_PICTURE, ParseUser.getCurrentUser().getParseFile("profilePicture").getUrl()); | |
} | |
notification.put(ParseConstants.KEY_NOTIFICATION_TYPE, ParseConstants.TYPE_EDIT); | |
return notification; | |
} | |
@Override | |
public void onImageDoubleTapped(final Feed feedDesign, final FeedItemView feedItemView) { | |
new LikeDesignTask(getSharedPreferences(MarketFeedActivity.PREFS_NAME, 0)).execute(new LikeDesignWrapper(feedDesign, feedItemView, FeedActivityV2.this)); | |
} | |
@Override | |
public void onAuthorClicked(Feed feedDesign) { | |
startGalleryActivity(feedDesign.getDesign().getAuthor().getObjectId()); | |
} | |
@Override | |
public void onAuthorClicked(String authorId) { | |
startGalleryActivity(authorId); | |
} | |
@Override | |
public void onCreateCommentClicked(Feed feedDesign) { | |
startCommentsActivity(feedDesign.getObjectId()); | |
} | |
@Override | |
public void onCreateEditImageClicked(Feed feedDesign) { | |
if (ParseAnonymousUtils.isLinked(ParseUser.getCurrentUser())) { | |
Toast.makeText(getApplicationContext(), "You must sign up to use this feature.", Toast.LENGTH_LONG).show(); | |
Intent intent = new Intent(getApplicationContext(), ParseLoginActivity.class); | |
startActivity(intent); | |
} else { | |
new DownloadDesignAndLaunchCustomizerTask(CustomizerLaunchPage.DESIGNER).execute(feedDesign.getDesign()); | |
// initiate installation query | |
ParseQuery<ParseInstallation> query = ParseInstallation.getQuery(); | |
query.whereEqualTo("userId", feedDesign.getDesign().getAuthor().getObjectId()); | |
System.out.println(feedDesign.getDesign().getAuthor().getObjectId()); | |
if (ParseUser.getCurrentUser() == null) { | |
// Do nothing | |
Log.e(TAG, "Current user is null. Do nothing"); | |
} else if (!feedDesign.getDesign().getAuthor().getObjectId().equals(ParseUser.getCurrentUser().getObjectId())) { | |
// send push notification | |
ParsePush push = new ParsePush(); | |
push.setQuery(query); | |
push.setMessage(getString(R.string.push_edit, ParseUser.getCurrentUser().getUsername())); | |
push.sendInBackground(); | |
// send notification to NotificationsActivity | |
createEditingMessage(feedDesign).saveInBackground(); | |
} | |
} | |
} | |
@Override | |
public void onProfilePictureClicked(Feed feedDesign) { | |
startGalleryActivity(feedDesign.getDesign().getAuthor().getObjectId()); | |
} | |
// @Override | |
// public void onFitDesignImageClicked(FeedItem feedItem, int position) { | |
// new DownloadDesignAndLaunchCustomizerTask(CustomizerLaunchPage.TEMPLATE, position).execute(feedItem.getDesign()); | |
// } | |
}); | |
} | |
public void remove_fragment(){ | |
Fragment f = getSupportFragmentManager().findFragmentByTag("dialog"); | |
if (f!=null){ | |
getSupportFragmentManager().beginTransaction().remove(f).commit(); | |
} | |
} | |
public void display(String url) { | |
BlurDialogFragment fragment = BlurDialogFragment.newInstance(url,this); | |
fragment.show(getSupportFragmentManager(), "dialog"); | |
} | |
private void determineIfRemixable(Feed feedDesign, FeedItemView feedItemView) { | |
final ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Design"); | |
query.whereEqualTo("objectId", feedDesign.getDesign().getObjectId()); | |
String canRemix = null; | |
try { | |
List<ParseObject> results = query.find(); | |
canRemix = results.get(0).getString("isRemixable"); | |
} catch (ParseException e) { | |
e.printStackTrace(); | |
} | |
System.out.println(canRemix); | |
if (canRemix == null || !canRemix.equals("false")) { | |
new SaveDesignTask(getSharedPreferences(MarketFeedActivity.PREFS_NAME, 0)).execute(new SaveDesignWrapper(feedDesign, feedItemView, this)); | |
} else { | |
if (ParseUser.getCurrentUser().getObjectId().equals(feedDesign.getDesign().getAuthor().getObjectId())) { | |
Toast.makeText(getApplicationContext(), "Your design can no longer be remixed.", Toast.LENGTH_SHORT).show(); | |
} else { | |
Toast.makeText(getApplicationContext(), feedDesign.getDesign().getAuthor().getUsername() + " has disabled remixing for this design.", Toast.LENGTH_SHORT).show(); | |
} | |
} | |
} | |
// from the activities view xml | |
public void LaunchCustomizer(View view) { | |
view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.image_click)); | |
if (ParseAnonymousUtils.isLinked(ParseUser.getCurrentUser())) { | |
Toast.makeText(getApplicationContext(), "You must sign up to use this feature.", Toast.LENGTH_LONG).show(); | |
Intent logOut = new Intent(this, ParseLoginActivity.class); | |
startActivity(logOut); | |
} else { | |
Intent intent = new Intent(this, MainActivity.class); | |
intent.putExtra("DesignerFragment", true); | |
startActivity(intent); | |
} | |
} | |
public void LaunchSearch(View view) { | |
view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.image_click)); | |
startActivity(new Intent(this, SearchActivity.class)); | |
} | |
public void LaunchNotificationsActivity(View view) { | |
view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.image_click)); | |
startActivity(new Intent(this, NotificationsActivity.class)); | |
} | |
public void LaunchPersonalGallery(View view) { | |
view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.image_click)); | |
startActivity(new Intent(this, GalleryActivity.class)); | |
} | |
public void startGalleryActivity(String userId) { | |
if(userId == null || userId.isEmpty()) { | |
return; | |
} | |
Intent intent = new Intent(this, GalleryActivity.class); | |
intent.putExtra(MainActivity.SELECTED_USER_OBJECT_ID, userId); | |
startActivity(intent); | |
} | |
public void startCommentsActivity(String feedId) { | |
if(feedId == null || feedId.isEmpty()) { | |
return; | |
} | |
Intent intent = new Intent(this, CommentsActivity.class); | |
intent.putExtra(MainActivity.SELECTED_FEED_OBJECT_ID, feedId); | |
this.startActivity(intent); | |
} | |
// just helps to show the progress modal, with specified message | |
private void ShowProgressDialog(String message) { | |
progress = new ProgressDialog(this); | |
progress.setMessage(message); | |
progress.setCancelable(true); | |
progress.setCanceledOnTouchOutside(true); | |
progress.show(); | |
} | |
private class DownloadDesignAndLaunchCustomizerTask extends AsyncTask<com.elgami.network.model.Design, Void, Uri> { | |
private com.elgami.network.model.Design design; | |
private CustomizerLaunchPage launchPage; | |
private int position; | |
public DownloadDesignAndLaunchCustomizerTask(CustomizerLaunchPage launchPage) { | |
this.launchPage = launchPage; | |
} | |
public DownloadDesignAndLaunchCustomizerTask(CustomizerLaunchPage launchPage, int position) { | |
this.launchPage = launchPage; | |
this.position = position; | |
} | |
@Override | |
protected void onPreExecute() { | |
ShowProgressDialog(getResources().getString(R.string.loading_design)); | |
} | |
@Override | |
protected Uri doInBackground(com.elgami.network.model.Design... params) { | |
this.design = params[0]; | |
return designImageLoader.getImageURIWithDownload(design.getImage().getUrl()); | |
} | |
@Override | |
protected void onPostExecute(Uri uri) { | |
progress.dismiss(); | |
if(uri == null) { | |
Toast.makeText(FeedActivityV2.this, R.string.failed_to_customize_design, Toast.LENGTH_LONG).show(); | |
} else { | |
Log.d(TAG, design.getImage().getUrl()); | |
CreateIntentForCustomizer(FeedActivityV2.this, uri, design.getObjectId(), launchPage, position); | |
} | |
} | |
} | |
// create an intent for the customizer, setting extras based on the page we are launching to | |
private void CreateIntentForCustomizer(Context context, Uri uri, String designIdBase, CustomizerLaunchPage launchPage, int position) { | |
Intent intent = new Intent(context, MainActivity.class); | |
switch (launchPage) { | |
case TEMPLATE: | |
intent.putExtra(MainActivity.TEMPLATE_TYPE, MainActivity.ProductType.values()[position - 1]); | |
// intentionally falls through ... | |
case DESIGNER: | |
intent.putExtra(MainActivity.SELECTED_IMAGE_MESSAGE, uri.toString()); | |
intent.putExtra(MainActivity.DESIGN_ID_BASE, designIdBase); | |
startActivity(intent); | |
break; | |
} | |
} | |
public void RemoveFeedDesignFromList(String feedObjectId) { | |
int indexForDeletion = -1; | |
for(int i = 0; i < feedItems.size(); i++) { | |
if(feedItems.get(i).getObjectId().equals(feedObjectId)) { | |
indexForDeletion = i; | |
} | |
} | |
if(indexForDeletion != -1) { | |
feedItems.remove(indexForDeletion); | |
if(feedRecyclerAdapter != null) { | |
feedRecyclerAdapter.notifyItemRemoved(indexForDeletion); | |
} | |
} | |
} | |
@Override | |
public void onRefresh() { | |
boolean isOnline = NetworkHelper.isOnline(this); | |
// turn off refreshing and return if not online or if already updating | |
if (!isOnline || isUpdating) { | |
((SwipeRefreshLayout) findViewById(R.id.swipe_container)).setRefreshing(false); | |
findViewById(R.id.networkOffline).setVisibility(isOnline ? View.GONE : View.VISIBLE); | |
findViewById(R.id.networkOfflineText).setVisibility(isOnline ? View.GONE : View.VISIBLE); | |
return; | |
} | |
// TODO temporary fix so we always re-load the whole list of feed items on pull to refresh | |
// see PrependDataTask | |
isUpdating = true; | |
feedItems.clear(); | |
// if we hadn't actually gathered anything yet, do an append. | |
// otherwise, do a prepend | |
if (feedItems.isEmpty()) { | |
getFeedDesigns(null); | |
} | |
} | |
private RetrofitParseRequestManager mRetrofitParseRequestManager; | |
private Subscription mFeedDesignsSubscription; | |
private boolean hasItems; | |
private void getFeedDesigns(Date date) { | |
hasItems = false; | |
feedRecyclerAdapter.toggleLoadingRowOn(); | |
mFeedDesignsSubscription = mRetrofitParseRequestManager.getFeedDesigns(date) | |
.map(feedDesign -> { | |
feedDesign.setTimestampText(FeedUtils.MSToDate(new Date().getTime() - feedDesign.getCreatedAt().getTime())); | |
feedDesign.setInPersonalGallery(UserStateProvider.getDesignIds(getSharedPreferences(MarketFeedActivity.PREFS_NAME, 0)).contains(feedDesign.getDesign().getObjectId())); | |
feedDesign.setLiked(UserStateProvider.getLikeIds(getSharedPreferences(MarketFeedActivity.PREFS_NAME, 0)).contains(feedDesign.getDesign().getObjectId())); | |
return feedDesign; | |
}) | |
.flatMap(feedDesign -> { | |
return mRetrofitParseRequestManager.getTopThreeComments(feedDesign.getObjectId()) | |
.map((Func1<List<Comment>, Feed>) comments -> { | |
feedDesign.setComments(comments); | |
return feedDesign; | |
}); | |
}) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribeOn(Schedulers.io()) | |
.subscribe( | |
feedDesign -> { | |
feedRecyclerAdapter.toggleLoadingRowOff(); | |
hasItems = true; | |
feedItems.add(feedDesign); | |
feedRecyclerAdapter.notifyItemInserted(feedItems.size() - 1); | |
SavePostTimes(feedItems); | |
}, | |
throwable -> { | |
Log.d(TAG, throwable.toString()); | |
// TODO handle error display | |
}, | |
() -> { | |
if(!hasItems) { moreRecords = false; } | |
lastRefresh = new Date(); | |
isUpdating = false; | |
((SwipeRefreshLayout) findViewById(R.id.swipe_container)).setRefreshing(false); | |
feedRecyclerAdapter.toggleLoadingRowOff(); | |
}); | |
} | |
private void SavePostTimes(List<Feed> results) { | |
// get the first element to set our latest (newest) record timestamp | |
// only if it has not yet been defined (i.e. first set) | |
if(latestPostTime == null) { | |
Date newLatestPostTime = results.get(0).getCreatedAt(); | |
if (newLatestPostTime != null) { | |
latestPostTime = results.get(0).getCreatedAt(); | |
Log.d(TAG, "latestPostTime " + latestPostTime.toString()); | |
} | |
} | |
Date newSetEndPostTime = results.get(results.size() - 1).getCreatedAt(); | |
if (newSetEndPostTime != null) { | |
setEndPostTime = results.get(results.size() - 1).getCreatedAt(); // always set the set end time to the last result in this query, so we can append more starting here later | |
Log.d(TAG, "setEndPostTime " + setEndPostTime.toString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment