Advertisement
Guest User

Untitled

a guest
Oct 6th, 2015
438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 23.10 KB | None | 0 0
  1. package com.paymon.tutorialapp;
  2.  
  3.  
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.SharedPreferences;
  7. import android.database.Cursor;
  8. import android.graphics.Point;
  9. import android.net.ConnectivityManager;
  10. import android.net.NetworkInfo;
  11. import android.net.Uri;
  12. import android.os.AsyncTask;
  13. import android.os.Bundle;
  14. import android.preference.PreferenceManager;
  15. import android.support.v4.app.Fragment;
  16. import android.view.Display;
  17. import android.view.LayoutInflater;
  18. import android.view.View;
  19. import android.view.ViewGroup;
  20. import android.view.WindowManager;
  21. import android.widget.AdapterView;
  22. import android.widget.GridView;
  23. import android.widget.LinearLayout;
  24. import android.widget.TextView;
  25.  
  26. import org.json.JSONArray;
  27. import org.json.JSONException;
  28. import org.json.JSONObject;
  29.  
  30. import java.io.BufferedReader;
  31. import java.io.IOException;
  32. import java.io.InputStream;
  33. import java.io.InputStreamReader;
  34. import java.net.HttpURLConnection;
  35. import java.net.URL;
  36. import java.util.ArrayList;
  37. import java.util.Arrays;
  38.  
  39. //sample movie path: "/kqjL17yufvn9OVLyXYpvtyrFfak.jpg"
  40. public  class MoviesFragment extends Fragment {
  41. static GridView gridview;
  42.     static int width;
  43.     static ArrayList<String> posters;
  44.     static boolean sortByPop = true;
  45.     static String API_KEY = "14bb2e410981baf68982e32ec2c4735b";
  46.  
  47.     static PreferenceChangeListener listener;
  48.     static SharedPreferences prefs;
  49.     static boolean sortByFavorites;
  50.     static ArrayList<String> postersF;
  51.     static ArrayList<String> titlesF;
  52.     static ArrayList<String> datesF;
  53.     static ArrayList<String> ratingsF;
  54.     static ArrayList<String> youtubesF;
  55.     static ArrayList<String> youtubes2F;
  56.     static ArrayList<ArrayList<String>> commentsF;
  57.     static ArrayList<String> overviewsF;
  58.  
  59.     static ArrayList<String> overviews;
  60.     static ArrayList<String> titles;
  61.     static ArrayList<String> dates;
  62.     static ArrayList<String> ratings;
  63.     static ArrayList<String> youtubes;
  64.     static ArrayList<String> youtubes2;
  65.     static ArrayList<String> ids;
  66.     static ArrayList<Boolean> favorited;
  67.     static ArrayList<ArrayList<String>> comments;
  68.  
  69.  
  70.     public MoviesFragment()
  71.     {
  72.     }
  73.  
  74.         @Override
  75.         public View onCreateView(LayoutInflater inflater, ViewGroup container,
  76.                 Bundle savedInstanceState) {
  77.             View rootView = inflater.inflate(R.layout.fragment_main, container, false);
  78.  
  79.             WindowManager wm =(WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
  80.             Display display = wm.getDefaultDisplay();
  81.             Point size = new Point();
  82.             display.getSize(size);
  83.             if(MainActivity.TABLET)
  84.             {
  85.                 width = size.x/6;
  86.             }
  87.             else width=size.x/3;
  88.             if(getActivity()!=null)
  89.             {
  90.                 ArrayList<String> array = new ArrayList<String>();
  91.                 ImageAdapter adapter = new ImageAdapter(getActivity(),array,width);
  92.                 gridview = (GridView)rootView.findViewById(R.id.gridview);
  93.  
  94.                 gridview.setColumnWidth(width);
  95.                 gridview.setAdapter(adapter);
  96.             }
  97.             //listen for presses on gridview items
  98.             gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  99.                 @Override
  100.                 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  101.                     if (!sortByFavorites) {
  102.                         favorited = bindFavoritesToMovies();
  103.                         Intent intent = new Intent(getActivity(), DetailActivity.class).
  104.                                 putExtra("overview", overviews.get(position)).
  105.                                 putExtra("poster", posters.get(position)).
  106.                                 putExtra("title", titles.get(position)).
  107.                                 putExtra("date", dates.get(position)).
  108.                                 putExtra("rating", ratings.get(position)).
  109.                                 putExtra("youtube", youtubes.get(position)).
  110.                                 putExtra("youtube2", youtubes2.get(position)).
  111.                                 putExtra("comments", comments.get(position)).
  112.                                 putExtra("favorite", favorited.get(position));
  113.  
  114.                         startActivity(intent);
  115.  
  116.                     }
  117.                     else{
  118.                         Intent intent = new Intent(getActivity(), DetailActivity.class).
  119.                                 putExtra("overview", overviewsF.get(position)).
  120.                                 putExtra("poster", postersF.get(position)).
  121.                                 putExtra("title", titlesF.get(position)).
  122.                                 putExtra("date", datesF.get(position)).
  123.                                 putExtra("rating", ratingsF.get(position)).
  124.                                 putExtra("youtube", youtubesF.get(position)).
  125.                                 putExtra("youtube2", youtubes2F.get(position)).
  126.                                 putExtra("comments", commentsF.get(position)).
  127.                                 putExtra("favorite", favorited.get(position));
  128.  
  129.                         startActivity(intent);
  130.                     }
  131.                 }
  132.                 }
  133.  
  134.                 );
  135.  
  136.  
  137.                 return rootView;
  138.             }
  139.             private class PreferenceChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener{
  140.  
  141.  
  142.         @Override
  143.         public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
  144.             gridview.setAdapter(null);
  145.             onStart();
  146.         }
  147.     }
  148.     public ArrayList<Boolean> bindFavoritesToMovies()
  149.     {
  150.         ArrayList<Boolean> result = new ArrayList<>();
  151.         for(int i =0; i<titles.size();i++)
  152.         {
  153.             result.add(false);
  154.         }
  155.         for(String favoritedTitles: titlesF)
  156.         {
  157.             for(int x = 0; x<titles.size(); x++)
  158.             {
  159.                 if(favoritedTitles.equals(titles.get(x)))
  160.                 {
  161.                     result.set(x,true);
  162.                 }
  163.             }
  164.         }
  165.         return result;
  166.     }
  167.     @Override
  168.     public void onStart()
  169.     {
  170.         super.onStart();
  171.         prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
  172.         listener = new PreferenceChangeListener();
  173.         prefs.registerOnSharedPreferenceChangeListener(listener);
  174.  
  175.         if(prefs.getString("sortby","popularity").equals("popularity"))
  176.         {
  177.             getActivity().setTitle("Most Popular Movies");
  178.             sortByPop = true;
  179.             sortByFavorites=false;
  180.         }
  181.         else if(prefs.getString("sortby","popularity").equals("rating"))
  182.         {
  183.             getActivity().setTitle("Highest Rated Movies");
  184.             sortByPop = false;
  185.             sortByFavorites=false;
  186.         }
  187.         else if(prefs.getString("sortby","popularity").equals("favorites"))
  188.         {
  189.             getActivity().setTitle("Favorited Movies");
  190.             sortByPop = false;
  191.             sortByFavorites=true;
  192.         }
  193.         TextView textView = new TextView(getActivity());
  194.         LinearLayout layout = (LinearLayout)getActivity().findViewById(R.id.linearlayout);
  195.         loadFavoritesData();
  196.         if(sortByFavorites)
  197.         {
  198.             if(postersF.size()==0)
  199.             {
  200.                 textView.setText("You have no favorites movies.");
  201.                 if(layout.getChildCount()==1)
  202.                     layout.addView(textView);
  203.                 gridview.setVisibility(GridView.GONE);
  204.             }
  205.             else{
  206.                 gridview.setVisibility(GridView.VISIBLE);
  207.                 layout.removeView(textView);
  208.             }
  209.             if(postersF!=null&&getActivity()!=null)
  210.             {
  211.                 ImageAdapter adapter = new ImageAdapter(getActivity(),postersF,width);
  212.                 gridview.setAdapter(adapter);
  213.             }
  214.         }
  215.         else {
  216.             gridview.setVisibility(GridView.VISIBLE);
  217.             layout.removeView(textView);
  218.  
  219.  
  220.             if (isNetworkAvailable()) {
  221.  
  222.                 new ImageLoadTask().execute();
  223.             } else {
  224.                 TextView textview1 = new TextView(getActivity());
  225.                 LinearLayout layout1 = (LinearLayout) getActivity().findViewById(R.id.linearlayout);
  226.                 textview1.setText("You are not connected to the Internet");
  227.                 if (layout1.getChildCount() == 1) {
  228.                     layout1.addView(textview1);
  229.                 }
  230.                 gridview.setVisibility(GridView.GONE);
  231.             }
  232.         }
  233.     }
  234. public void loadFavoritesData()
  235. {
  236.     String URL = "content://com.paymon.provider.Movies/movies";
  237.     Uri movies = Uri.parse(URL);
  238.     Cursor c = getActivity().getContentResolver().query(movies,null,null,null,"title");
  239.     postersF = new ArrayList<String>();
  240.     titlesF = new ArrayList<String>();
  241.     datesF = new ArrayList<String>();
  242.     overviewsF = new ArrayList<String>();
  243.     favorited = new ArrayList<Boolean>();
  244.     commentsF = new ArrayList<ArrayList<String>>();
  245.     youtubesF = new ArrayList<String>();
  246.     youtubes2F = new ArrayList<String>();
  247.     ratingsF = new ArrayList<String>();
  248.     if(c==null) return;
  249.     while(c.moveToNext())
  250.     {
  251.         postersF.add(c.getString(c.getColumnIndex(MovieProvider.NAME)));
  252.         commentsF.add(convertStringToArrayList(c.getString(c.getColumnIndex(MovieProvider.REVIEW))));
  253.         titlesF.add(c.getString(c.getColumnIndex(MovieProvider.TITLE)));
  254.         overviewsF.add(c.getString(c.getColumnIndex(MovieProvider.OVERVIEW)));
  255.         youtubesF.add(c.getString(c.getColumnIndex(MovieProvider.YOUTUBE1)));
  256.         youtubes2F.add(c.getString(c.getColumnIndex(MovieProvider.YOUTUBE2)));
  257.         datesF.add(c.getString(c.getColumnIndex(MovieProvider.DATE)));
  258.         ratingsF.add(c.getString(c.getColumnIndex(MovieProvider.RATING)));
  259.         favorited.add(true);
  260.  
  261.     }
  262. }
  263.     public ArrayList<String> convertStringToArrayList(String s)
  264.     {
  265.         ArrayList<String> result = new ArrayList<>(Arrays.asList(s.split("divider123")));
  266.         return result;
  267.     }
  268.     public boolean isNetworkAvailable()
  269.     {
  270.         ConnectivityManager connectivityManager = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
  271.         NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  272.         return activeNetworkInfo !=null &&activeNetworkInfo.isConnected();
  273.     }
  274.     public class ImageLoadTask extends AsyncTask<Void, Void, ArrayList<String>>{
  275.  
  276.         @Override
  277.         protected ArrayList<String> doInBackground(Void... params) {
  278.             while(true){
  279.                 try{
  280.                     posters = new ArrayList(Arrays.asList(getPathsFromAPI(sortByPop)));
  281.                     return posters;
  282.                 }
  283.                 catch(Exception e)
  284.                 {
  285.                     continue;
  286.                 }
  287.             }
  288.  
  289.         }
  290.         @Override
  291.         protected void onPostExecute(ArrayList<String>result)
  292.         {
  293.             if(result!=null && getActivity()!=null)
  294.             {
  295.                 ImageAdapter adapter = new ImageAdapter(getActivity(),result, width);
  296.                 gridview.setAdapter(adapter);
  297.  
  298.             }
  299.         }
  300.         public String[] getPathsFromAPI(boolean sortbypop)
  301.         {
  302.             while(true)
  303.             {
  304.  
  305.                 HttpURLConnection urlConnection = null;
  306.                 BufferedReader reader = null;
  307.                 String JSONResult;
  308.  
  309.                 try {
  310.                     String urlString = null;
  311.                     if (sortbypop) {
  312.                         urlString = "http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=" + API_KEY;
  313.                     } else {
  314.                         urlString = "http://api.themoviedb.org/3/discover/movie?sort_by=vote_average.desc&vote_count.gte=500&api_key=" + API_KEY;
  315.                     }
  316.                     URL url = new URL(urlString);
  317.                     urlConnection = (HttpURLConnection) url.openConnection();
  318.                     urlConnection.setRequestMethod("GET");
  319.                     urlConnection.connect();
  320.  
  321.                     //Read the input stream into a String
  322.                     InputStream inputStream = urlConnection.getInputStream();
  323.                     StringBuffer buffer = new StringBuffer();
  324.                     if (inputStream == null) {
  325.                         return null;
  326.                     }
  327.                     reader = new BufferedReader(new InputStreamReader(inputStream));
  328.                     String line;
  329.                     while ((line = reader.readLine()) != null) {
  330.                         buffer.append(line + "\n");
  331.                     }
  332.                     if (buffer.length() == 0) {
  333.                         return null;
  334.                     }
  335.                     JSONResult = buffer.toString();
  336.  
  337.                     try {
  338.                         overviews = new ArrayList<String>(Arrays.asList(getStringsFromJSON(JSONResult,"overview")));
  339.  
  340.                         titles = new ArrayList<String>(Arrays.asList(getStringsFromJSON(JSONResult,"original_title")));
  341.                         ratings = new ArrayList<String>(Arrays.asList(getStringsFromJSON(JSONResult,"vote_average")));
  342.                         dates = new ArrayList<String>(Arrays.asList(getStringsFromJSON(JSONResult,"release_date")));
  343.                         ids = new ArrayList<String>(Arrays.asList(getStringsFromJSON(JSONResult,"id")));
  344.                         while(true)
  345.                         {
  346.     youtubes = new ArrayList<String>(Arrays.asList(getYoutubesFromIds(ids,0)));
  347.                             youtubes2 = new ArrayList<String>(Arrays.asList(getYoutubesFromIds(ids,1)));
  348.                             int nullCount = 0;
  349.                             for(int i = 0; i<youtubes.size();i++)
  350.                             {
  351.                                 if(youtubes.get(i)==null)
  352.                                 {
  353.                                     nullCount++;
  354.                                     youtubes.set(i,"no video found");
  355.                                 }
  356.                             }
  357.                             for(int i = 0; i<youtubes2.size();i++)
  358.                             {
  359.                                 if(youtubes2.get(i)==null)
  360.                                 {
  361.                                     nullCount++;
  362.                                     youtubes2.set(i,"no video found");
  363.                                 }
  364.                             }
  365.                             if(nullCount>2)continue;
  366.                             break;
  367.                         }
  368.                         comments = getReviewsFromIds(ids);
  369.                         return getPathsFromJSON(JSONResult);
  370.  
  371.                     } catch (JSONException e) {
  372.                         continue;
  373.                     }
  374.                 }catch(Exception e)
  375.                 {
  376.                     continue;
  377.                 }finally {
  378.                     if(urlConnection!=null)
  379.                     {
  380.                         urlConnection.disconnect();
  381.                     }
  382.                     if(reader!=null)
  383.                     {
  384.                         try{
  385.                             reader.close();
  386.                         }catch(final IOException e)
  387.                         {
  388.                     }
  389.                 }
  390.             }
  391.  
  392.  
  393.         }
  394.  
  395.     }
  396.         public String[] getYoutubesFromIds(ArrayList<String> ids, int position)
  397.         {
  398.         String[] results = new String[ids.size()];
  399.             for(int i =0; i<ids.size(); i++)
  400.             {
  401.             HttpURLConnection urlConnection = null;
  402.             BufferedReader reader = null;
  403.             String JSONResult;
  404.  
  405.             try {
  406.                 String urlString = null;
  407.                 urlString = "http://api.themoviedb.org/3/movie/" + ids.get(i) + "/videos?api_key=" + API_KEY;
  408.  
  409.  
  410.                 URL url = new URL(urlString);
  411.                 urlConnection = (HttpURLConnection) url.openConnection();
  412.                 urlConnection.setRequestMethod("GET");
  413.                 urlConnection.connect();
  414.  
  415.                 //Read the input stream into a String
  416.                 InputStream inputStream = urlConnection.getInputStream();
  417.                 StringBuffer buffer = new StringBuffer();
  418.                 if (inputStream == null) {
  419.                     return null;
  420.                 }
  421.                 reader = new BufferedReader(new InputStreamReader(inputStream));
  422.                 String line;
  423.                 while ((line = reader.readLine()) != null) {
  424.                     buffer.append(line + "\n");
  425.                 }
  426.                 if (buffer.length() == 0) {
  427.                     return null;
  428.                 }
  429.                 JSONResult = buffer.toString();
  430.                 try {
  431.                     results[i] = getYoutubeFromJSON(JSONResult, position);
  432.                 } catch (JSONException E) {
  433.                     results[i] = "no video found";
  434.                 }
  435.                 } catch (Exception e) {
  436.  
  437.                 } finally {
  438.                     if (urlConnection != null) {
  439.                         urlConnection.disconnect();
  440.                     }
  441.                     if (reader != null) {
  442.                         try {
  443.                             reader.close();
  444.                         } catch (final IOException e) {
  445.                         }
  446.                     }
  447.                 }
  448.             }
  449.             return results;
  450.  
  451.         }
  452.         public ArrayList<ArrayList<String>> getReviewsFromIds(ArrayList<String> ids)
  453.         {
  454.             outerloop:
  455.             while(true)
  456.             {
  457.                 ArrayList<ArrayList<String>> results = new ArrayList<>();
  458.                 for(int i =0; i<ids.size(); i++)
  459.                 {
  460.                     HttpURLConnection urlConnection = null;
  461.                     BufferedReader reader = null;
  462.                     String JSONResult;
  463.  
  464.                     try {
  465.                         String urlString = null;
  466.                         urlString = "http://api.themoviedb.org/3/movie/" + ids.get(i) + "/reviews?api_key=" + API_KEY;
  467.                         URL url = new URL(urlString);
  468.                         urlConnection = (HttpURLConnection) url.openConnection();
  469.                         urlConnection.setRequestMethod("GET");
  470.                         urlConnection.connect();
  471.  
  472.                         //Read the input stream into a String
  473.                         InputStream inputStream = urlConnection.getInputStream();
  474.                         StringBuffer buffer = new StringBuffer();
  475.                         if (inputStream == null) {
  476.                             return null;
  477.                         }
  478.                         reader = new BufferedReader(new InputStreamReader(inputStream));
  479.                         String line;
  480.                         while ((line = reader.readLine()) != null) {
  481.                             buffer.append(line + "\n");
  482.                         }
  483.                         if (buffer.length() == 0) {
  484.                             return null;
  485.                         }
  486.                         JSONResult = buffer.toString();
  487.                         try {
  488.                             results.add(getCommentsFromJSON(JSONResult));
  489.                         } catch (JSONException E) {
  490.                             return null;
  491.                         }
  492.                     } catch (Exception e) {
  493.                         continue outerloop;
  494.  
  495.                     } finally {
  496.                         if (urlConnection != null) {
  497.                             urlConnection.disconnect();
  498.                         }
  499.                         if (reader != null) {
  500.                             try {
  501.                                 reader.close();
  502.                             } catch (final IOException e) {
  503.                             }
  504.                         }
  505.                     }
  506.                 }
  507.                 return results;
  508.  
  509.             }
  510.         }
  511.         public ArrayList<String> getCommentsFromJSON(String JSONStringParam)throws JSONException{
  512.             JSONObject JSONString = new JSONObject(JSONStringParam);
  513.             JSONArray reviewsArray = JSONString.getJSONArray("results");
  514.             ArrayList<String> results = new ArrayList<>();
  515.             if(reviewsArray.length()==0)
  516.             {
  517.                 results.add("No reviews found for this movie.");
  518.                 return results;
  519.             }
  520.             for(int i = 0; i<reviewsArray.length(); i++)
  521.             {
  522.                 JSONObject result = reviewsArray.getJSONObject(i);
  523.                 results.add(result.getString("content"));
  524.             }
  525.             return results;
  526.  
  527.         }
  528.         public String getYoutubeFromJSON(String JSONStringParam, int position) throws JSONException
  529.         {
  530.             JSONObject JSONString = new JSONObject(JSONStringParam);
  531.             JSONArray youtubesArray = JSONString.getJSONArray("results");
  532.             JSONObject youtube;
  533.             String result = "no videos found";
  534.             if(position ==0)
  535.             {
  536.                 youtube = youtubesArray.getJSONObject(0);
  537.                 result = youtube.getString("key");
  538.             }
  539.             else if(position==1)
  540.             {
  541.                 if(youtubesArray.length()>1)
  542.                 {
  543.                     youtube = youtubesArray.getJSONObject(1);
  544.                 }
  545.                 else{
  546.                     youtube = youtubesArray.getJSONObject(0);
  547.                 }
  548.                 result = youtube.getString("key");
  549.             }
  550.             return result;
  551.         }
  552.         public String[] getStringsFromJSON(String JSONStringParam, String param)  throws JSONException
  553.         {
  554.             JSONObject JSONString = new JSONObject(JSONStringParam);
  555.  
  556.             JSONArray moviesArray = JSONString.getJSONArray("results");
  557.             String[] result = new String[moviesArray.length()];
  558.  
  559.             for(int i = 0; i<moviesArray.length();i++)
  560.             {
  561.                 JSONObject movie = moviesArray.getJSONObject(i);
  562.                 if(param.equals("vote_average"))
  563.                 {
  564.                     Double number = movie.getDouble("vote_average");
  565.                     String rating =Double.toString(number)+"/10";
  566.                     result[i]=rating;
  567.                 }
  568.                 else {
  569.                     String data = movie.getString(param);
  570.                     result[i] = data;
  571.                 }
  572.             }
  573.             return result;
  574.         }
  575.         public String[] getPathsFromJSON(String JSONStringParam) throws JSONException{
  576.  
  577.             JSONObject JSONString = new JSONObject(JSONStringParam);
  578.  
  579.             JSONArray moviesArray = JSONString.getJSONArray("results");
  580.             String[] result = new String[moviesArray.length()];
  581.  
  582.             for(int i = 0; i<moviesArray.length();i++)
  583.             {
  584.                 JSONObject movie = moviesArray.getJSONObject(i);
  585.                 String moviePath = movie.getString("poster_path");
  586.                 result[i] = moviePath;
  587.             }
  588.             return result;
  589.         }
  590.     }
  591. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement