stirante

FilterStore

Feb 18th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.64 KB | None | 0 0
  1. package com.stirante.quizcheat.material;
  2.  
  3. import android.app.ProgressDialog;
  4. import android.content.Context;
  5. import android.os.AsyncTask;
  6. import android.os.Environment;
  7. import android.support.v7.app.AppCompatActivity;
  8. import android.os.Bundle;
  9. import android.view.LayoutInflater;
  10. import android.view.View;
  11. import android.view.ViewGroup;
  12. import android.widget.AbsListView;
  13. import android.widget.AdapterView;
  14. import android.widget.BaseAdapter;
  15. import android.widget.GridView;
  16. import android.widget.ImageView;
  17. import android.widget.ProgressBar;
  18. import android.widget.TextView;
  19. import android.widget.Toast;
  20.  
  21. import com.stirante.quizcheat.DrawableManager;
  22. import com.stirante.quizcheat.R;
  23.  
  24. import org.apache.http.HttpEntity;
  25. import org.apache.http.HttpResponse;
  26. import org.apache.http.client.methods.HttpGet;
  27. import org.apache.http.client.methods.HttpPost;
  28. import org.apache.http.impl.client.DefaultHttpClient;
  29. import org.apache.http.params.BasicHttpParams;
  30. import org.json.JSONArray;
  31. import org.json.JSONException;
  32. import org.json.JSONObject;
  33.  
  34. import java.io.BufferedReader;
  35. import java.io.File;
  36. import java.io.FileOutputStream;
  37. import java.io.InputStream;
  38. import java.io.InputStreamReader;
  39. import java.util.ArrayList;
  40.  
  41. public class FiltersActivity extends AppCompatActivity {
  42.  
  43. private GridView gridView;
  44. private ProgressDialog progress;
  45. private ArrayList<RedditFilter> filters = new ArrayList<>();
  46. private boolean loading = false;
  47. private String after = null;
  48. private File filtersDir = new File(Environment.getExternalStorageDirectory() + "/Snapprefs/NewFilters/");
  49.  
  50. @Override
  51. protected void onCreate(Bundle savedInstanceState) {
  52. super.onCreate(savedInstanceState);
  53. setContentView(R.layout.activity_filters);
  54. filtersDir.mkdirs();
  55. gridView = (GridView) findViewById(R.id.filter_grid);
  56. gridView.setAdapter(new FilterAdapter());
  57. gridView.setNumColumns(2);
  58. progress = ProgressDialog.show(this, "Loading", "Please wait", true);
  59. new LoadFilters().execute();
  60. gridView.setOnScrollListener(new AbsListView.OnScrollListener() {
  61. @Override
  62. public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
  63. if (firstVisibleItem + visibleItemCount >= totalItemCount) {
  64. if (!loading) {
  65. new LoadFilters().execute();
  66. progress.setMessage("Loading filters");
  67. progress.show();
  68. }
  69. }
  70. }
  71.  
  72. @Override
  73. public void onScrollStateChanged(AbsListView view, int scrollState) {
  74. }
  75. });
  76. gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  77. @Override
  78. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  79. if (filters.get(position).downloaded) return;
  80. System.out.println(filters.get(position).image);
  81. new SaveFilter(filters.get(position)).execute();
  82. ((ViewHolder) view.getTag()).title.setBackgroundColor(0xaa00ff00);
  83. }
  84. });
  85. }
  86.  
  87. class FilterAdapter extends BaseAdapter {
  88. public View getView(int position, View convertView, ViewGroup parent) {
  89. ViewHolder vh;
  90. if (convertView == null) {
  91. convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.filter_element, null);
  92. vh = new ViewHolder();
  93. vh.image = (ImageView) convertView.findViewById(R.id.filter);
  94. vh.title = (TextView) convertView.findViewById(R.id.filter_title);
  95. convertView.setTag(vh);
  96. } else {
  97. vh = (ViewHolder) convertView.getTag();
  98. }
  99. vh.filter = filters.get(position);
  100. vh.image.setImageBitmap(null);
  101. String text = vh.filter.name + "\nAuthor: " + vh.filter.author + "\n Score: " + vh.filter.score;
  102. vh.title.setText(text);
  103. DrawableManager.fetchDrawableOnThread(vh.filter.preview, vh.image);
  104. if (vh.filter.downloaded)
  105. vh.title.setBackgroundColor(0xaa00ff00);
  106. else
  107. vh.title.setBackgroundColor(0xaa000000);
  108. return convertView;
  109. }
  110.  
  111. @Override
  112. public int getCount() {
  113. return filters.size();
  114. }
  115.  
  116. @Override
  117. public Object getItem(int position) {
  118. return filters.get(position);
  119. }
  120.  
  121. @Override
  122. public long getItemId(int position) {
  123. return position;
  124. }
  125.  
  126. @Override
  127. public boolean hasStableIds() {
  128. return true;
  129. }
  130. }
  131.  
  132. class ViewHolder {
  133. RedditFilter filter;
  134. TextView title;
  135. ImageView image;
  136. }
  137.  
  138. class RedditFilter {
  139. String id;
  140. String name;
  141. String preview;
  142. String image;
  143. String author;
  144. int score;
  145. boolean downloaded;
  146.  
  147. @Override
  148. public String toString() {
  149. return "RedditFilter{" +
  150. "id='" + id + '\'' +
  151. ", name='" + name + '\'' +
  152. ", preview='" + preview + '\'' +
  153. ", image='" + image + '\'' +
  154. ", author='" + author + '\'' +
  155. ", score=" + score +
  156. ", downloaded=" + downloaded +
  157. '}';
  158. }
  159. }
  160.  
  161. class LoadFilters extends AsyncTask<Void, Void, Void> {
  162.  
  163. @Override
  164. protected void onPreExecute() {
  165. loading = true;
  166. }
  167.  
  168. @Override
  169. protected Void doInBackground(Void... params) {
  170. DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
  171. String uri = "https://www.reddit.com/r/snapprefs/hot.json?limit=25";//we can increase limit
  172. if (after != null && !after.isEmpty()) {
  173. uri += "&after=" + after;//better don't change it :P
  174. }
  175. HttpGet get = new HttpGet(uri);
  176. get.setHeader("Content-type", "application/json");
  177.  
  178. InputStream inputStream = null;
  179. String result = null;
  180. try {
  181. HttpResponse response = httpclient.execute(get);
  182. HttpEntity entity = response.getEntity();
  183. inputStream = entity.getContent();
  184. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
  185. StringBuilder sb = new StringBuilder();
  186. String line;
  187. while ((line = reader.readLine()) != null) {
  188. sb.append(line + "\n");
  189. }
  190. result = sb.toString();
  191. } catch (Exception ignored) {
  192. } finally {
  193. try {
  194. if (inputStream != null) inputStream.close();
  195. } catch (Exception ignored) {
  196. }
  197. }
  198. try {
  199. JSONObject jObject = new JSONObject(result);
  200. after = jObject.getJSONObject("data").getString("after");
  201. JSONArray jsonArray = jObject.getJSONObject("data").getJSONArray("children");
  202. for (int i = 0; i < jsonArray.length(); i++) {
  203. JSONObject obj = jsonArray.getJSONObject(i).getJSONObject("data");
  204. if (obj.getString("domain").equalsIgnoreCase("self.snapprefs") || !obj.has("preview") || obj.getString("title").toLowerCase().contains("[request]"))//needs preview tag, can't be self post and filter out requests
  205. continue;
  206. RedditFilter f = new RedditFilter();
  207. f.id = obj.getString("id");
  208. f.score = obj.getInt("score");
  209. f.name = obj.getString("title");
  210. f.preview = obj.getString("thumbnail");//little image for preview
  211. f.image = obj.getJSONObject("preview").getJSONArray("images").getJSONObject(0).getJSONObject("source").getString("url");//full resolution
  212. f.author = obj.getString("author");
  213. f.downloaded = new File(filtersDir, f.id + ".jpg").exists();//named after reddit id so i know if this filter is already downloaded
  214. filters.add(f);
  215. }
  216. } catch (JSONException e) {
  217. e.printStackTrace();
  218. }
  219. return null;
  220. }
  221.  
  222. @Override
  223. protected void onPostExecute(Void aVoid) {
  224. progress.dismiss();
  225. ((FilterAdapter) gridView.getAdapter()).notifyDataSetChanged();
  226. gridView.invalidateViews();
  227. loading = false;
  228. }
  229. }
  230.  
  231. class SaveFilter extends AsyncTask<Void, Void, Boolean> {
  232.  
  233. private RedditFilter redditFilter;
  234.  
  235. public SaveFilter(RedditFilter redditFilter) {
  236. this.redditFilter = redditFilter;
  237. }
  238.  
  239. @Override
  240. protected void onPreExecute() {
  241. progress.setMessage("Downloading filter");
  242. progress.show();
  243. }
  244.  
  245. @Override
  246. protected Boolean doInBackground(Void... params) {
  247. try {
  248. DefaultHttpClient httpClient = new DefaultHttpClient();
  249. HttpGet request = new HttpGet(redditFilter.image);
  250. HttpResponse response = httpClient.execute(request);
  251. InputStream input = response.getEntity().getContent();
  252. File f = new File(filtersDir, redditFilter.id + ".jpg");
  253. FileOutputStream output = new FileOutputStream(f);
  254. try {
  255. byte[] buffer = new byte[4096];
  256. int read;
  257.  
  258. while ((read = input.read(buffer)) != -1) {
  259. output.write(buffer, 0, read);
  260. }
  261. output.flush();
  262. } finally {
  263. output.close();
  264. input.close();
  265. }
  266. } catch (Exception e) {
  267. e.printStackTrace();
  268. return false;
  269. }
  270. return true;
  271. }
  272.  
  273. @Override
  274. protected void onPostExecute(Boolean result) {
  275. progress.dismiss();
  276. if (result)
  277. redditFilter.downloaded = true;
  278. else
  279. Toast.makeText(getApplicationContext(), "Failed to download filter!", Toast.LENGTH_LONG).show();
  280. }
  281. }
  282.  
  283. }
Add Comment
Please, Sign In to add comment