PageRenderTime 58ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/app/src/main/java/tk/elevenk/dailybread/fragment/SearchResultsFragment.java

https://gitlab.com/manadream/DailybRead
Java | 246 lines | 190 code | 29 blank | 27 comment | 34 complexity | f324751e8bc60fc77e9cb89aaf52f164 MD5 | raw file
  1. /*
  2. * SearchResultsFragment.java is a part of DailybRead
  3. * Copyright (C) 2015 John Krause, Eleven-K Software
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. package tk.elevenk.dailybread.fragment;
  19. import android.app.ProgressDialog;
  20. import android.content.Intent;
  21. import android.graphics.Bitmap;
  22. import android.graphics.BitmapFactory;
  23. import android.net.Uri;
  24. import android.os.AsyncTask;
  25. import android.os.Bundle;
  26. import android.support.annotation.Nullable;
  27. import android.support.v4.app.FragmentTransaction;
  28. import android.util.Log;
  29. import android.view.Menu;
  30. import android.view.MenuInflater;
  31. import android.view.View;
  32. import android.widget.ListView;
  33. import android.widget.Toast;
  34. import tk.elevenk.dailybread.R;
  35. import tk.elevenk.dailybread.adapter.SearchResultsAdapter;
  36. import tk.elevenk.dailybread.fragment.reader.MainReaderFragment;
  37. import tk.elevenk.olapi.Library;
  38. import tk.elevenk.olapi.OpenLibrary;
  39. import tk.elevenk.olapi.data.BookData;
  40. import tk.elevenk.olapi.data.BookList;
  41. import java.io.BufferedInputStream;
  42. import java.io.InputStream;
  43. import java.net.URL;
  44. import java.util.ArrayList;
  45. import java.util.List;
  46. /**
  47. * Results from search displayed using this fragment
  48. *
  49. * Created by John Krause on 1/1/15.
  50. */
  51. public class SearchResultsFragment extends BooksListFragment {
  52. private BookList books;
  53. private Library library;
  54. private LoadEbook currentTask;
  55. private SearchResultsAdapter searchResultsAdapter;
  56. private List<AsyncTask> tasks;
  57. private ProgressDialog progress;
  58. public void populateSearchResults(Library library, BookList bookList) {
  59. this.books = bookList;
  60. this.library = library;
  61. this.tasks = new ArrayList<>();
  62. searchResultsAdapter = new SearchResultsAdapter(books, this.getActivity());
  63. this.setListAdapter(searchResultsAdapter);
  64. for (BookData data : bookList) {
  65. tasks.add(new DownloadImage().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, data));
  66. }
  67. if(bookList.isEmpty()){
  68. // TODO make better dialog/action for this
  69. Toast.makeText(getActivity(), "No Results Found!", Toast.LENGTH_LONG).show();
  70. getActivity().onBackPressed();
  71. }
  72. }
  73. @Override
  74. public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
  75. super.onViewCreated(view, savedInstanceState);
  76. reader = new MainReaderFragment(){
  77. @Override
  78. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  79. inflater.inflate(R.menu.reader_from_search, menu);
  80. }
  81. };
  82. }
  83. @Override
  84. public void onListItemClick(ListView l, View v, int position, long id) {
  85. progress = ProgressDialog.show(this.getActivity(), "Loading book...", "Trying to load ebook. If none is found you will be taken to the book's web page.", true, false);
  86. BookData book = books.get(position);
  87. currentTask = new LoadEbook();
  88. currentTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, book);
  89. }
  90. private void cancelTasks() {
  91. if(tasks != null) {
  92. for (AsyncTask task : tasks) {
  93. task.cancel(true);
  94. }
  95. tasks.clear();
  96. }
  97. }
  98. @Override
  99. public void onDestroyView() {
  100. super.onDestroyView();
  101. cancelTasks();
  102. }
  103. @Override
  104. public void onStop() {
  105. super.onStop();
  106. cancelTasks();
  107. }
  108. @Override
  109. public void onDetach() {
  110. super.onDetach();
  111. cancelTasks();
  112. }
  113. @Override
  114. public void onDestroy() {
  115. super.onDestroy();
  116. cancelTasks();
  117. }
  118. private class LoadEbook extends AsyncTask<BookData, String, Object> {
  119. private BookData bookData;
  120. @Override
  121. protected Object doInBackground(BookData... params) {
  122. bookData = params[0];
  123. Object book = null;
  124. bookData.addBookDetails(library);
  125. if (bookData.hasEpubUrl()) {
  126. book = library.getEbook(params[0]);
  127. }
  128. return book;
  129. }
  130. @Override
  131. protected void onPostExecute(Object o) {
  132. if (o != null) {
  133. FragmentTransaction transaction = getFragmentManager().beginTransaction().replace(R.id.main_content_layout, reader);
  134. transaction.addToBackStack(null);
  135. transaction.commitAllowingStateLoss();
  136. getFragmentManager().executePendingTransactions();
  137. if (!reader.loadNewBook(o)) {
  138. openBookInBrowser();
  139. } else {
  140. progress.hide();
  141. }
  142. } else {
  143. openBookInBrowser();
  144. progress.hide();
  145. }
  146. }
  147. private void openBookInBrowser() {
  148. String url = bookData.getUrl();
  149. if (url != null && url.length() > 0) {
  150. if (url.startsWith("/")) {
  151. url = library.getBaseUrl() + url;
  152. }
  153. Intent browserCall = new Intent(Intent.ACTION_VIEW);
  154. browserCall.setData(Uri.parse(url));
  155. startActivity(browserCall);
  156. }
  157. }
  158. }
  159. private class DownloadImage extends AsyncTask<Object, Integer, Bitmap> {
  160. @Override
  161. protected Bitmap doInBackground(Object... args) {
  162. Bitmap bmp = null;
  163. if (args[0] != null) {
  164. BookData data = (BookData) args[0];
  165. if (data.getCoverImage() == null) {
  166. if (isCancelled()) return null;
  167. Library lib = OpenLibrary.androidLibrary(null);
  168. if (isCancelled()) return null;
  169. Object url = lib.getCoverUrls("id", data.getCoverId()).get("medium");
  170. if (isCancelled()) return null;
  171. if (url == null) {
  172. url = lib.getCoverUrls("olid", data.getCoverEditionKey()).get("medium");
  173. }
  174. if (isCancelled()) return null;
  175. if (url == null) {
  176. url = lib.getCoverUrls("olid", data.getOlid()).get("medium");
  177. }
  178. if (isCancelled()) return null;
  179. if (url != null) {
  180. bmp = downloadImage(url.toString());
  181. if (isCancelled()) return null;
  182. data.setCoverImage(bmp);
  183. }
  184. }
  185. }
  186. return bmp;
  187. }
  188. @Override
  189. protected void onPostExecute(Bitmap image) {
  190. searchResultsAdapter.notifyDataSetChanged();
  191. }
  192. private Bitmap downloadImage(String _url) {
  193. //Prepare to download image
  194. Bitmap bMap = null;
  195. URL url;
  196. InputStream in;
  197. BufferedInputStream buf;
  198. //BufferedInputStream buf;
  199. try {
  200. url = new URL(_url);
  201. if (isCancelled()) return null;
  202. in = url.openStream();
  203. // Read the input stream
  204. if (isCancelled()) return null;
  205. buf = new BufferedInputStream(in);
  206. // Convert the BufferedInputStream to a Bitmap
  207. if (isCancelled()) return null;
  208. bMap = BitmapFactory.decodeStream(buf);
  209. in.close();
  210. buf.close();
  211. } catch (Exception e) {
  212. Log.e("Error reading file", e.toString());
  213. }
  214. return bMap;
  215. }
  216. }
  217. }