From 5129c06cd4cf2f3d65df3d1881d82e6404ef6e21 Mon Sep 17 00:00:00 2001 From: Thodoris1999 Date: Wed, 12 Sep 2018 13:29:16 +0300 Subject: [PATCH] add default request in NetworkTask, refactor main activity --- .../activities/main/forum/ForumFragment.java | 89 ++++++++++--------- .../main/recent/RecentFragment.java | 70 ++++++++------- .../main/unread/UnreadFragment.java | 71 +++++++++------ .../mthmmy/utils/parsing/NetworkTask.java | 9 +- 4 files changed, 142 insertions(+), 97 deletions(-) diff --git a/app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java b/app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java index 3b6366b4..f98dcd60 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java +++ b/app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java @@ -10,6 +10,7 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.RelativeLayout; +import android.widget.Toast; import com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter; @@ -17,21 +18,26 @@ import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import gr.thmmy.mthmmy.R; import gr.thmmy.mthmmy.base.BaseActivity; +import gr.thmmy.mthmmy.base.BaseApplication; import gr.thmmy.mthmmy.base.BaseFragment; import gr.thmmy.mthmmy.model.Board; import gr.thmmy.mthmmy.model.Category; import gr.thmmy.mthmmy.session.SessionManager; import gr.thmmy.mthmmy.utils.CustomRecyclerView; +import gr.thmmy.mthmmy.utils.parsing.NewParseTask; +import gr.thmmy.mthmmy.utils.parsing.Parcel; import gr.thmmy.mthmmy.utils.parsing.ParseException; -import gr.thmmy.mthmmy.utils.parsing.ParseTask; import me.zhanghai.android.materialprogressbar.MaterialProgressBar; import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; import okhttp3.Request; +import okhttp3.Response; import timber.log.Timber; /** @@ -83,7 +89,7 @@ public class ForumFragment extends BaseFragment { public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (categories.isEmpty()) { - forumTask = new ForumTask(); + forumTask = new ForumTask(this::onForumTaskStarted, this::onForumTaskFinished); forumTask.execute(); } @@ -106,7 +112,7 @@ public class ForumFragment extends BaseFragment { if (BaseActivity.getSessionManager().isLoggedIn()) { if (forumTask.getStatus() == AsyncTask.Status.RUNNING) forumTask.cancel(true); - forumTask = new ForumTask(); + forumTask = new ForumTask(ForumFragment.this::onForumTaskStarted, ForumFragment.this::onForumTaskFinished); forumTask.setUrl(categories.get(parentPosition).getCategoryURL()); forumTask.execute(); } @@ -117,7 +123,7 @@ public class ForumFragment extends BaseFragment { if (BaseActivity.getSessionManager().isLoggedIn()) { if (forumTask.getStatus() == AsyncTask.Status.RUNNING) forumTask.cancel(true); - forumTask = new ForumTask(); + forumTask = new ForumTask(ForumFragment.this::onForumTaskStarted, ForumFragment.this::onForumTaskFinished); forumTask.setUrl(categories.get(parentPosition).getCategoryURL()); forumTask.execute(); } @@ -135,16 +141,12 @@ public class ForumFragment extends BaseFragment { swipeRefreshLayout = rootView.findViewById(R.id.swiperefresh); swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.primary); swipeRefreshLayout.setColorSchemeResources(R.color.accent); - swipeRefreshLayout.setOnRefreshListener( - new SwipeRefreshLayout.OnRefreshListener() { - @Override - public void onRefresh() { - if (forumTask != null && forumTask.getStatus() != AsyncTask.Status.RUNNING) { - forumTask = new ForumTask(); - forumTask.execute(SessionManager.indexUrl.toString()); - } + swipeRefreshLayout.setOnRefreshListener(() -> { + if (forumTask != null && forumTask.getStatus() != AsyncTask.Status.RUNNING) { + forumTask = new ForumTask(ForumFragment.this::onForumTaskStarted, ForumFragment.this::onForumTaskFinished); + //forumTask.execute(SessionManager.indexUrl.toString()); + forumTask.execute(); } - } ); @@ -163,33 +165,38 @@ public class ForumFragment extends BaseFragment { void onForumFragmentInteraction(Board board); } - //---------------------------------------ASYNC TASK----------------------------------- + public void onForumTaskStarted() { + progressBar.setVisibility(ProgressBar.VISIBLE); + } - private class ForumTask extends ParseTask { - private HttpUrl forumUrl = SessionManager.forumUrl; //may change upon collapse/expand + public void onForumTaskFinished(int resultCode, ArrayList fetchedCategories) { + if (resultCode == Parcel.ResultCode.SUCCESSFUL) { + categories.clear(); + categories.addAll(fetchedCategories); + forumAdapter.notifyParentDataSetChanged(false); + } else if (resultCode == Parcel.ResultCode.NETWORK_ERROR) { + Toast.makeText(BaseApplication.getInstance().getApplicationContext(), "Network error", Toast.LENGTH_SHORT).show(); + } - private final List fetchedCategories; + progressBar.setVisibility(ProgressBar.INVISIBLE); + swipeRefreshLayout.setRefreshing(false); + } - ForumTask() { - fetchedCategories = new ArrayList<>(); - } + //---------------------------------------ASYNC TASK----------------------------------- - protected void onPreExecute() { - progressBar.setVisibility(ProgressBar.VISIBLE); - } + private class ForumTask extends NewParseTask> { + private HttpUrl forumUrl = SessionManager.forumUrl; //may change upon collapse/expand - @Override - protected Request prepareRequest(String... params) { - return new Request.Builder() - .url(forumUrl) - .build(); + public ForumTask(OnParseTaskStartedListener onParseTaskStartedListener, + OnParseTaskFinishedListener> onParseTaskFinishedListener) { + super(onParseTaskStartedListener, onParseTaskFinishedListener); } - @Override - public void parse(Document document) throws ParseException { + protected ArrayList parse(Document document) throws ParseException { Elements categoryBlocks = document.select(".tborder:not([style])>table[cellpadding=5]"); if (categoryBlocks.size() != 0) { + ArrayList fetchedCategories = new ArrayList<>(); for (Element categoryBlock : categoryBlocks) { Element categoryElement = categoryBlock.select("td[colspan=2]>[name]").first(); String categoryUrl = categoryElement.attr("href"); @@ -207,24 +214,26 @@ public class ForumFragment extends BaseFragment { fetchedCategories.add(category); } - categories.clear(); - categories.addAll(fetchedCategories); - fetchedCategories.clear(); + return fetchedCategories; } else throw new ParseException("Parsing failed"); } @Override - protected void postExecution(ParseTask.ResultCode result) { - if (result == ResultCode.SUCCESS) - forumAdapter.notifyParentDataSetChanged(false); + protected Response sendRequest(OkHttpClient client, String... input) throws IOException { + Request request = new Request.Builder() + .url(forumUrl) + .build(); + return client.newCall(request).execute(); + } - progressBar.setVisibility(ProgressBar.INVISIBLE); - swipeRefreshLayout.setRefreshing(false); + @Override + protected int getResultCode(Response response, ArrayList data) { + return Parcel.ResultCode.SUCCESSFUL; } - public void setUrl(String string) //TODO delete and simplify e.g. in prepareRequest possible? - { + //TODO delete and simplify e.g. in prepareRequest possible? + public void setUrl(String string) { forumUrl = HttpUrl.parse(string); } } diff --git a/app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java b/app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java index aee35e37..31b3421d 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java +++ b/app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java @@ -10,23 +10,30 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.RelativeLayout; +import android.widget.Toast; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import gr.thmmy.mthmmy.R; +import gr.thmmy.mthmmy.base.BaseApplication; import gr.thmmy.mthmmy.base.BaseFragment; import gr.thmmy.mthmmy.model.TopicSummary; import gr.thmmy.mthmmy.session.SessionManager; import gr.thmmy.mthmmy.utils.CustomRecyclerView; +import gr.thmmy.mthmmy.utils.parsing.NewParseTask; +import gr.thmmy.mthmmy.utils.parsing.Parcel; import gr.thmmy.mthmmy.utils.parsing.ParseException; -import gr.thmmy.mthmmy.utils.parsing.ParseTask; import me.zhanghai.android.materialprogressbar.MaterialProgressBar; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; import timber.log.Timber; @@ -79,7 +86,7 @@ public class RecentFragment extends BaseFragment { public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (topicSummaries.isEmpty()) { - recentTask = new RecentTask(); + recentTask = new RecentTask(this::onRecentTaskStarted, this::onRecentTaskFinished); recentTask.execute(SessionManager.indexUrl.toString()); } @@ -109,16 +116,11 @@ public class RecentFragment extends BaseFragment { swipeRefreshLayout = rootView.findViewById(R.id.swiperefresh); swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.primary); swipeRefreshLayout.setColorSchemeResources(R.color.accent); - swipeRefreshLayout.setOnRefreshListener( - new SwipeRefreshLayout.OnRefreshListener() { - @Override - public void onRefresh() { - if (recentTask != null && recentTask.getStatus() != AsyncTask.Status.RUNNING) { - recentTask = new RecentTask(); - recentTask.execute(SessionManager.indexUrl.toString()); - } + swipeRefreshLayout.setOnRefreshListener(() -> { + if (recentTask != null && recentTask.getStatus() != AsyncTask.Status.RUNNING) { + recentTask = new RecentTask(this::onRecentTaskStarted, this::onRecentTaskFinished); + recentTask.execute(SessionManager.indexUrl.toString()); } - } ); } @@ -138,18 +140,34 @@ public class RecentFragment extends BaseFragment { void onRecentFragmentInteraction(TopicSummary topicSummary); } + private void onRecentTaskStarted() { + progressBar.setVisibility(ProgressBar.VISIBLE); + } + + private void onRecentTaskFinished(int resultCode, ArrayList fetchedRecent) { + if (resultCode == Parcel.ResultCode.SUCCESSFUL) { + topicSummaries.clear(); + topicSummaries.addAll(fetchedRecent); + recentAdapter.notifyDataSetChanged(); + } else if (resultCode == Parcel.ResultCode.NETWORK_ERROR) { + Toast.makeText(BaseApplication.getInstance().getApplicationContext(), "Network error", Toast.LENGTH_SHORT).show(); + } + + progressBar.setVisibility(ProgressBar.INVISIBLE); + swipeRefreshLayout.setRefreshing(false); + } + //---------------------------------------ASYNC TASK----------------------------------- - private class RecentTask extends ParseTask { - private List fetchedRecent; + private class RecentTask extends NewParseTask> { - @Override - protected void onPreExecute() { - progressBar.setVisibility(ProgressBar.VISIBLE); - fetchedRecent = new ArrayList<>(); + public RecentTask(OnParseTaskStartedListener onParseTaskStartedListener, + OnParseTaskFinishedListener> onParseTaskFinishedListener) { + super(onParseTaskStartedListener, onParseTaskFinishedListener); } @Override - public void parse(Document document) throws ParseException { + protected ArrayList parse(Document document) throws ParseException { + ArrayList fetchedRecent = new ArrayList<>(); Elements recent = document.select("#block8 :first-child div"); if (!recent.isEmpty()) { for (int i = 0; i < recent.size(); i += 3) { @@ -174,7 +192,7 @@ public class RecentFragment extends BaseFragment { dateTime.contains(" πμ") || dateTime.contains(" μμ")) { dateTime = dateTime.replaceAll(":[0-5][0-9] ", " "); } else { - dateTime=dateTime.substring(0,dateTime.lastIndexOf(":")); + dateTime = dateTime.substring(0, dateTime.lastIndexOf(":")); } if (!dateTime.contains(",")) { dateTime = dateTime.replaceAll(".+? ([0-9])", "$1"); @@ -184,22 +202,14 @@ public class RecentFragment extends BaseFragment { fetchedRecent.add(new TopicSummary(link, title, lastUser, dateTime)); } - return; + return fetchedRecent; } throw new ParseException("Parsing failed"); } @Override - protected void postExecution(ParseTask.ResultCode result) { - if (result == ResultCode.SUCCESS) - { - topicSummaries.clear(); - topicSummaries.addAll(fetchedRecent); - recentAdapter.notifyDataSetChanged(); - } - - progressBar.setVisibility(ProgressBar.INVISIBLE); - swipeRefreshLayout.setRefreshing(false); + protected int getResultCode(Response response, ArrayList data) { + return Parcel.ResultCode.SUCCESSFUL; } } } diff --git a/app/src/main/java/gr/thmmy/mthmmy/activities/main/unread/UnreadFragment.java b/app/src/main/java/gr/thmmy/mthmmy/activities/main/unread/UnreadFragment.java index b18874d5..0c4f5417 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/activities/main/unread/UnreadFragment.java +++ b/app/src/main/java/gr/thmmy/mthmmy/activities/main/unread/UnreadFragment.java @@ -22,13 +22,19 @@ import java.util.ArrayList; import java.util.List; import gr.thmmy.mthmmy.R; +import gr.thmmy.mthmmy.base.BaseApplication; import gr.thmmy.mthmmy.base.BaseFragment; import gr.thmmy.mthmmy.model.TopicSummary; import gr.thmmy.mthmmy.session.SessionManager; import gr.thmmy.mthmmy.utils.CustomRecyclerView; +import gr.thmmy.mthmmy.utils.parsing.NewParseTask; +import gr.thmmy.mthmmy.utils.parsing.Parcel; +import gr.thmmy.mthmmy.utils.parsing.ParseException; import gr.thmmy.mthmmy.utils.parsing.ParseTask; import me.zhanghai.android.materialprogressbar.MaterialProgressBar; +import okhttp3.OkHttpClient; import okhttp3.Request; +import okhttp3.Response; import timber.log.Timber; /** @@ -83,7 +89,7 @@ public class UnreadFragment extends BaseFragment { public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (topicSummaries.isEmpty()) { - unreadTask = new UnreadTask(); + unreadTask = new UnreadTask(this::onUnreadTaskStarted, this::onUnreadTaskFinished); assert SessionManager.unreadUrl != null; unreadTask.execute(SessionManager.unreadUrl.toString()); } @@ -126,7 +132,7 @@ public class UnreadFragment extends BaseFragment { topicSummaries.clear(); numberOfPages = 0; loadedPages = 0; - unreadTask = new UnreadTask(); + unreadTask = new UnreadTask(this::onUnreadTaskStarted, this::onUnreadTaskFinished); assert SessionManager.unreadUrl != null; unreadTask.execute(SessionManager.unreadUrl.toString()); } @@ -151,13 +157,42 @@ public class UnreadFragment extends BaseFragment { } //---------------------------------------ASYNC TASK----------------------------------- - private class UnreadTask extends ParseTask { - protected void onPreExecute() { - progressBar.setVisibility(ProgressBar.VISIBLE); + + private void onUnreadTaskStarted() { + progressBar.setVisibility(ProgressBar.VISIBLE); + } + + private void onUnreadTaskFinished(int resultCode, Void data) { + if (resultCode == Parcel.ResultCode.SUCCESSFUL) { + unreadAdapter.notifyDataSetChanged(); + + ++loadedPages; + if (loadedPages < numberOfPages) { + unreadTask = new UnreadTask(this::onUnreadTaskStarted, this::onUnreadTaskFinished); + assert SessionManager.unreadUrl != null; + unreadTask.execute(SessionManager.unreadUrl.toString() + ";start=" + loadedPages * 20); + } + else { + progressBar.setVisibility(ProgressBar.INVISIBLE); + swipeRefreshLayout.setRefreshing(false); + } + } + else{ + progressBar.setVisibility(ProgressBar.INVISIBLE); + swipeRefreshLayout.setRefreshing(false); + if (resultCode == Parcel.ResultCode.NETWORK_ERROR) + Toast.makeText(BaseApplication.getInstance().getApplicationContext(), "Network error", Toast.LENGTH_SHORT).show(); + } + } + + private class UnreadTask extends NewParseTask { + + UnreadTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener onParseTaskFinishedListener) { + super(onParseTaskStartedListener, onParseTaskFinishedListener); } @Override - public void parse(Document document) { + protected Void parse(Document document) throws ParseException { Elements unread = document.select("table.bordercolor[cellspacing=1] tr:not(.titlebg)"); if (!unread.isEmpty()) { //topicSummaries.clear(); @@ -217,28 +252,12 @@ public class UnreadFragment extends BaseFragment { } topicSummaries.add(new TopicSummary(null, null, null, message)); } + return null; } @Override - protected void postExecution(ParseTask.ResultCode result) { - if (result == ResultCode.SUCCESS) { - unreadAdapter.notifyDataSetChanged(); - - ++loadedPages; - if (loadedPages < numberOfPages) { - unreadTask = new UnreadTask(); - assert SessionManager.unreadUrl != null; - unreadTask.execute(SessionManager.unreadUrl.toString() + ";start=" + loadedPages * 20); - } - else { - progressBar.setVisibility(ProgressBar.INVISIBLE); - swipeRefreshLayout.setRefreshing(false); - } - } - else{ - progressBar.setVisibility(ProgressBar.INVISIBLE); - swipeRefreshLayout.setRefreshing(false); - } + protected int getResultCode(Response response, Void data) { + return Parcel.ResultCode.SUCCESSFUL; } } @@ -282,7 +301,7 @@ public class UnreadFragment extends BaseFragment { , "Fatal error!\n Task aborted...", Toast.LENGTH_LONG).show(); } else { if (unreadTask != null && unreadTask.getStatus() != AsyncTask.Status.RUNNING) { - unreadTask = new UnreadTask(); + unreadTask = new UnreadTask(UnreadFragment.this::onUnreadTaskStarted, UnreadFragment.this::onUnreadTaskFinished); assert SessionManager.unreadUrl != null; unreadTask.execute(SessionManager.unreadUrl.toString()); } diff --git a/app/src/main/java/gr/thmmy/mthmmy/utils/parsing/NetworkTask.java b/app/src/main/java/gr/thmmy/mthmmy/utils/parsing/NetworkTask.java index 3507d130..c638f284 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/utils/parsing/NetworkTask.java +++ b/app/src/main/java/gr/thmmy/mthmmy/utils/parsing/NetworkTask.java @@ -7,6 +7,7 @@ import java.io.IOException; import gr.thmmy.mthmmy.base.BaseApplication; import okhttp3.OkHttpClient; +import okhttp3.Request; import okhttp3.Response; import timber.log.Timber; @@ -67,7 +68,13 @@ public abstract class NetworkTask extends ExternalAsyncTask super.onPostExecute(tParcel); } - protected abstract Response sendRequest(OkHttpClient client, String... input) throws IOException; + protected Response sendRequest(OkHttpClient client, String... input) throws IOException { + String url = input[0]; + Request request = new Request.Builder() + .url(url) + .build(); + return client.newCall(request).execute(); + } protected abstract T performTask(Document document);