Advertisement
iXaDe

iPoema.java [COMPLETO]

Mar 13th, 2014
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 21.62 KB | None | 0 0
  1. package com.cubika.iPoema;
  2.  
  3. import java.io.*;
  4. import java.net.MalformedURLException;
  5. import java.net.URI;
  6. import java.net.URISyntaxException;
  7. import java.net.URL;
  8. import java.net.URLConnection;
  9. import java.util.*;
  10.  
  11. import android.annotation.TargetApi;
  12. import android.app.AlertDialog;
  13. import android.app.ProgressDialog;
  14. import android.content.*;
  15. import android.content.pm.PackageInfo;
  16. import android.net.*;
  17. import android.content.pm.PackageManager;
  18. import android.os.*;
  19. import android.support.v7.app.*;
  20. import android.support.v4.view.*;
  21. import android.support.v4.app.*;
  22. import android.view.*;
  23. import android.widget.*;
  24. import org.jdom2.*;
  25. import org.jdom2.input.*;
  26. import org.apache.http.util.ByteArrayBuffer;
  27.  
  28. @TargetApi(Build.VERSION_CODES.CUPCAKE)
  29. public class iPoema extends ActionBarActivity {
  30.  
  31.     /**
  32.      * The {@link android.support.v4.view.PagerAdapter} that will provide
  33.      * fragments for each of the sections. We use a
  34.      * {@link FragmentPagerAdapter} derivative, which will keep every
  35.      * loaded fragment in memory. If this becomes too memory intensive, it
  36.      * may be best to switch to a
  37.      * {@link android.support.v4.app.FragmentStatePagerAdapter}.
  38.      */
  39.     private static String PATH = Environment.getExternalStorageDirectory()+"/Download/";
  40.     private PackageInfo Pi = null;
  41.     int lenghtOfFile = 0;
  42.     int progress = 0;
  43.     String titulo[] = new String[20];
  44.     String texto[] = new String[20];
  45.     String autor[] = new String[20];
  46.     SectionsPagerAdapter mSectionsPagerAdapter;
  47.  
  48.     /**
  49.      * The {@link ViewPager} that will host the section contents.
  50.      */
  51.     ViewPager mViewPager;
  52.  
  53.     @Override
  54.     protected void onCreate(Bundle savedInstanceState) {
  55.         super.onCreate(savedInstanceState);
  56.         setContentView(R.layout.activity_i_poema);
  57.  
  58.         try {
  59.             Pi = getPackageManager().getPackageInfo(getPackageName(), 0);
  60.         } catch (PackageManager.NameNotFoundException e) { }
  61.  
  62.         File arquivo = new File(PATH + "iPoema.xml");
  63.         if (arquivo.exists() == true) {
  64.             readXML();
  65.         } else {
  66.             refresh();
  67.         }
  68.  
  69.         // Create the adapter that will return a fragment for each of the three
  70.         // primary sections of the activity.
  71.         mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
  72.  
  73.         // Set up the ViewPager with the sections adapter.
  74.         mViewPager = (ViewPager) findViewById(R.id.pager);
  75.         mViewPager.setAdapter(mSectionsPagerAdapter);
  76.  
  77.     }
  78.  
  79.  
  80.     @Override
  81.     public boolean onCreateOptionsMenu(Menu menu) {
  82.        
  83.         // Inflate the menu; this adds items to the action bar if it is present.
  84.         getMenuInflater().inflate(R.menu.i_poema, menu);
  85.         return true;
  86.     }
  87.  
  88.     @Override
  89.     public boolean onOptionsItemSelected(MenuItem item) {
  90.         // Handle action bar item clicks here. The action bar will
  91.         // automatically handle clicks on the Home/Up button, so long
  92.         // as you specify a parent activity in AndroidManifest.xml.
  93.         int id = item.getItemId();
  94.         if (id == R.id.action_refresh) {
  95.             refresh();
  96.             return true;
  97.         } else if (id == R.id.action_settings) {
  98.             Intent intent = new Intent(this, Settings.class);
  99.             startActivity(intent);
  100.             return true;
  101.         } else if (id == R.id.action_update) {
  102.             loadAtualizacao();
  103.             return true;
  104.         } else {
  105.             return super.onOptionsItemSelected(item);
  106.         }
  107.     }
  108.  
  109.     public void readXML() {
  110.         final ProgressDialog d  = new ProgressDialog(this);
  111.         d.setMessage("Recebendo os dados de XML...");
  112.         d.setTitle("Lendo arquivo");
  113.         d.setIndeterminate(false);
  114.         d.setProgress(0);
  115.         d.setMax(100);
  116.         d.setProgressStyle(ProgressDialog.STYLE_SPINNER);
  117.         d.setCancelable(true);
  118.         d.show();
  119.         new Thread(new Runnable() {
  120.             @Override
  121.             public void run() {
  122.                 try {
  123.                     Thread.sleep(5000);
  124.                     lerXML.execute();
  125.                 } catch (Exception e) {
  126.                     showMessage(e.getClass().getName(), "Não foi possível receber os dados do XML.");
  127.                 }
  128.                 d.dismiss();
  129.             }
  130.         }).start();
  131.     }
  132.  
  133.     public String getTitulo(int i) {
  134.         return titulo[i];
  135.     }
  136.  
  137.     public String getTexto(int i) throws UnsupportedEncodingException {
  138.         String text = null;
  139.         text = texto[i];
  140.         text = text.replaceAll("</p>", "\n");
  141.         text = text.replaceAll("<p>", "");
  142.         text = text.replaceAll("<br/>", "\n");
  143.         text = text.replaceAll("&#8217;", "'");
  144.         text = text.replaceAll("&#8220;", "\"");
  145.         text = text.replaceAll("&#8221;", "\"");
  146.         return text;
  147.     }
  148.  
  149.     public String getAutor(int i) {
  150.         return autor[i];
  151.     }
  152.  
  153.     public void showMessage(String title, String text) {
  154.         AlertDialog.Builder builder = new AlertDialog.Builder(this);
  155.         builder.setCancelable(false);
  156.         builder.setTitle(title);
  157.         builder.setMessage(text);
  158.         builder.setIcon(R.drawable.ic_launcher);
  159.         builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
  160.             @Override
  161.             public void onClick(DialogInterface dialog, int which) {
  162.                 dialog.cancel();
  163.             }
  164.         });
  165.         AlertDialog alert = builder.create();
  166.         alert.show();
  167.     }
  168.  
  169.     public void loadAtualizacao() {
  170.         final ProgressDialog d  = new ProgressDialog(this);
  171.         d.setMessage("Checando versão de iPoema...");
  172.         d.setTitle("Aguarde");
  173.         d.setIndeterminate(false);
  174.         d.setProgress(0);
  175.         d.setMax(100);
  176.         d.setProgressStyle(ProgressDialog.STYLE_SPINNER);
  177.         d.setCancelable(true);
  178.         d.show();
  179.         new Thread(new Runnable() {
  180.             @Override
  181.             public void run() {
  182.                 try {
  183.                     Thread.sleep(5000);
  184.                     atualizaApp.execute();
  185.                 } catch (Exception e) {
  186.                     showMessage(e.getClass().getName(), "Não foi possível receber os dados de versão.");
  187.                 }
  188.                 d.dismiss();
  189.             }
  190.         }).start();
  191.     }
  192.  
  193.     public void refresh() {
  194.         final ProgressDialog d  = new ProgressDialog(this);
  195.         d.setMessage("Recebendo dados de Feed");
  196.         d.setTitle("Atualizando");
  197.         d.setIndeterminate(false);
  198.         d.setProgress(0);
  199.         d.setMax(100);
  200.         d.setProgressStyle(ProgressDialog.STYLE_SPINNER);
  201.         d.setCancelable(true);
  202.         d.show();
  203.         new Thread(new Runnable() {
  204.             @Override
  205.             public void run() {
  206.                 try {
  207.                     Thread.sleep(3000);
  208.                     getFeed.execute();
  209.                 } catch (Exception e) {
  210.                     showMessage(e.getClass().getName(), "Não foi possível receber os dados de Feed.");
  211.                 }
  212.                 d.dismiss();
  213.             }
  214.         }).start();
  215.     }
  216.  
  217.     AsyncTask<Void, Void, String> getFeed = new AsyncTask<Void, Void, String>(){
  218.         @Override
  219.         protected String doInBackground(Void... params) {
  220.             String retorno = "não";
  221.             try {
  222.                 // Baixar Feed
  223.                 URL url = new URL("http://www.ipoema.tumblr.com/rss");
  224.                 File file = new File(PATH + "iPoema.xml");
  225.                 file.delete();
  226.                 URLConnection ucon = url.openConnection();
  227.                 InputStream is = ucon.getInputStream();
  228.                 BufferedInputStream bis = new BufferedInputStream(is);
  229.                 ByteArrayBuffer baf = new ByteArrayBuffer(50);
  230.                 lenghtOfFile = ucon.getContentLength();
  231.                 int current = 0;
  232.                 while ((current = bis.read()) != -1) {
  233.                     baf.append((byte) current);
  234.                     progress = current;
  235.                 }
  236.                 FileOutputStream fos = new FileOutputStream(file);
  237.                 fos.write(baf.toByteArray());
  238.                 fos.close();
  239.                 retorno = "sim";
  240.             } catch (IOException e) {
  241.                 showMessage(e.getClass().getName(), "Erro ao tentar realizar o download do arquivo.");
  242.             }
  243.             return retorno;
  244.         }
  245.  
  246.         @Override
  247.         protected void onPostExecute(String s) {
  248.             super.onPostExecute(s);
  249.             if (s.equals("sim")) {
  250.                 try {
  251.                     lerXML.execute();
  252.                 } catch (Exception e) {
  253.                     showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do arquivo.");
  254.                 }
  255.             }
  256.         }
  257.     };
  258.  
  259.     AsyncTask<Void, Void, String> lerXML = new AsyncTask<Void, Void, String>(){
  260.         @Override
  261.         protected String doInBackground(Void... params) {
  262.             String state = "erro";
  263.             try {
  264.                 // Ler XML
  265.                 showMessage("iPoema", "Arquivo lido com sucesso");
  266.                 File f = new File(PATH + "iPoema.xml");
  267.                 SAXBuilder sb = new SAXBuilder();
  268.                 Document d = sb.build(f);
  269.                 Element mural = d.getRootElement();
  270.                 List<Element> elements = mural.getChildren("channel");
  271.                 Iterator<Element> i = elements.iterator();
  272.                 int x = 0;
  273.                 //for (int x = 0; x <= elements.size(); x++) {
  274.                 while (i.hasNext()) {
  275.                     //Element node = (Element) elements.get(x);
  276.                     Element node = (Element) i.next();
  277.                     Element item = node.getChild("item");
  278.  
  279.                     titulo[x] = item.getChildText("title");
  280.                     texto[x] = item.getChildText("description");
  281.                     autor[x] = item.getChildText("category");
  282.                     x++;
  283.                 }
  284.                 state = "ok";
  285.             } catch (JDOMException e) {
  286.                 showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do XML.");
  287.             } catch (IOException e) {
  288.                 showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do XML.");
  289.             }
  290.             return state;
  291.         }
  292.  
  293.         @Override
  294.         protected void onPostExecute(String s) {
  295.             super.onPostExecute(s);
  296.             if (s.equals("ok")) {
  297.                 try {
  298.                     // Títulos
  299.                     TextView titulo1 = (TextView) findViewById(R.id.titulo1);
  300.                     TextView titulo2 = (TextView) findViewById(R.id.titulo2);
  301.                     TextView titulo3 = (TextView) findViewById(R.id.titulo3);
  302.                     TextView titulo4 = (TextView) findViewById(R.id.titulo4);
  303.  
  304.                     // Textos
  305.                     TextView texto1 = (TextView) findViewById(R.id.texto1);
  306.                     TextView texto2 = (TextView) findViewById(R.id.texto2);
  307.                     TextView texto3 = (TextView) findViewById(R.id.texto3);
  308.                     TextView texto4 = (TextView) findViewById(R.id.texto4);
  309.  
  310.                     // SetText
  311.                     titulo1.setText(getTitulo(0));
  312.                     texto1.setText(getTexto(0)+"\n\n#"+getAutor(0)+"\n\n");
  313.  
  314.                     titulo2.setText(getTitulo(1));
  315.                     texto2.setText(getTexto(1)+"\n\n#"+getAutor(1)+"\n\n");
  316.  
  317.                     titulo3.setText(getTitulo(2));
  318.                     texto3.setText(getTexto(2)+"\n\n#"+getAutor(2)+"\n\n");
  319.  
  320.                     titulo4.setText(getTitulo(3));
  321.                     texto4.setText(getTexto(3)+"\n\n#"+getAutor(3)+"\n\n");
  322.  
  323.                     // Exibe
  324.                     titulo1.setVisibility(TextView.VISIBLE);
  325.                     texto1.setVisibility(TextView.VISIBLE);
  326.  
  327.                     titulo2.setVisibility(TextView.VISIBLE);
  328.                     texto2.setVisibility(TextView.VISIBLE);
  329.  
  330.                     titulo3.setVisibility(TextView.VISIBLE);
  331.                     texto3.setVisibility(TextView.VISIBLE);
  332.  
  333.                     titulo4.setVisibility(TextView.VISIBLE);
  334.                     texto4.setVisibility(TextView.VISIBLE);
  335.                 } catch (Exception e) {
  336.                     showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do arquivo.");
  337.                 }
  338.             }
  339.         }
  340.     };
  341.  
  342.     AsyncTask<Void, Void, String> atualizaApp = new AsyncTask<Void, Void, String>(){
  343.         @Override
  344.         protected String doInBackground(Void... params) {
  345.             String versao = "0";
  346.             try {
  347.                 // Baixar iPoema.txt
  348.                 URL url = new URL("http://www.xadees.xpg.com.br/iPoema.txt");
  349.                 File file = new File(PATH + "iPoema.txt");
  350.                 file.delete();
  351.                 URLConnection ucon = url.openConnection();
  352.                 InputStream is = ucon.getInputStream();
  353.                 BufferedInputStream bis = new BufferedInputStream(is);
  354.                 ByteArrayBuffer baf = new ByteArrayBuffer(50);
  355.                 lenghtOfFile = ucon.getContentLength();
  356.                 int current = 0;
  357.                 while ((current = bis.read()) != -1) {
  358.                     baf.append((byte) current);
  359.                     progress = current;
  360.                 }
  361.                 FileOutputStream fos = new FileOutputStream(file);
  362.                 fos.write(baf.toByteArray());
  363.                 fos.close();
  364.  
  365.                 // Ler iPoema.txt
  366.                 StringBuilder text = new StringBuilder();
  367.                 BufferedReader br = new BufferedReader(new FileReader(file));
  368.                 String line;
  369.                 while ((line = br.readLine()) != null) {
  370.                     text.append(line);
  371.                 }
  372.                 versao = text.toString();
  373.             } catch (IOException e) {
  374.                 showMessage(e.getClass().getName(), "Erro ao tentar realizar o download do arquivo.");
  375.             } catch (Exception e) {
  376.                 showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do arquivo.");
  377.             }
  378.  
  379.             return versao;
  380.         }
  381.  
  382.         @Override
  383.         protected void onPostExecute(String s) {
  384.             super.onPostExecute(s);
  385.             int vAtual = Pi.versionCode;
  386.             int vAPK = Integer.parseInt(s);
  387.  
  388.             if (vAtual < vAPK) {
  389.                 try {
  390.                     // Baixar
  391.                     URL url = new URL("http://www.xadees.xpg.com.br/iPoema%20for%20Android.apk");
  392.                     File file = new File(PATH + "iPoema.apk");
  393.                     file.delete();
  394.                     URLConnection ucon = url.openConnection();
  395.                     InputStream is = ucon.getInputStream();
  396.                     BufferedInputStream bis = new BufferedInputStream(is);
  397.                     ByteArrayBuffer baf = new ByteArrayBuffer(50);
  398.                     lenghtOfFile = ucon.getContentLength();
  399.                     int current = 0;
  400.                     while ((current = bis.read()) != -1) {
  401.                         baf.append((byte) current);
  402.                         progress = current;
  403.                     }
  404.                     FileOutputStream fos = new FileOutputStream(file);
  405.                     fos.write(baf.toByteArray());
  406.                     fos.close();
  407.  
  408.                     // Instalar
  409.                     Intent intent = new Intent(Intent.ACTION_VIEW);
  410.                     intent.setDataAndType(Uri.fromFile(new File(PATH + "iPoema.apk")), "application/vnd.android.package-archive");
  411.                     //java.lang.Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "adb install -r " + PATH + "iPoema.apk"});
  412.                     //proc.waitFor();
  413.                     startActivityForResult(intent,0);
  414.                 } catch (IOException e) {
  415.                     showMessage(e.getClass().getName(), "Erro ao tentar realizar o download do pacote.");
  416.                 }
  417.             } else {
  418.                 showMessage("iPoema", "iPoema já está atualizado.");
  419.             }
  420.         }
  421.     };
  422.  
  423.  
  424.    
  425.  
  426.     /**
  427.      * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
  428.      * one of the sections/tabs/pages.
  429.      */
  430.     public class SectionsPagerAdapter extends FragmentPagerAdapter {
  431.  
  432.         public SectionsPagerAdapter(FragmentManager fm) {
  433.             super(fm);
  434.         }
  435.  
  436.         @Override
  437.         public Fragment getItem(int position) {
  438.             // getItem is called to instantiate the fragment for the given page.
  439.             // Return a PlaceholderFragment (defined as a static inner class below).
  440.             return PlaceholderFragment.newInstance(position + 1);
  441.         }
  442.  
  443.         @Override
  444.         public int getCount() {
  445.             // Show 3 total pages.
  446.             return 3;
  447.         }
  448.  
  449.         @Override
  450.         public CharSequence getPageTitle(int position) {
  451.             Locale l = Locale.getDefault();
  452.             switch (position) {
  453.                 case 0:
  454.                     return getString(R.string.title_section1).toUpperCase(l);
  455.                 case 1:
  456.                     return getString(R.string.title_section2).toUpperCase(l);
  457.                 case 2:
  458.                     return getString(R.string.title_section3).toUpperCase(l);
  459.             }
  460.             return null;
  461.         }
  462.     }
  463.  
  464.     /**
  465.      * A placeholder fragment containing a simple view.
  466.      */
  467.     public static class PlaceholderFragment extends Fragment {
  468.         /**
  469.          * The fragment argument representing the section number for this
  470.          * fragment.
  471.          */
  472.         private static final String ARG_SECTION_NUMBER = "section_number";
  473.  
  474.         /**
  475.          * Returns a new instance of this fragment for the given section
  476.          * number.
  477.          */
  478.         public static PlaceholderFragment newInstance(int sectionNumber) {
  479.             PlaceholderFragment fragment = new PlaceholderFragment();
  480.             Bundle args = new Bundle();
  481.             args.putInt(ARG_SECTION_NUMBER, sectionNumber);
  482.             fragment.setArguments(args);
  483.             return fragment;
  484.         }
  485.  
  486.         public PlaceholderFragment() {
  487.         }
  488.  
  489.         @Override
  490.         public View onCreateView(LayoutInflater inflater, ViewGroup container,
  491.                 Bundle savedInstanceState) {
  492.             View rootView = inflater.inflate(R.layout.fragment_i_poema, container, false);
  493.  
  494.             // Componenetes
  495.             TextView section_label = (TextView) rootView.findViewById(R.id.section_label);
  496.             ImageView appLogo = (ImageView) rootView.findViewById(R.id.appLogo);
  497.  
  498.             // AboutApp() {
  499.             TextView aboutApp1 = (TextView) rootView.findViewById(R.id.aboutApp1);
  500.             TextView aboutApp2 = (TextView) rootView.findViewById(R.id.aboutApp2);
  501.             TextView appName = (TextView) rootView.findViewById(R.id.appName);
  502.             TextView appVersion = (TextView) rootView.findViewById(R.id.appVersion);
  503.             TextView appAutor = (TextView) rootView.findViewById(R.id.appAutor);
  504.             TextView appURL = (TextView) rootView.findViewById(R.id.appURL);
  505.  
  506.             appVersion.setText("Versão 1.4.0");
  507.             // }
  508.  
  509.             // AboutAutor() {
  510.             ImageView autorFoto = (ImageView) rootView.findViewById(R.id.autorFoto);
  511.             TextView aboutPotynho = (TextView) rootView.findViewById(R.id.aboutPotynho);
  512.             // }
  513.  
  514.             switch (getArguments().getInt(ARG_SECTION_NUMBER)) {
  515.                 case 1:
  516.                     section_label.setText(getString(R.string.title_section1));
  517.                     appLogo.setVisibility(ImageView.GONE);
  518.                     autorFoto.setVisibility(ImageView.GONE);
  519.                     aboutPotynho.setVisibility(TextView.GONE);
  520.                     aboutApp1.setVisibility(TextView.GONE);
  521.                     aboutApp2.setVisibility(TextView.GONE);
  522.                     appName.setVisibility(TextView.GONE);
  523.                     appVersion.setVisibility(TextView.GONE);
  524.                     appAutor.setVisibility(TextView.GONE);
  525.                     appURL.setVisibility(TextView.GONE);
  526.                     break;
  527.                 case 2:
  528.                     section_label.setText(getString(R.string.title_section2));
  529.                     appLogo.setVisibility(ImageView.VISIBLE);
  530.                     autorFoto.setVisibility(ImageView.GONE);
  531.                     aboutPotynho.setVisibility(TextView.GONE);
  532.                     aboutApp1.setVisibility(TextView.VISIBLE);
  533.                     aboutApp2.setVisibility(TextView.VISIBLE);
  534.                     appName.setVisibility(TextView.VISIBLE);
  535.                     appVersion.setVisibility(TextView.VISIBLE);
  536.                     appAutor.setVisibility(TextView.VISIBLE);
  537.                     appURL.setVisibility(TextView.VISIBLE);
  538.                     break;
  539.                 case 3:
  540.                     section_label.setText(getString(R.string.title_section3));
  541.                     appLogo.setVisibility(ImageView.GONE);
  542.                     autorFoto.setVisibility(ImageView.VISIBLE);
  543.                     aboutPotynho.setVisibility(TextView.VISIBLE);
  544.                     aboutApp1.setVisibility(TextView.GONE);
  545.                     aboutApp2.setVisibility(TextView.GONE);
  546.                     appName.setVisibility(TextView.GONE);
  547.                     appVersion.setVisibility(TextView.GONE);
  548.                     appAutor.setVisibility(TextView.GONE);
  549.                     appURL.setVisibility(TextView.GONE);
  550.                     break;
  551.                 default:
  552.                     section_label.setText("404: NOT FOUND!");
  553.                     break;
  554.             }
  555.             return rootView;
  556.         }
  557.     }
  558.  
  559. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement