Demasiado lenta mi aplicacion con SAXParser

36 views
Skip to first unread message

fernandosg

unread,
Feb 12, 2013, 7:08:56 AM2/12/13
to android...@googlegroups.com
Saludos.
Esta vez vengo con un problema de rendimiento, la verdad he leido tutoriales,checado codigos ya elaborados e implementarlos en lo que quiero hacer, creo que este fue un error fatal,espero alguien pueda ayudarme.
La aplicacion es un lector de feed xml de un blog en wordpress,
Basicamente lo unico que hace la aplicacion es al ingresar a una seccion te enlista los articulos de esa seccion, le añadi una mini paginacion(adelante y atras), para que siga leyendo por cada 10 articulos,en cada articulo tiene 2 botones, para compartir en twitter y facebook la url del post.
El proyecto tiene 3 archivos importantes que encontre en tutoriales para parsear xml: RssFeedReaderActivity,RssReaderListAdapter,RssFeedReaderActivity, y un archivo CustomHttpClient que es una clase en la cual tengo un metodo para encontrar el total de post en la pagina siguiente(para la paginacion), esto lo hice por que pense que tenia que ver con el rendimiento, me carga igual que si tuviera un codigo para contabilizar los siguientes elementos dentro de java, asi que no lo puse.

El sitio cuenta luego con imagenes(es un sitio de humor textual y grafico,chistes en resumen), la aplicacion cuando es una seccion grafica agarra el elemento content, con jsoup saco la imagen y la paso a bitmap para el imageview, no se si ese sea el problema, aun asi en los contenidos de solo texto, deshabilite eso, solamente se carga cuando se dirige a una seccion de humor grafico.

Este es mi RssFeedReaderActivity:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.paq.rsstest.CustomHttpClient;
import com.paq.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;

public class RssFeedReaderActivity extends Activity {
/** Called when the activity is first created. */
ListView _rssFeedListView;
List<JSONObject> jobs ;
List<RssFeedStructure> rssStr ;
private RssReaderListAdapter _adapter;
String sorti = "";
String mode = "";
Intent inte;  
Button sort_Btn;
ImageButton siguiente,atras;
String urlbase,url,url2;
int aumento,aumento2,cambio,humor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lalista);
inte=getIntent();      
     urlbase=inte.getStringExtra("url");
     //System.out.println("La url es "+urlbase);
     siguiente=(ImageButton)findViewById(R.id.boton_siguiente);
          atras=(ImageButton)findViewById(R.id.boton_atras);
        url=urlbase+"/feed/";
        aumento=inte.getIntExtra("pagina", 1);        
        humor=inte.getIntExtra("humor",0);
        aumento2=aumento+1;
        url2=url+"?paged="+aumento2;
        if(this.enviomensaje(url2)>0)
        siguiente.setVisibility(View.GONE);
        if(aumento==1)
        atras.setVisibility(View.INVISIBLE);
        
_rssFeedListView = (ListView)findViewById(R.id.list);
if(aumento>1)
       url=url+"?paged="+aumento; 
siguiente.setOnClickListener(new OnClickListener(){
       
@Override
public void onClick(View arg0) {
cambio=1;
recargar();
}
       
       });
       atras.setOnClickListener(new OnClickListener(){
        public void onClick(View arg0){
        cambio=0;
        recargar();
        }
       });
RssFeedTask rssTask = new RssFeedTask();
rssTask.execute();
}


public int enviomensaje(String url_post){
  ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
   
                  postParameters.add(new BasicNameValuePair("direccion", url_post));
                
   
   
   
                  String response = null;
   
                  try {
                      response = CustomHttpClient.executeHttpPost("http://fernandosegura.info/gecount.php", postParameters);
   
                      String res=response.toString();
                      if(res.contains("<b>Warning</b>")){
   
                  return 1;
   
                  }else{
                  return 0;
                  }
                      }catch (Exception e) {
   
                      return 1;
                  }

  }

@Override
protected void onRestart() {

    // TODO Auto-generated method stub
    super.onRestart();
    Intent i = new Intent(RssFeedReaderActivity.this, RssFeedReaderActivity.class);  //your class
    if(cambio==1)
    aumento=aumento+1;
    else{
    if(aumento>1)
    aumento=aumento-1;
    }
    i.putExtra("pagina", aumento);
    i.putExtra("url", urlbase);
    i.putExtra("humor", humor);
    startActivity(i);
    finish();

}

public void recargar(){
this.onRestart();
}


private class RssFeedTask extends AsyncTask<String, Void, String> {
// private String Content;
private ProgressDialog Dialog;
String response = "";
@Override
protected void onPreExecute() {
Dialog = new ProgressDialog(RssFeedReaderActivity.this);
Dialog.setMessage("Cargando...");
Dialog.show();
}
@Override
protected String doInBackground(String... urls) {
try {
String feed = url;
XmlHandler rh = new XmlHandler();
rssStr = rh.getLatestArticles(feed);
} catch (Exception e) {
}
return response;
}
@Override
protected void onPostExecute(String result) {
if(rssStr != null){
_adapter = new RssReaderListAdapter(RssFeedReaderActivity.this,rssStr,humor);
_rssFeedListView.setAdapter(_adapter);
}
Dialog.dismiss();
}
}
}



--------------------------------------------------------------------------------------------------------------------------------------------------------------
RssReaderListAdapter.java


package com.paq.rsstest;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.paq.R;
import com.paq.rsstest.RssFeedStructure;
import com.paq.vistas.verimagen_solo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class RssReaderListAdapter extends ArrayAdapter<RssFeedStructure> {
List<RssFeedStructure> imageAndTexts1 =null;
Context contexto;
int humor_cont;
public RssReaderListAdapter(Activity activity, List<RssFeedStructure> imageAndTexts,int humor) {
super(activity, 0, imageAndTexts);
contexto=activity.getBaseContext();
imageAndTexts1 = imageAndTexts;
humor_cont=humor;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {

Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();


View rowView = inflater.inflate(R.layout.rssitemview, null);
TextView textView = (TextView) rowView.findViewById(R.id.txtTitle);
TextView timeFeedText = (TextView) rowView.findViewById(R.id.txtDescription);
//ImageView imageView = (ImageView) rowView.findViewById(R.id.imagen_humor);
ImageButton humor=(ImageButton)rowView.findViewById(R.id.imagen_humor);
        try {
       
        //Log.d("rssfeed", "imageAndTexts1.get(position).getImgLink() :: " +imageAndTexts1.get(position).getImgLink() +" :: " +imageAndTexts1.get(position).getTitle());
        //textView.setText(imageAndTexts1.get(position).getTitle());
        SpannableString content = new SpannableString(imageAndTexts1.get(position).getEncodedContent());
        content.setSpan(new UnderlineSpan(), 0, 13, 0);        
        //System.out.println("el getencoded "+imageAndTexts1.get(position).getEncodedContent());
        Document doc = Jsoup.parse(""+content);
        String prueba=""+content;          
       
        String contenido=doc.body().text().replace("Tweet", " ").replace("Chistes", " ");
        final Elements pngs = doc.body().select("img[src$=.jpg]"); // img with src ending .png
        //final int humor2=humor_cont;
        if(humor_cont>0){          
            humor.setVisibility(View.VISIBLE);
             
             
              humor.setImageBitmap(this.getBitmapFromURL(pngs.last().attr("src")));
        }else{
        humor.setVisibility(View.INVISIBLE);
        }
         
         
         humor.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//Intent i=new Intent(this,verimagen_solo.class);
Intent intent = new Intent(contexto, verimagen_solo.class);
intent.putExtra("url_foto", pngs.last().attr("src"));
intent.putExtra("humor",RssReaderListAdapter.this.humor_cont );
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       contexto.startActivity(intent);
}
             
              });
         
        prueba=contenido.substring(contenido.lastIndexOf("/"));
        prueba=prueba.substring(prueba.indexOf(" "));
        if(prueba.contains("[...]")){
        prueba=prueba.substring(prueba.lastIndexOf("[...]")).replace("[...] ", " ");
        }else{
        prueba=prueba.substring(prueba.length()/2).replace("[...] ", " ");
        }
        timeFeedText.setText(prueba);
        //imageAndTexts1.get(position).getUrl();
       
       
        ImageButton compartir=(ImageButton)rowView.findViewById(R.id.boton_compartir_facebook);
            ImageButton twitter=(ImageButton)rowView.findViewById(R.id.boton_compartir_twitter);
            //System.out.println(imageAndTexts1.get(position).getUrl()+" la url");
            String pruebax=imageAndTexts1.get(position).getUrl();
            pruebax=pruebax.substring(pruebax.lastIndexOf("http://chistesbuenos.info/"));
        //feedStr.setUrl();
            final String enlace="http:"+pruebax.substring(pruebax.indexOf("/"),pruebax.lastIndexOf("/"));
            //System.out.println(enlace+" el enlace");
            compartir.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Genial "+enlace);
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
   if ((app.activityInfo.name).contains("facebook")) {
       final ActivityInfo activity = app.activityInfo;
       final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
       shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
       shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |             Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
       shareIntent.setComponent(name);
       v.getContext().startActivity(shareIntent);
       break;
  }else{
  String url = "http://www.facebook.com/share.php?u="+enlace;
  Intent i = new Intent(Intent.ACTION_VIEW);
  i.setData(Uri.parse(url));
  i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  contexto.startActivity(i);
  }
}
}
           
            });
            
            twitter.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Genial "+enlace);
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
   if ("com.twitter.android.PostActivity".equals(app.activityInfo.name)) {
       final ActivityInfo activity = app.activityInfo;
       final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
       shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
       shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |             Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
       shareIntent.setComponent(name);
       v.getContext().startActivity(shareIntent);
       break;
  }else{
  String url = "http://twitter.com/home?status=Genial este chiste, te lo recomiendo "+enlace;
  Intent i = new Intent(Intent.ACTION_VIEW);
  i.setData(Uri.parse(url));
  i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  contexto.startActivity(i);
  }
}
}
           
            });
       
       
        if(imageAndTexts1.get(position).getImgLink() !=null){
       
       
        URL feedImage= new URL(imageAndTexts1.get(position).getImgLink().toString());
       
        }
       
       
        } catch (MalformedURLException e) {
       
        }
        catch (IOException e) {
        
        }

return rowView;

}
public Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

}

------------------------------------------------------------------------------------------------------------------------

XmlHandler.java

package com.paq.rsstest;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class XmlHandler extends DefaultHandler {
private RssFeedStructure feedStr = new RssFeedStructure();
private List<RssFeedStructure> rssList = new ArrayList<RssFeedStructure>();
private int articlesAdded = 0;
// Number of articles to download
private static final int ARTICLES_LIMIT = 25;
StringBuffer chars = new StringBuffer();
public void startElement(String uri, String localName, String qName, Attributes atts) {
chars = new StringBuffer();
if (qName.equalsIgnoreCase("media:content"))
{
if(!atts.getValue("url").toString().equalsIgnoreCase("null")){
feedStr.setImgLink(atts.getValue("url").toString());
}
else{
feedStr.setImgLink("");
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("title"))
{
//feedStr.setTitle(chars.toString());
}
else if (localName.equalsIgnoreCase("encoded"))
{
feedStr.setEncodedContent(chars.toString());
}
else if (qName.equalsIgnoreCase("media:content"))
{
}
else if (localName.equalsIgnoreCase("link"))
{
feedStr.setUrl(chars.toString());
}
if (localName.equalsIgnoreCase("item")) {
rssList.add(feedStr);
feedStr = new RssFeedStructure();
articlesAdded++;
if (articlesAdded >= ARTICLES_LIMIT)
{
throw new SAXException();
}
}
}
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
public List<RssFeedStructure> getLatestArticles(String feedUrl) {
URL url = null;
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
} catch (SAXException e) {
} catch (ParserConfigurationException e) {
}
return rssList;
}
}

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

RssFeedStructure.java

package com.paq.rsstest;

import java.net.URL;


public class RssFeedStructure {

private long articleId;
private long feedId;
private String title;
private String description;
private String imgLink;
private String pubDate;
private String url;
private String encodedContent;

public long getArticleId() {
return articleId;
}

public void setArticleId(long articleId) {
this.articleId = articleId;
}

public long getFeedId() {
return feedId;
}
/**
* @param feedId the feedId to set
*/
public void setFeedId(long feedId) {
this.feedId = feedId;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = "";
}
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* @param url the url to set
*/
public void setUrl(String url) {
this.url = url;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;


if (description.contains("<img ")){
String img = description.substring(description.indexOf("<img "));
String cleanUp = img.substring(0, img.indexOf(">")+1);
img = img.substring(img.indexOf("src=") + 5);
int indexOf = img.indexOf("'");
if (indexOf==-1){
indexOf = img.indexOf("\"");
}
img = img.substring(0, indexOf);

//setImgLink(img);

this.description = this.description.replace(cleanUp, "");
}else{
description="";
}
}
/**
* @return the description
*/
public String getDescription() {
return "";
}
/**
* @param pubDate the pubDate to set
*/
public void setPubDate(String pubDate) {
this.pubDate = "";
}
/**
* @return the pubDate
*/
public String getPubDate() {
return pubDate;
}
/**
* @param encodedContent the encodedContent to set
*/
public void setEncodedContent(String encodedContent) {
this.encodedContent = encodedContent;
//System.out.println("Añadiendo el encoded "+encodedContent);
}
/**
* @return the encodedContent
*/
public String getEncodedContent() {
return encodedContent;
}
/**
* @param imgLink the imgLink to set
*/
public void setImgLink(String imgLink) {
this.imgLink = imgLink;
}
/**
* @return the imgLink
*/
public String getImgLink() {
return imgLink;
}

}


------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


Lamento si esta demasiado extenso, espero alguien pueda ayudarme a mejorar el rendimiento, la aplicacion realiza lo que se pensaba, pero tarda algo, de 3 a 6 segundos, no se si este sea el promedio de carga del SAXParser, si es asi, no se que otros metodos haya factibles para una mayor carga(pense en llamar a un fichero en el host para traer contenido string,particionarlo y pasarlo a un listadapter como arreglo,no tengo idea si eso sea mejor que el SAXParser).

Espero alguien pueda ayudarme, o me de tips de que debo de cambiar.

Gracias a todos.

Reply all
Reply to author
Forward
0 new messages