Browse Source

Merge pull request #43 from ThmmyNoLife/page_indicator_fix

Page indicator fix
pull/44/head
oogee 6 years ago
committed by GitHub
parent
commit
6b57927b6e
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 351
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java
  2. 32
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicAdapter.java
  3. 2
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/DeleteTask.java
  4. 13
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/PrepareForReply.java
  5. 8
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/PrepareForReplyResult.java
  6. 53
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTask.java
  7. 31
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTaskResult.java
  8. 15
      app/src/main/java/gr/thmmy/mthmmy/utils/ScrollAwareFABBehavior.java
  9. 17
      app/src/main/java/gr/thmmy/mthmmy/utils/ScrollAwareLinearBehavior.java
  10. 20
      app/src/main/java/gr/thmmy/mthmmy/utils/parsing/ParseHelpers.java
  11. 188
      app/src/main/java/gr/thmmy/mthmmy/viewmodel/TopicViewModel.java
  12. 10
      app/src/main/res/layout/activity_topic.xml
  13. 4
      app/src/main/res/values/strings.xml

351
app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java

@ -11,6 +11,7 @@ import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.RecyclerView;
@ -30,7 +31,6 @@ import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Objects;
import gr.thmmy.mthmmy.R;
import gr.thmmy.mthmmy.activities.topic.tasks.DeleteTask;
@ -45,6 +45,7 @@ import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.model.ThmmyPage;
import gr.thmmy.mthmmy.utils.CustomLinearLayoutManager;
import gr.thmmy.mthmmy.utils.HTMLUtils;
import gr.thmmy.mthmmy.utils.parsing.ParseHelpers;
import gr.thmmy.mthmmy.viewmodel.TopicViewModel;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar;
import timber.log.Timber;
@ -58,9 +59,7 @@ import static gr.thmmy.mthmmy.services.NotificationService.NEW_POST_TAG;
* key {@link #BUNDLE_TOPIC_TITLE} for faster title rendering.
*/
@SuppressWarnings("unchecked")
public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskObserver,
DeleteTask.DeleteTaskCallbacks, ReplyTask.ReplyTaskCallbacks, PrepareForEditTask.PrepareForEditCallbacks,
EditTask.EditTaskCallbacks, PrepareForReply.PrepareForReplyCallbacks, TopicAdapter.OnPostFocusChangeListener {
public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFocusChangeListener {
//Activity's variables
/**
* The key to use when putting topic's url String to {@link TopicActivity}'s Bundle.
@ -103,11 +102,6 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
* long click is held in either first or last buttons
*/
private static final int LARGE_STEP = 10;
/**
* Holds the value (index) of the page to be requested when a user interaction with bottom
* navigation bar occurs
*/
private Integer pageRequestValue;
//Bottom navigation bar graphics related
private LinearLayout bottomNavBar;
@ -116,6 +110,7 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
private TextView pageIndicator;
private ImageButton nextPage;
private ImageButton lastPage;
private Snackbar snackbar;
private TopicViewModel viewModel;
//Fix for vector drawables on android <21
@ -129,14 +124,9 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_topic);
// get TopicViewModel instance
viewModel = ViewModelProviders.of(this).get(TopicViewModel.class);
viewModel.setTopicTaskObserver(this);
viewModel.setDeleteTaskCallbacks(this);
viewModel.setReplyFinishListener(this);
viewModel.setPrepareForEditCallbacks(this);
viewModel.setEditTaskCallbacks(this);
viewModel.setPrepareForReplyCallbacks(this);
subscribeUI();
Bundle extras = getIntent().getExtras();
String topicTitle = extras.getString(BUNDLE_TOPIC_TITLE);
@ -206,81 +196,7 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
paginationEnabled(false);
viewModel.getTopicTaskResult().observe(this, topicTaskResult -> {
if (topicTaskResult == null) {
progressBar.setVisibility(ProgressBar.VISIBLE);
} else {
switch (topicTaskResult.getResultCode()) {
case SUCCESS:
if (topicTitle == null || Objects.equals(topicTitle, "")
|| !Objects.equals(topicTitle, topicTaskResult.getTopicTitle())) {
toolbarTitle.setText(topicTaskResult.getTopicTitle());
}
recyclerView.getRecycledViewPool().clear(); //Avoid inconsistency detected bug
postsList.clear();
postsList.addAll(topicTaskResult.getNewPostsList());
topicAdapter.notifyDataSetChanged();
pageIndicator.setText(String.valueOf(topicTaskResult.getCurrentPageIndex()) + "/" +
String.valueOf(topicTaskResult.getPageCount()));
pageRequestValue = topicTaskResult.getCurrentPageIndex();
paginationEnabled(true);
if (topicTaskResult.getCurrentPageIndex() == topicTaskResult.getPageCount()) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null)
notificationManager.cancel(NEW_POST_TAG, topicTaskResult.getLoadedPageTopicId());
}
progressBar.setVisibility(ProgressBar.GONE);
if (topicTaskResult.getReplyPageUrl() == null)
replyFAB.hide();
else
replyFAB.show();
recyclerView.scrollToPosition(topicTaskResult.getFocusedPostIndex());
break;
case NETWORK_ERROR:
Toast.makeText(getBaseContext(), "Network Error", Toast.LENGTH_SHORT).show();
break;
case UNAUTHORIZED:
progressBar.setVisibility(ProgressBar.GONE);
Toast.makeText(getBaseContext(), "This topic is either missing or off limits to you", Toast.LENGTH_SHORT).show();
break;
default:
//Parse failed - should never happen
Timber.d("Parse failed!"); //TODO report ParseException!!!
Toast.makeText(getBaseContext(), "Fatal Error", Toast.LENGTH_SHORT).show();
finish();
break;
}
}
});
viewModel.getPrepareForReplyResult().observe(this, prepareForReplyResult -> {
if (prepareForReplyResult != null) {
//prepare for a reply
postsList.add(Post.newQuickReply());
topicAdapter.notifyItemInserted(postsList.size());
recyclerView.scrollToPosition(postsList.size() - 1);
progressBar.setVisibility(ProgressBar.GONE);
replyFAB.hide();
bottomNavBar.setVisibility(View.GONE);
}
});
viewModel.getPrepareForEditResult().observe(this, result -> {
if (result != null && result.isSuccessful()) {
viewModel.setEditingPost(true);
postsList.get(result.getPosition()).setPostType(Post.TYPE_EDIT);
topicAdapter.notifyItemChanged(result.getPosition());
recyclerView.scrollToPosition(result.getPosition());
progressBar.setVisibility(ProgressBar.GONE);
replyFAB.hide();
bottomNavBar.setVisibility(View.GONE);
}
});
viewModel.initialLoad(topicPageUrl);
viewModel.loadUrl(topicPageUrl);
}
@Override
@ -310,18 +226,14 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
TextView usersViewing = infoDialog.findViewById(R.id.users_viewing);
usersViewing.setText(new SpannableStringBuilder("Loading..."));
usersViewing.setMovementMethod(LinkMovementMethod.getInstance());
viewModel.getTopicTaskResult().observe(this, topicTaskResult -> {
if (topicTaskResult == null) {
usersViewing.setText(new SpannableStringBuilder("Loading..."));
treeAndMods.setText(new SpannableStringBuilder("Loading..."));
} else {
String treeAndModsString = topicTaskResult.getTopicTreeAndMods();
treeAndMods.setText(HTMLUtils.getSpannableFromHtml(this, treeAndModsString));
String topicViewersString = topicTaskResult.getTopicViewers();
usersViewing.setText(HTMLUtils.getSpannableFromHtml(this, topicViewersString));
}
viewModel.getTopicTreeAndMods().observe(this, topicTreeAndMods -> {
if (topicTreeAndMods == null) return;
treeAndMods.setText(HTMLUtils.getSpannableFromHtml(this, topicTreeAndMods));
});
viewModel.getTopicViewers().observe(this, topicViewers -> {
if (topicViewers == null) return;
usersViewing.setText(HTMLUtils.getSpannableFromHtml(this, topicViewers));
});
builder.setView(infoDialog);
AlertDialog dialog = builder.create();
dialog.show();
@ -400,10 +312,10 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
public void run() {
long REPEAT_DELAY = 250;
if (autoIncrement) {
incrementPageRequestValue(step);
viewModel.incrementPageRequestValue(step, false);
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(step), REPEAT_DELAY);
} else if (autoDecrement) {
decrementPageRequestValue(step);
viewModel.decrementPageRequestValue(step, false);
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(step), REPEAT_DELAY);
}
}
@ -443,11 +355,9 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
// Increment once for a click
increment.setOnClickListener(v -> {
if (!autoIncrement && step == LARGE_STEP) {
incrementPageRequestValue(viewModel.getPageCount());
viewModel.changePage(viewModel.getPageCount() - 1);
viewModel.setPageIndicatorIndex(viewModel.getPageCount(), true);
} else if (!autoIncrement) {
incrementPageRequestValue(step);
viewModel.changePage(pageRequestValue - 1);
viewModel.incrementPageRequestValue(step, true);
}
});
@ -471,11 +381,11 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
} else if (rect != null && event.getAction() == MotionEvent.ACTION_UP && autoIncrement) {
autoIncrement = false;
paginationEnabled(true);
viewModel.changePage(pageRequestValue - 1);
viewModel.performPageChange();
} else if (rect != null && event.getAction() == MotionEvent.ACTION_MOVE) {
if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) {
autoIncrement = false;
decrementPageRequestValue(pageRequestValue - viewModel.getCurrentPageIndex());
viewModel.setPageIndicatorIndex(viewModel.getCurrentPageIndex(), false);
paginationEnabled(true);
}
}
@ -489,11 +399,9 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
// Decrement once for a click
decrement.setOnClickListener(v -> {
if (!autoDecrement && step == LARGE_STEP) {
decrementPageRequestValue(viewModel.getPageCount());
viewModel.changePage(0);
viewModel.setPageIndicatorIndex(1, true);
} else if (!autoDecrement) {
decrementPageRequestValue(step);
viewModel.changePage(pageRequestValue - 1);
viewModel.decrementPageRequestValue(step, true);
}
});
@ -517,12 +425,12 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
} else if (event.getAction() == MotionEvent.ACTION_UP && autoDecrement) {
autoDecrement = false;
paginationEnabled(true);
viewModel.changePage(pageRequestValue - 1);
viewModel.performPageChange();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (rect != null &&
!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) {
autoIncrement = false;
incrementPageRequestValue(viewModel.getCurrentPageIndex() - pageRequestValue);
viewModel.setPageIndicatorIndex(viewModel.getCurrentPageIndex(), false);
paginationEnabled(true);
}
}
@ -531,34 +439,42 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
});
}
private void incrementPageRequestValue(int step) {
if (pageRequestValue < viewModel.getPageCount() - step) {
pageRequestValue = pageRequestValue + step;
} else
pageRequestValue = viewModel.getPageCount();
pageIndicator.setText(pageRequestValue + "/" + String.valueOf(viewModel.getPageCount()));
}
private void decrementPageRequestValue(int step) {
if (pageRequestValue > step)
pageRequestValue = pageRequestValue - step;
else
pageRequestValue = 1;
pageIndicator.setText(pageRequestValue + "/" + String.valueOf(viewModel.getPageCount()));
}
//------------------------------------BOTTOM NAV BAR METHODS END------------------------------------
/**
* Binds the UI to its data
*/
private void subscribeUI() {
// Implement async task callbacks
viewModel.setTopicTaskObserver(new TopicTask.TopicTaskObserver() {
@Override
public void onTopicTaskStarted() {
progressBar.setVisibility(ProgressBar.VISIBLE);
if (snackbar != null) snackbar.dismiss();
}
@Override
public void onTopicTaskCancelled() {
progressBar.setVisibility(ProgressBar.GONE);
}
});
viewModel.setDeleteTaskCallbacks(new DeleteTask.DeleteTaskCallbacks() {
@Override
public void onDeleteTaskStarted() {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
@Override
public void onDeleteTaskFinished(boolean result) {
progressBar.setVisibility(ProgressBar.GONE);
if (result)
viewModel.reloadPage();
else
Toast.makeText(getBaseContext(), "Delete failed!", Toast.LENGTH_SHORT).show();
}
});
viewModel.setReplyFinishListener(new ReplyTask.ReplyTaskCallbacks() {
@Override
public void onReplyTaskStarted() {
progressBar.setVisibility(ProgressBar.VISIBLE);
@ -572,85 +488,180 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
postsList.remove(postsList.size() - 1);
topicAdapter.notifyItemRemoved(postsList.size());
progressBar.setVisibility(ProgressBar.GONE);
if (success) {
replyFAB.show();
bottomNavBar.setVisibility(View.VISIBLE);
viewModel.setWritingReply(false);
if (success) {
if ((postsList.get(postsList.size() - 1).getPostNumber() + 1) % 15 == 0) {
viewModel.loadUrl(viewModel.getBaseUrl() + "." + 2147483647);
viewModel.loadUrl(ParseHelpers.getBaseURL(viewModel.getTopicUrl()) + "." + 2147483647);
} else {
viewModel.reloadPage();
}
} else {
Toast.makeText(TopicActivity.this, "Post failed!", Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(), "Post failed!", Toast.LENGTH_SHORT).show();
recyclerView.getChildAt(postsList.size() - 1).setAlpha(1);
recyclerView.getChildAt(postsList.size() - 1).setEnabled(true);
}
}
});
viewModel.setPrepareForEditCallbacks(new PrepareForEditTask.PrepareForEditCallbacks() {
@Override
public void onPrepareForReplyStarted() {
public void onPrepareEditStarted() {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
@Override
public void onPrepareForReplyCancelled() {
public void onPrepareEditCancelled() {
progressBar.setVisibility(ProgressBar.GONE);
}
});
viewModel.setEditTaskCallbacks(new EditTask.EditTaskCallbacks() {
@Override
public void onDeleteTaskStarted() {
public void onEditTaskStarted() {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
@Override
public void onDeleteTaskFinished(boolean result) {
public void onEditTaskFinished(boolean result, int position) {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
progressBar.setVisibility(ProgressBar.GONE);
if (result) {
postsList.get(position).setPostType(Post.TYPE_POST);
topicAdapter.notifyItemChanged(position);
replyFAB.show();
bottomNavBar.setVisibility(View.VISIBLE);
viewModel.setEditingPost(false);
viewModel.reloadPage();
} else {
Toast.makeText(TopicActivity.this, "Post deleted!", Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(), "Edit failed!", Toast.LENGTH_SHORT).show();
recyclerView.getChildAt(viewModel.getPostBeingEditedPosition()).setAlpha(1);
recyclerView.getChildAt(viewModel.getPostBeingEditedPosition()).setEnabled(true);
}
}
});
viewModel.setPrepareForReplyCallbacks(new PrepareForReply.PrepareForReplyCallbacks() {
@Override
public void onPrepareEditStarted() {
public void onPrepareForReplyStarted() {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
@Override
public void onPrepareEditCancelled() {
public void onPrepareForReplyCancelled() {
progressBar.setVisibility(ProgressBar.GONE);
}
@Override
public void onEditTaskStarted() {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
@Override
public void onEditTaskFinished(boolean result, int position) {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
});
// observe the chages in data
viewModel.getPageIndicatorIndex().observe(this, pageIndicatorIndex -> {
if (pageIndicatorIndex == null) return;
pageIndicator.setText(String.valueOf(pageIndicatorIndex) + "/" +
String.valueOf(viewModel.getPageCount()));
});
viewModel.getTopicTitle().observe(this, newTopicTitle -> {
if (newTopicTitle == null) return;
if (!TextUtils.equals(toolbarTitle.getText(), newTopicTitle))
toolbarTitle.setText(newTopicTitle);
});
viewModel.getPageTopicId().observe(this, pageTopicId -> {
if (pageTopicId == null) return;
if (viewModel.getCurrentPageIndex() == viewModel.getPageCount()) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null)
notificationManager.cancel(NEW_POST_TAG, pageTopicId);
}
postsList.get(position).setPostType(Post.TYPE_POST);
topicAdapter.notifyItemChanged(position);
viewModel.setEditingPost(false);
progressBar.setVisibility(ProgressBar.GONE);
});
viewModel.getReplyPageUrl().observe(this, replyPageUrl -> {
if (replyPageUrl == null)
replyFAB.hide();
else
replyFAB.show();
bottomNavBar.setVisibility(View.VISIBLE);
if (result) {
});
viewModel.getPostsList().observe(this, postList -> {
if (postList == null) progressBar.setVisibility(ProgressBar.VISIBLE);
recyclerView.getRecycledViewPool().clear(); //Avoid inconsistency detected bug
postsList.clear();
postsList.addAll(postList);
topicAdapter.notifyDataSetChanged();
});
viewModel.getFocusedPostIndex().observe(this, focusedPostIndex -> {
if (focusedPostIndex == null) return;
recyclerView.scrollToPosition(focusedPostIndex);
});
viewModel.getTopicTaskResultCode().observe(this, resultCode -> {
if (resultCode == null) return;
progressBar.setVisibility(ProgressBar.GONE);
switch (resultCode) {
case SUCCESS:
paginationEnabled(true);
break;
case NETWORK_ERROR:
if (viewModel.getPostsList().getValue() == null) {
// no page has been loaded yet. Give user the ability to refresh
recyclerView.setVisibility(View.GONE);
TextView errorTextview = findViewById(R.id.error_textview);
errorTextview.setText(getString(R.string.network_error_retry_prompt));
errorTextview.setVisibility(View.VISIBLE);
errorTextview.setOnClickListener(view -> {
viewModel.reloadPage();
errorTextview.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
});
} else {
Toast.makeText(TopicActivity.this, "Edit failed!", Toast.LENGTH_SHORT).show();
// a page has already been loaded
viewModel.setPageIndicatorIndex(viewModel.getCurrentPageIndex(), false);
snackbar = Snackbar.make(findViewById(R.id.main_content),
R.string.generic_network_error, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction(R.string.retry, view -> viewModel.reloadPage());
snackbar.show();
}
break;
case UNAUTHORIZED:
recyclerView.setVisibility(View.GONE);
TextView errorTextview = findViewById(R.id.error_textview);
errorTextview.setText(getString(R.string.unauthorized_topic_error));
errorTextview.setVisibility(View.VISIBLE);
break;
default:
//Parse failed - should never happen
Timber.d("Parse failed!"); //TODO report ParseException!!!
Toast.makeText(getBaseContext(), "Fatal Error", Toast.LENGTH_SHORT).show();
finish();
break;
}
});
viewModel.getPrepareForReplyResult().observe(this, prepareForReplyResult -> {
progressBar.setVisibility(ProgressBar.GONE);
if (prepareForReplyResult != null && prepareForReplyResult.isSuccessful()) {
//prepare for a reply
viewModel.setWritingReply(true);
postsList.add(Post.newQuickReply());
topicAdapter.notifyItemInserted(postsList.size());
recyclerView.scrollToPosition(postsList.size() - 1);
replyFAB.hide();
bottomNavBar.setVisibility(View.GONE);
} else {
Snackbar.make(findViewById(R.id.main_content), getString(R.string.generic_network_error), Snackbar.LENGTH_SHORT).show();
}
});
viewModel.getPrepareForEditResult().observe(this, result -> {
progressBar.setVisibility(ProgressBar.GONE);
if (result != null && result.isSuccessful()) {
viewModel.setEditingPost(true);
postsList.get(result.getPosition()).setPostType(Post.TYPE_EDIT);
topicAdapter.notifyItemChanged(result.getPosition());
recyclerView.scrollToPosition(result.getPosition());
replyFAB.hide();
bottomNavBar.setVisibility(View.GONE);
} else {
Snackbar.make(findViewById(R.id.main_content), getString(R.string.generic_network_error), Snackbar.LENGTH_SHORT).show();
}
});
}
}

32
app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicAdapter.java

@ -46,6 +46,7 @@ import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.model.ThmmyFile;
import gr.thmmy.mthmmy.model.ThmmyPage;
import gr.thmmy.mthmmy.utils.CircleTransform;
import gr.thmmy.mthmmy.utils.parsing.ParseHelpers;
import gr.thmmy.mthmmy.viewmodel.TopicViewModel;
import timber.log.Timber;
@ -452,7 +453,7 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
.transform(new CircleTransform())
.into(holder.thumbnail);
holder.username.setText(getSessionManager().getUsername());
holder.quickReplySubject.setText("Re: " + viewModel.getTopicTitle());
holder.quickReplySubject.setText("Re: " + viewModel.getTopicTitle().getValue());
holder.quickReply.setText(viewModel.getBuildedQuotes());
@ -460,15 +461,13 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
holder.submitButton.setOnClickListener(view -> {
if (holder.quickReplySubject.getText().toString().isEmpty()) return;
if (holder.quickReply.getText().toString().isEmpty()) return;
holder.submitButton.setEnabled(false);
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
holder.itemView.setAlpha(0.5f);
holder.itemView.setEnabled(false);
viewModel.postReply(context, holder.quickReplySubject.getText().toString(),
holder.quickReply.getText().toString());
holder.quickReplySubject.getText().clear();
holder.quickReplySubject.setText("Re: " + viewModel.getTopicTitle());
holder.quickReply.getText().clear();
holder.submitButton.setEnabled(true);
});
@ -498,13 +497,12 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
holder.submitButton.setOnClickListener(view -> {
if (holder.editSubject.getText().toString().isEmpty()) return;
if (holder.editMessage.getText().toString().isEmpty()) return;
holder.submitButton.setEnabled(false);
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
holder.itemView.setAlpha(0.5f);
holder.itemView.setEnabled(false);
viewModel.editPost(position, holder.editSubject.getText().toString(), holder.editMessage.getText().toString());
holder.editSubject.getText().clear();
holder.editSubject.setText(postsList.get(position).getSubject());
holder.submitButton.setEnabled(true);
});
if (backPressHidden) {
@ -636,8 +634,7 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
if (target.is(ThmmyPage.PageCategory.TOPIC)) {
//This url points to a topic
//Checks if the page to be loaded is the one already shown
if (uriString.contains(viewModel.getBaseUrl())) {
Timber.e("reached here!");
if (uriString.contains(ParseHelpers.getBaseURL(viewModel.getTopicUrl()))) {
if (uriString.contains("topicseen#new") || uriString.contains("#new")) {
if (viewModel.getCurrentPageIndex() == viewModel.getPageCount()) {
//same page
@ -651,7 +648,6 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
if (tmpUrlSbstr.contains("msg"))
tmpUrlSbstr = tmpUrlSbstr.substring(0, tmpUrlSbstr.indexOf("msg") - 1);
int testAgainst = Integer.parseInt(tmpUrlSbstr);
Timber.e("reached tthere! %s", testAgainst);
for (int i = 0; i < postsList.size(); i++) {
if (postsList.get(i).getPostIndex() == testAgainst) {
//same page
@ -660,11 +656,11 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
return true;
}
}
} else if ((Objects.equals(uriString, viewModel.getBaseUrl()) && viewModel.getCurrentPageIndex() == 1) ||
Integer.parseInt(uriString.substring(viewModel.getBaseUrl().length() + 1)) / 15 + 1 ==
} else if ((Objects.equals(uriString, ParseHelpers.getBaseURL(viewModel.getTopicUrl())) &&
viewModel.getCurrentPageIndex() == 1) ||
Integer.parseInt(uriString.substring(ParseHelpers.getBaseURL(viewModel.getTopicUrl()).length() + 1)) / 15 + 1 ==
viewModel.getCurrentPageIndex()) {
//same page
Timber.e("ha");
return true;
}
}

2
app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/DeleteTask.java

@ -41,7 +41,7 @@ public class DeleteTask extends AsyncTask<String, Void, Boolean> {
return true;
default:
Timber.e("Something went wrong. Request string: %s", delete.toString());
return true;
return false;
}
} catch (IOException e) {
Timber.e(e, "Delete failed.");

13
app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/PrepareForReply.java

@ -33,18 +33,13 @@ public class PrepareForReply extends AsyncTask<Integer, Void, PrepareForReplyRes
@Override
protected PrepareForReplyResult doInBackground(Integer... postIndices) {
String numReplies = null;
String seqnum = null;
String sc = null;
String topic = null;
StringBuilder buildedQuotes = new StringBuilder("");
Document document;
Request request = new Request.Builder()
.url(replyPageUrl + ";wap2")
.build();
OkHttpClient client = BaseApplication.getInstance().getClient();
String numReplies, seqnum, sc, topic;
try {
Response response = client.newCall(request).execute();
document = Jsoup.parse(response.body().string());
@ -55,14 +50,15 @@ public class PrepareForReply extends AsyncTask<Integer, Void, PrepareForReplyRes
topic = document.select("input[name=topic]").first().attr("value");
} catch (IOException | Selector.SelectorParseException e) {
Timber.e(e, "Prepare failed.");
return new PrepareForReplyResult(false, null, null, null, null, null);
}
StringBuilder buildedQuotes = new StringBuilder("");
for (Integer postIndex : postIndices) {
request = new Request.Builder()
.url("https://www.thmmy.gr/smf/index.php?action=quotefast;quote=" +
postIndex + ";" + "sesc=" + sc + ";xml")
.build();
try {
Response response = client.newCall(request).execute();
String body = response.body().string();
@ -70,9 +66,10 @@ public class PrepareForReply extends AsyncTask<Integer, Void, PrepareForReplyRes
buildedQuotes.append("\n\n");
} catch (IOException | Selector.SelectorParseException e) {
Timber.e(e, "Quote building failed.");
return new PrepareForReplyResult(false, null, null, null, null, null);
}
}
return new PrepareForReplyResult(numReplies, seqnum, sc, topic, buildedQuotes.toString());
return new PrepareForReplyResult(true, numReplies, seqnum, sc, topic, buildedQuotes.toString());
}
@Override

8
app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/PrepareForReplyResult.java

@ -2,9 +2,11 @@ package gr.thmmy.mthmmy.activities.topic.tasks;
public class PrepareForReplyResult {
private final String numReplies, seqnum, sc, topic, buildedQuotes;
private boolean successful;
public PrepareForReplyResult(String numReplies, String seqnum, String sc, String topic, String buildedQuotes) {
public PrepareForReplyResult(boolean successful, String numReplies, String seqnum, String sc, String topic, String buildedQuotes) {
this.successful = successful;
this.numReplies = numReplies;
this.seqnum = seqnum;
this.sc = sc;
@ -31,4 +33,8 @@ public class PrepareForReplyResult {
public String getBuildedQuotes() {
return buildedQuotes;
}
public boolean isSuccessful() {
return successful;
}
}

53
app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTask.java

@ -43,18 +43,6 @@ public class TopicTask extends AsyncTask<String, Void, TopicTaskResult> {
@Override
protected TopicTaskResult doInBackground(String... strings) {
String topicTitle = null;
String topicTreeAndMods = "";
String topicViewers = "";
ArrayList<Post> newPostsList = null;
int loadedPageTopicId = -1;
int focusedPostIndex = 0;
SparseArray<String> pagesUrls = new SparseArray<>();
int currentPageIndex = 1;
int pageCount = 1;
String baseUrl = "";
String lastPageLoadAttemptedUrl = "";
Document topic = null;
String newPageUrl = strings[0];
@ -70,14 +58,9 @@ public class TopicTask extends AsyncTask<String, Void, TopicTaskResult> {
}
}
lastPageLoadAttemptedUrl = newPageUrl;
if (strings[0].substring(0, strings[0].lastIndexOf(".")).contains("topic="))
baseUrl = strings[0].substring(0, strings[0].lastIndexOf(".")); //New topic's base url
String replyPageUrl = null;
Request request = new Request.Builder()
.url(newPageUrl)
.build();
ResultCode resultCode;
try {
Response response = BaseApplication.getInstance().getClient().newCall(request).execute();
topic = Jsoup.parse(response.body().string());
@ -85,17 +68,18 @@ public class TopicTask extends AsyncTask<String, Void, TopicTaskResult> {
ParseHelpers.Language language = ParseHelpers.Language.getLanguage(topic);
//Finds topic's tree, mods and users viewing
topicTreeAndMods = topic.select("div.nav").first().html();
topicViewers = TopicParser.parseUsersViewingThisTopic(topic, language);
String topicTreeAndMods = topic.select("div.nav").first().html();
String topicViewers = TopicParser.parseUsersViewingThisTopic(topic, language);
//Finds reply page url
String replyPageUrl = null;
Element replyButton = topic.select("a:has(img[alt=Reply])").first();
if (replyButton == null)
replyButton = topic.select("a:has(img[alt=Απάντηση])").first();
if (replyButton != null) replyPageUrl = replyButton.attr("href");
//Finds topic title if missing
topicTitle = topic.select("td[id=top_subject]").first().text();
String topicTitle = topic.select("td[id=top_subject]").first().text();
if (topicTitle.contains("Topic:")) {
topicTitle = topicTitle.substring(topicTitle.indexOf("Topic:") + 7
, topicTitle.indexOf("(Read") - 2);
@ -106,42 +90,39 @@ public class TopicTask extends AsyncTask<String, Void, TopicTaskResult> {
}
//Finds current page's index
currentPageIndex = TopicParser.parseCurrentPageIndex(topic, language);
int currentPageIndex = TopicParser.parseCurrentPageIndex(topic, language);
//Finds number of pages
pageCount = TopicParser.parseTopicNumberOfPages(topic, currentPageIndex, language);
int pageCount = TopicParser.parseTopicNumberOfPages(topic, currentPageIndex, language);
for (int i = 0; i < pageCount; i++) {
//Generate each page's url from topic's base url +".15*numberOfPage"
pagesUrls.put(i, baseUrl + "." + String.valueOf(i * 15));
}
newPostsList = TopicParser.parseTopic(topic, language);
ArrayList<Post> newPostsList = TopicParser.parseTopic(topic, language);
loadedPageTopicId = Integer.parseInt(ThmmyPage.getTopicId(lastPageLoadAttemptedUrl));
int loadedPageTopicId = Integer.parseInt(ThmmyPage.getTopicId(newPageUrl));
//Finds the position of the focused message if present
int focusedPostIndex = 0;
for (int i = 0; i < newPostsList.size(); ++i) {
if (newPostsList.get(i).getPostIndex() == postFocus) {
focusedPostIndex = i;
break;
}
}
resultCode = ResultCode.SUCCESS;
return new TopicTaskResult(ResultCode.SUCCESS, topicTitle, replyPageUrl, newPostsList, loadedPageTopicId,
currentPageIndex, pageCount, focusedPostIndex, topicTreeAndMods, topicViewers);
} catch (IOException e) {
Timber.i(e, "IO Exception");
resultCode = ResultCode.NETWORK_ERROR;
return new TopicTaskResult(ResultCode.NETWORK_ERROR, null, null, null,
0, 0, 0, 0, null, null);
} catch (Exception e) {
if (isUnauthorized(topic)) {
resultCode = ResultCode.UNAUTHORIZED;
return new TopicTaskResult(ResultCode.UNAUTHORIZED, null, null, null,
0, 0, 0, 0, null, null);
} else {
Timber.e(e, "Parsing Error");
resultCode = ResultCode.PARSING_ERROR;
return new TopicTaskResult(ResultCode.PARSING_ERROR, null, null, null,
0, 0, 0, 0, null, null);
}
}
return new TopicTaskResult(resultCode, baseUrl, topicTitle, replyPageUrl, newPostsList,
loadedPageTopicId, currentPageIndex, pageCount, focusedPostIndex, topicTreeAndMods,
topicViewers, lastPageLoadAttemptedUrl, pagesUrls);
}
private boolean isUnauthorized(Document document) {

31
app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTaskResult.java

@ -9,13 +9,6 @@ import gr.thmmy.mthmmy.model.Post;
public class TopicTaskResult {
private final TopicTask.ResultCode resultCode;
/**
* Holds this topic's base url. For example a topic with url similar to
* "https://www.thmmy.gr/smf/index.php?topic=1.15;topicseen" or
* "https://www.thmmy.gr/smf/index.php?topic=1.msg1#msg1"
* has the base url "https://www.thmmy.gr/smf/index.php?topic=1"
*/
private final String baseUrl;
/**
* Holds this topic's title. At first this gets the value of the topic title that came with
* bundle and is rendered in the toolbar while parsing this topic. Later, if a different topic
@ -46,18 +39,12 @@ public class TopicTaskResult {
//Topic's info related
private final String topicTreeAndMods;
private final String topicViewers;
/**
* The url of the last page that was attempted to be loaded
*/
private final String lastPageLoadAttemptedUrl;
private final SparseArray<String> pagesUrls;
public TopicTaskResult(TopicTask.ResultCode resultCode, String baseUrl, String topicTitle,
public TopicTaskResult(TopicTask.ResultCode resultCode, String topicTitle,
String replyPageUrl, ArrayList<Post> newPostsList, int loadedPageTopicId,
int currentPageIndex, int pageCount, int focusedPostIndex, String topicTreeAndMods,
String topicViewers, String lastPageLoadAttemptedUrl, SparseArray<String> pagesUrls) {
String topicViewers) {
this.resultCode = resultCode;
this.baseUrl = baseUrl;
this.topicTitle = topicTitle;
this.replyPageUrl = replyPageUrl;
this.newPostsList = newPostsList;
@ -67,18 +54,12 @@ public class TopicTaskResult {
this.focusedPostIndex = focusedPostIndex;
this.topicTreeAndMods = topicTreeAndMods;
this.topicViewers = topicViewers;
this.lastPageLoadAttemptedUrl = lastPageLoadAttemptedUrl;
this.pagesUrls = pagesUrls;
}
public TopicTask.ResultCode getResultCode() {
return resultCode;
}
public String getBaseUrl() {
return baseUrl;
}
public String getTopicTitle() {
return topicTitle;
}
@ -114,12 +95,4 @@ public class TopicTaskResult {
public String getTopicViewers() {
return topicViewers;
}
public String getLastPageLoadAttemptedUrl() {
return lastPageLoadAttemptedUrl;
}
public SparseArray<String> getPagesUrls() {
return pagesUrls;
}
}

15
app/src/main/java/gr/thmmy/mthmmy/utils/ScrollAwareFABBehavior.java

@ -4,13 +4,14 @@ import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
/**
* Extends FloatingActionButton's behavior so the button will hide when scrolling down and show
* otherwise.
* otherwise. It also lifts the {@link FloatingActionButton} when a {@link Snackbar} is shown.
*/
@SuppressWarnings("unused")
public class ScrollAwareFABBehavior extends CoordinatorLayout.Behavior<FloatingActionButton> {
@ -48,4 +49,16 @@ public class ScrollAwareFABBehavior extends CoordinatorLayout.Behavior<FloatingA
child.show();
}
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) {
return dependency instanceof Snackbar.SnackbarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child, View dependency) {
float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight());
child.setTranslationY(translationY);
return true;
}
}

17
app/src/main/java/gr/thmmy/mthmmy/utils/ScrollAwareLinearBehavior.java

@ -4,6 +4,7 @@ import android.animation.Animator;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.util.AttributeSet;
@ -13,7 +14,9 @@ import android.view.ViewPropertyAnimator;
/**
* Extends LinearLayout's behavior. Used for bottom navigation bar.
* <p>When a nested ScrollView is scrolled down, the view will disappear.
* When the ScrollView is scrolled back up, the view will reappear.</p>
* When the ScrollView is scrolled back up, the view will reappear. It also pushes the
* {@link android.widget.LinearLayout} up when a {@link Snackbar} is shown
* </p>
*/
@SuppressWarnings("unused")
public class ScrollAwareLinearBehavior extends CoordinatorLayout.Behavior<View> {
@ -111,4 +114,16 @@ public class ScrollAwareLinearBehavior extends CoordinatorLayout.Behavior<View>
animator.start();
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
return dependency instanceof Snackbar.SnackbarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight());
child.setTranslationY(translationY);
return true;
}
}

20
app/src/main/java/gr/thmmy/mthmmy/utils/parsing/ParseHelpers.java

@ -6,6 +6,8 @@ import org.jsoup.select.Elements;
import java.util.ArrayList;
import timber.log.Timber;
/**
* This class consists exclusively of static classes (enums) and methods (excluding methods of inner
* classes). It can be used to resolve a page's language and state or fix embedded videos html code.
@ -166,4 +168,22 @@ public class ParseHelpers {
}
return fixed;
}
/**
* Method that extracts the base URL from a topic's page URL. For example a topic with url similar to
* "https://www.thmmy.gr/smf/index.php?topic=1.15;topicseen" or
* "https://www.thmmy.gr/smf/index.php?topic=1.msg1#msg1"
* has the base url "https://www.thmmy.gr/smf/index.php?topic=1"
*
* @param topicURL a topic's page URL
* @return the base URL of the given topic
*/
public static String getBaseURL(String topicURL) {
if (topicURL.substring(0, topicURL.lastIndexOf(".")).contains("topic="))
return topicURL.substring(0, topicURL.lastIndexOf("."));
else {
Timber.wtf(new ParseException("Could not parse base URL of topic"));
return "";
}
}
}

188
app/src/main/java/gr/thmmy/mthmmy/viewmodel/TopicViewModel.java

@ -21,6 +21,7 @@ import gr.thmmy.mthmmy.activities.topic.tasks.TopicTaskResult;
import gr.thmmy.mthmmy.base.BaseActivity;
import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.session.SessionManager;
import gr.thmmy.mthmmy.utils.parsing.ParseHelpers;
public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTaskCompleted,
PrepareForReply.OnPrepareForReplyFinished, PrepareForEditTask.OnPrepareEditFinished {
@ -54,44 +55,58 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
private EditTask.EditTaskCallbacks editTaskCallbacks;
private PrepareForReply.PrepareForReplyCallbacks prepareForReplyCallbacks;
private MutableLiveData<TopicTaskResult> topicTaskResult = new MutableLiveData<>();
/**
* Holds the value (index) of the page to be requested when a user interaction with bottom
* navigation bar occurs, aka the value that the page indicator shows
*/
private MutableLiveData<Integer> pageIndicatorIndex = new MutableLiveData<>();
private MutableLiveData<String> replyPageUrl = new MutableLiveData<>();
private MutableLiveData<Integer> pageTopicId = new MutableLiveData<>();
private MutableLiveData<String> topicTitle = new MutableLiveData<>();
private MutableLiveData<ArrayList<Post>> postsList = new MutableLiveData<>();
private MutableLiveData<Integer> focusedPostIndex = new MutableLiveData<>();
private MutableLiveData<TopicTask.ResultCode> topicTaskResultCode = new MutableLiveData<>();
private MutableLiveData<String> topicTreeAndMods = new MutableLiveData<>();
private MutableLiveData<String> topicViewers = new MutableLiveData<>();
private String topicUrl;
private int currentPageIndex;
private int pageCount;
private MutableLiveData<PrepareForReplyResult> prepareForReplyResult = new MutableLiveData<>();
private MutableLiveData<PrepareForEditResult> prepareForEditResult = new MutableLiveData<>();
private String firstTopicUrl;
public void initialLoad(String pageUrl) {
firstTopicUrl = pageUrl;
currentTopicTask = new TopicTask(topicTaskObserver, this);
currentTopicTask.execute(pageUrl);
}
public void loadUrl(String pageUrl) {
stopLoading();
topicUrl = pageUrl;
currentTopicTask = new TopicTask(topicTaskObserver, this);
currentTopicTask.execute(pageUrl);
}
public void reloadPage() {
if (topicTaskResult.getValue() == null)
throw new NullPointerException("No topic task has finished yet!");
loadUrl(topicTaskResult.getValue().getLastPageLoadAttemptedUrl());
if (topicUrl == null) throw new NullPointerException("No topic task has been requested yet!");
loadUrl(topicUrl);
}
public void changePage(int pageRequested) {
if (topicTaskResult.getValue() == null)
public void performPageChange() {
if (pageIndicatorIndex.getValue() == null)
throw new NullPointerException("No page has been loaded yet!");
if (pageRequested != topicTaskResult.getValue().getCurrentPageIndex() - 1)
loadUrl(topicTaskResult.getValue().getPagesUrls().get(pageRequested));
int pageRequested = pageIndicatorIndex.getValue() - 1;
if (pageRequested != currentPageIndex - 1) {
loadUrl(ParseHelpers.getBaseURL(topicUrl) + "." + String.valueOf(pageRequested * 15));
pageIndicatorIndex.setValue(pageRequested + 1);
} else {
stopLoading();
}
}
public void prepareForReply() {
if (topicTaskResult.getValue() == null)
if (replyPageUrl.getValue() == null)
throw new NullPointerException("Topic task has not finished yet!");
stopLoading();
changePage(topicTaskResult.getValue().getPageCount() - 1);
setPageIndicatorIndex(pageCount, true);
currentPrepareForReplyTask = new PrepareForReply(prepareForReplyCallbacks, this,
topicTaskResult.getValue().getReplyPageUrl());
replyPageUrl.getValue());
currentPrepareForReplyTask.execute(toQuoteList.toArray(new Integer[0]));
}
@ -116,11 +131,11 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
}
public void prepareForEdit(int position, String postEditURL) {
if (topicTaskResult.getValue() == null)
if (replyPageUrl.getValue() == null)
throw new NullPointerException("Topic task has not finished yet!");
stopLoading();
currentPrepareForEditTask = new PrepareForEditTask(prepareForEditCallbacks, this, position,
topicTaskResult.getValue().getReplyPageUrl());
replyPageUrl.getValue());
currentPrepareForEditTask.execute(postEditURL);
}
@ -140,6 +155,7 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
public void stopLoading() {
if (currentTopicTask != null && currentTopicTask.getStatus() == AsyncTask.Status.RUNNING) {
currentTopicTask.cancel(true);
pageIndicatorIndex.setValue(currentPageIndex);
topicTaskObserver.onTopicTaskCancelled();
}
if (currentPrepareForEditTask != null && currentPrepareForEditTask.getStatus() == AsyncTask.Status.RUNNING) {
@ -157,30 +173,108 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
// callbacks for viewmodel
@Override
public void onTopicTaskCompleted(TopicTaskResult result) {
topicTaskResult.setValue(result);
if (result.getResultCode() == TopicTask.ResultCode.SUCCESS) {
currentPageIndex = result.getCurrentPageIndex();
pageCount = result.getPageCount();
topicTreeAndMods.setValue(result.getTopicTreeAndMods());
topicViewers.setValue(result.getTopicViewers());
pageTopicId.setValue(result.getLoadedPageTopicId());
replyPageUrl.setValue(result.getReplyPageUrl());
topicTitle.setValue(result.getTopicTitle());
pageIndicatorIndex.setValue(result.getCurrentPageIndex());
postsList.setValue(result.getNewPostsList());
focusedPostIndex.setValue(result.getFocusedPostIndex());
isUserExtraInfoVisibile.clear();
for (int i = 0; i < result.getNewPostsList().size(); i++) {
isUserExtraInfoVisibile.add(false);
}
}
topicTaskResultCode.setValue(result.getResultCode());
}
@Override
public void onPrepareForReplyFinished(PrepareForReplyResult result) {
writingReply = true;
prepareForReplyResult.setValue(result);
}
@Override
public void onPrepareEditFinished(PrepareForEditResult result, int position) {
editingPost = true;
postBeingEditedPosition = position;
prepareForEditResult.setValue(result);
}
public void incrementPageRequestValue(int step, boolean changePage) {
if (pageIndicatorIndex.getValue() == null)
throw new NullPointerException("No page has been loaded yet!");
int oldIndicatorIndex = pageIndicatorIndex.getValue();
if (oldIndicatorIndex <= pageCount - step) {
pageIndicatorIndex.setValue(pageIndicatorIndex.getValue() + step);
} else
pageIndicatorIndex.setValue(pageCount);
if (changePage && oldIndicatorIndex != pageIndicatorIndex.getValue()) performPageChange();
}
public void decrementPageRequestValue(int step, boolean changePage) {
if (pageIndicatorIndex.getValue() == null)
throw new NullPointerException("No page has been loaded yet!");
int oldIndicatorIndex = pageIndicatorIndex.getValue();
if (oldIndicatorIndex > step) {
pageIndicatorIndex.setValue(pageIndicatorIndex.getValue() - step);
} else
pageIndicatorIndex.setValue(1);
if (changePage && oldIndicatorIndex != pageIndicatorIndex.getValue()) performPageChange();
}
public void setPageIndicatorIndex(int pageIndicatorIndex, boolean changePage) {
if (this.pageIndicatorIndex.getValue() == null)
throw new NullPointerException("No page has been loaded yet!");
int oldIndicatorIndex = this.pageIndicatorIndex.getValue();
this.pageIndicatorIndex.setValue(pageIndicatorIndex);
if (changePage && oldIndicatorIndex != this.pageIndicatorIndex.getValue()) performPageChange();
}
// <-------------Just getters, setters and helper methods below here---------------->
public MutableLiveData<String> getTopicViewers() {
return topicViewers;
}
public MutableLiveData<String> getTopicTreeAndMods() {
return topicTreeAndMods;
}
public MutableLiveData<TopicTask.ResultCode> getTopicTaskResultCode() {
return topicTaskResultCode;
}
public MutableLiveData<Integer> getFocusedPostIndex() {
return focusedPostIndex;
}
public MutableLiveData<ArrayList<Post>> getPostsList() {
return postsList;
}
public MutableLiveData<String> getReplyPageUrl() {
return replyPageUrl;
}
public MutableLiveData<Integer> getPageTopicId() {
return pageTopicId;
}
public MutableLiveData<String> getTopicTitle() {
return topicTitle;
}
public String getTopicUrl() {
return topicUrl;
}
public MutableLiveData<Integer> getPageIndicatorIndex() {
return pageIndicatorIndex;
}
public boolean isUserExtraInfoVisible(int position) {
return isUserExtraInfoVisibile.get(position);
}
@ -228,10 +322,6 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
this.prepareForReplyCallbacks = prepareForReplyCallbacks;
}
public MutableLiveData<TopicTaskResult> getTopicTaskResult() {
return topicTaskResult;
}
public MutableLiveData<PrepareForReplyResult> getPrepareForReplyResult() {
return prepareForReplyResult;
}
@ -253,7 +343,7 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
}
public boolean canReply() {
return topicTaskResult.getValue() != null && topicTaskResult.getValue().getReplyPageUrl() != null;
return replyPageUrl.getValue() != null;
}
public boolean isWritingReply() {
@ -264,40 +354,14 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
this.writingReply = writingReply;
}
public String getBaseUrl() {
if (topicTaskResult.getValue() != null) {
return topicTaskResult.getValue().getBaseUrl();
} else {
return "";
}
}
public String getTopicUrl() {
if (topicTaskResult.getValue() != null) {
return topicTaskResult.getValue().getLastPageLoadAttemptedUrl();
} else {
// topic task has not finished yet (log? disable menu button until load is finished?)
return firstTopicUrl;
}
}
public String getTopicTitle() {
if (topicTaskResult.getValue() == null)
throw new NullPointerException("Topic task has not finished yet!");
return topicTaskResult.getValue().getTopicTitle();
}
public int getCurrentPageIndex() {
if (topicTaskResult.getValue() == null)
throw new NullPointerException("No page has been loaded yet!");
return topicTaskResult.getValue().getCurrentPageIndex();
if (currentPageIndex == 0) throw new NullPointerException("No page has been loaded yet!");
return currentPageIndex;
}
public int getPageCount() {
if (topicTaskResult.getValue() == null)
throw new NullPointerException("No page has been loaded yet!");
return topicTaskResult.getValue().getPageCount();
if (pageCount == 0) throw new NullPointerException("No page has been loaded yet!");
return pageCount;
}
public String getPostBeingEditedText() {
@ -307,10 +371,8 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
}
public String getBuildedQuotes() {
if (prepareForReplyResult.getValue() != null) {
if (prepareForReplyResult.getValue() == null)
throw new NullPointerException("Reply preparation was not found");
return prepareForReplyResult.getValue().getBuildedQuotes();
} else {
return "";
}
}
}

10
app/src/main/res/layout/activity_topic.xml

@ -47,6 +47,16 @@
app:layout_behavior="@string/appbar_scrolling_view_behavior">
</android.support.v7.widget.RecyclerView>
<TextView
android:id="@+id/error_textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/network_error_retry_prompt"
android:textSize="32sp"
android:textColor="@color/white"
android:gravity="center"
android:visibility="gone" />
<LinearLayout
android:id="@+id/bottom_navigation_bar"
android:layout_width="match_parent"

4
app/src/main/res/values/strings.xml

@ -53,6 +53,10 @@
<string name="subject">Subject&#8230;</string>
<string name="submit">Submit</string>
<string name="post_message">Message&#8230;</string>
<string name="network_error_retry_prompt">Could not connect to thmmy.gr \n\n Tap to retry</string>
<string name="generic_network_error">Network error</string>
<string name="retry">retry</string>
<string name="unauthorized_topic_error">This topic is either missing or off limits to you</string>
<!--Profile Activity-->
<string name="username">Username</string>

Loading…
Cancel
Save