Skip to main content
se eliminaron 4 caracteres en el cuerpo
Origen Enlace
Rodrigo
  • 685
  • 1
  • 7
  • 22
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
Context c;
ArrayList<Article> articles;


public MyAdapter(Context c, ArrayList<Article> articles) {
    this.c = c;
    this.articles = articles;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v= LayoutInflater.from(c).inflate(R.layout.model,parent,false);
    return new MyViewHolder(v);
}

@Override
   public void onBindViewHolder(final MyViewHolder holder, final int 
position) 
  {
     final Article article=articles.get(position);
    System.out.println("MyAdater, position es: "+position);
     String title=article.getTitle();
    //String desc=article.getDescription();
    String dateFecha=article.getTsFecha();
    String dateHora=article.getTsHora();
    String imageUrl=article.getImageUrl();
    final String tsarticle=article.getTsArticle();

    holder.titleTxt.setText(title);
    holder.dateFechaTxt.setText(dateFecha);
    holder.dateHoraTxt.setText(dateHora);


    String baseUrl = "http://www.cooperativaejemplo.cl";
    String cadenaUrl = baseUrl+imageUrl;

   // Log.i("valor total cadena",": "+cadenaUrl);
    Picasso.with(c).load(cadenaUrl).into(holder.img);

    holder.img.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {

          Intent intent = new Intent(c, PictureDetailActivity.class);

            if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP){

                Explode explode = new Explode();
                explode.setDuration(1000);
                //si estuvieramos en una actividad no sería necesario 
  agregar activity.getWindow, solo getWindow
                //activity.getWindow()

                //como personalizamos la duración de la transición(el objeto 
   Explode), debemos colocar el nombre de la clase instanciada,
                // .setExitTransition(explode);
                // de lo contrario solo sería .setExitTransition(new 
   Explode()); y toma los valores por defecto de Explode.

           //  c.getWindow().setExitTransition(explode);
               // activity.startActivity(intent, ActivityOptionsCompat.
                 //       

makeSceneTransitionAnimation(activity,v,activity.getString
(R.string.transitonname_picture))
                 //       .toBundle());



              //  Log.i("el ts es "," :"+tsarticle.toString());
                intent.putExtra("article_object", article);
               c.startActivity(intent);
            }else {
                c.startActivity(intent);
            }
        }
    });
  }
      @Override
    public int getItemCount() {
       return articles.size();
    }

  }
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
Context c;
ArrayList<Article> articles;


public MyAdapter(Context c, ArrayList<Article> articles) {
    this.c = c;
    this.articles = articles;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v= LayoutInflater.from(c).inflate(R.layout.model,parent,false);
    return new MyViewHolder(v);
}

@Override
   public void onBindViewHolder(final MyViewHolder holder, final int 
position) 
  {
     final Article article=articles.get(position);
    System.out.println("MyAdater, position es: "+position);
     String title=article.getTitle();
    //String desc=article.getDescription();
    String dateFecha=article.getTsFecha();
    String dateHora=article.getTsHora();
    String imageUrl=article.getImageUrl();
    final String tsarticle=article.getTsArticle();

    holder.titleTxt.setText(title);
    holder.dateFechaTxt.setText(dateFecha);
    holder.dateHoraTxt.setText(dateHora);


    String baseUrl = "http://www.cooperativa.cl";
    String cadenaUrl = baseUrl+imageUrl;

   // Log.i("valor total cadena",": "+cadenaUrl);
    Picasso.with(c).load(cadenaUrl).into(holder.img);

    holder.img.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {

          Intent intent = new Intent(c, PictureDetailActivity.class);

            if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP){

                Explode explode = new Explode();
                explode.setDuration(1000);
                //si estuvieramos en una actividad no sería necesario 
  agregar activity.getWindow, solo getWindow
                //activity.getWindow()

                //como personalizamos la duración de la transición(el objeto 
   Explode), debemos colocar el nombre de la clase instanciada,
                // .setExitTransition(explode);
                // de lo contrario solo sería .setExitTransition(new 
   Explode()); y toma los valores por defecto de Explode.

           //  c.getWindow().setExitTransition(explode);
               // activity.startActivity(intent, ActivityOptionsCompat.
                 //       

makeSceneTransitionAnimation(activity,v,activity.getString
(R.string.transitonname_picture))
                 //       .toBundle());



              //  Log.i("el ts es "," :"+tsarticle.toString());
                intent.putExtra("article_object", article);
               c.startActivity(intent);
            }else {
                c.startActivity(intent);
            }
        }
    });
  }
      @Override
    public int getItemCount() {
       return articles.size();
    }

  }
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
Context c;
ArrayList<Article> articles;


public MyAdapter(Context c, ArrayList<Article> articles) {
    this.c = c;
    this.articles = articles;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v= LayoutInflater.from(c).inflate(R.layout.model,parent,false);
    return new MyViewHolder(v);
}

@Override
   public void onBindViewHolder(final MyViewHolder holder, final int 
position) 
  {
     final Article article=articles.get(position);
    System.out.println("MyAdater, position es: "+position);
     String title=article.getTitle();
    //String desc=article.getDescription();
    String dateFecha=article.getTsFecha();
    String dateHora=article.getTsHora();
    String imageUrl=article.getImageUrl();
    final String tsarticle=article.getTsArticle();

    holder.titleTxt.setText(title);
    holder.dateFechaTxt.setText(dateFecha);
    holder.dateHoraTxt.setText(dateHora);


    String baseUrl = "http://www.ejemplo.cl";
    String cadenaUrl = baseUrl+imageUrl;

   // Log.i("valor total cadena",": "+cadenaUrl);
    Picasso.with(c).load(cadenaUrl).into(holder.img);

    holder.img.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {

          Intent intent = new Intent(c, PictureDetailActivity.class);

            if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP){

                Explode explode = new Explode();
                explode.setDuration(1000);
                //si estuvieramos en una actividad no sería necesario 
  agregar activity.getWindow, solo getWindow
                //activity.getWindow()

                //como personalizamos la duración de la transición(el objeto 
   Explode), debemos colocar el nombre de la clase instanciada,
                // .setExitTransition(explode);
                // de lo contrario solo sería .setExitTransition(new 
   Explode()); y toma los valores por defecto de Explode.

           //  c.getWindow().setExitTransition(explode);
               // activity.startActivity(intent, ActivityOptionsCompat.
                 //       

makeSceneTransitionAnimation(activity,v,activity.getString
(R.string.transitonname_picture))
                 //       .toBundle());



              //  Log.i("el ts es "," :"+tsarticle.toString());
                intent.putExtra("article_object", article);
               c.startActivity(intent);
            }else {
                c.startActivity(intent);
            }
        }
    });
  }
      @Override
    public int getItemCount() {
       return articles.size();
    }

  }
Edición de clase RSSParserDetail
Origen Enlace
Rodrigo
  • 685
  • 1
  • 7
  • 22

Esta es la clase RSSParser, en donde hago el parseo del archivo XML (en este momento no voy a dejar la clase en donde hago la conexión HttpURLConnection) ` public class RSSParser extends AsyncTask<Void,Void,Boolean> {

Contextpublic c;
InputStreamclass is;
RecyclerViewRSSParserDetail rv;implements Serializable{

ProgressDialog pd;
ArrayList<Article> articles=new ArrayList<>();

public RSSParser(Context c,c;

private InputStream is, RecyclerView rv) {urlStream;
private XmlPullParserFactory factory;
private XmlPullParser this.cparser;

private =List<ArticleDetail> c;rssFeedList;
private ArticleDetail rssFeed;

private String this.isurlString;
private =String is;tagName;
 
private  String this.rvtitle;
private =String rv;link;
}private String description;
@Override
protected voidpublic onPreExecute()static {
final String ITEM = super.onPreExecute();"artic_data";
public static final String pd=newCHANNEL ProgressDialog(c);= "public";
public static final String pd.setTitle("Parse");TITLE = "_txt_titular";
public static final String pd.setMessage("Parsing...PleaseLINK wait");= "fotofija_port_649x365";
public static final String DESCRIPTION = pd.show();
}"vtxt_cuerpo";

@Override
protected Boolean doInBackgroundpublic RSSParserDetail(Void... paramsString urlString ) {
    return  this.parseRSS();urlString=urlString;
}
 
@Override
protected void onPostExecute(Boolean isParsed) {
 public static InputStream super.onPostExecutedownloadUrl(isParsed);

   String pd.dismiss(urlString);
  throws IOException if(isParsed)
    {
        //BIND
    URL url = rv.setAdapter(new MyAdapterURL(c,articles)urlString);

    }else {
     HttpURLConnection conn = Toast.makeText(c,"Unable To Parse",Toast.LENGTH_SHORTHttpURLConnection) url.showopenConnection();
   
  }
}

private Boolean parseRSSconn.setRequestMethod("GET")
{
    try
    {;
        XmlPullParserFactory factory=XmlPullParserFactoryconn.newInstancesetDoInput(true);
        XmlPullParser parser=factoryconn.newPullParserconnect();

     InputStream stream = parserconn.setInputgetInputStream(is,null);
    return stream;
 }

  public intList<ArticleDetail> event=parser.getEventTypeparse();
 {
    try {
   String tagValue=null;
    int count = 0;
 Boolean isSiteMeta=true;

      factory = articlesXmlPullParserFactory.clearnewInstance();
        Articleparser article=new= Articlefactory.newPullParser();
 
        do {

   urlStream = downloadUrl(urlString);
       String tagName=parserparser.getNamesetInput(urlStream, null);
 
          int eventType switch= parser.getEventType(event);
         boolean done = {false;
              rssFeed = casenew XmlPullParser.START_TAG:ArticleDetail();
                 rssFeedList = new if(tagName.equalsIgnoreCaseArrayList<ArticleDetail>("item"));
              while (eventType != XmlPullParser.END_DOCUMENT && !done) {
                       tagName article=new= Articleparser.getName();
           
            switch (eventType) isSiteMeta=false;{
                   case }XmlPullParser.START_DOCUMENT:
                    break;
 
                case XmlPullParser.TEXTSTART_TAG:
                    tagValue=parserif (tagName.getTextequals(ITEM);
                   ) break;
{
                case XmlPullParser.END_TAG:

                 rssFeed = new ifArticleDetail(!isSiteMeta);
                    {
}
                        if (tagName.equalsIgnoreCaseequals("title"TITLE))
                        {
                          title = articleparser.setTitlenextText(tagValue).toString();
 
                        }else if(tagNameSystem.equalsIgnoreCaseout.println("description"))
                     "Muestrame el titulo, {
        RSSParserDetail: "+title);
                   String desc=tagValue;}
                           if article.setDescription(desc.substring(desctagName.indexOfequals("/>")+2LINK));
 {
                        }elselink if(tagName= parser.equalsIgnoreCasenextText("prontus_ts").toString()
                        {;
                            article.setTsArticle(tagValue);
}
                        }else if (tagName.equalsIgnoreCaseequals("prontus_horap"DESCRIPTION))
                        {
                          description = articleparser.setTsHoranextText(tagValue).toString();
                        }else if (tagName.equalsIgnoreCase("prontus_fechap"))
     
                    {break;
                           case articleXmlPullParser.setTsFecha(tagValue);END_TAG:
                        }else if (tagName.equalsIgnoreCaseequals("prontus_foto640"CHANNEL))
                        {
                            article.setImageUrl(tagValue);
                      done = }
true;
                    }

                   else if (tagName.equalsIgnoreCaseequals("item"ITEM))
                    {
                        articles.addrssFeed=new ArticleDetail(articletitle,link,description);
                        isSiteMeta=true;rssFeedList.add(rssFeed);
                    }
 
                    break;
            }
 
            event=parsereventType = parser.next();
 
        }while (event != XmlPullParser.END_DOCUMENT);

   }
     return true;

    } catch (XmlPullParserExceptionException e) {
        e.printStackTrace();
    } catch (IOException e) {}
     
    e.printStackTrace();
   return }rssFeedList;
    return false;
}

}`

Esta es la clase RSSParser, en donde hago el parseo del archivo XML (en este momento no voy a dejar la clase en donde hago la conexión HttpURLConnection) ` public class RSSParser extends AsyncTask<Void,Void,Boolean> {

Context c;
InputStream is;
RecyclerView rv;

ProgressDialog pd;
ArrayList<Article> articles=new ArrayList<>();

public RSSParser(Context c, InputStream is, RecyclerView rv) {
    this.c = c;
    this.is = is;
    this.rv = rv;
}
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pd=new ProgressDialog(c);
    pd.setTitle("Parse");
    pd.setMessage("Parsing...Please wait");
    pd.show();
}

@Override
protected Boolean doInBackground(Void... params) {
    return this.parseRSS();
}
 
@Override
protected void onPostExecute(Boolean isParsed) {
    super.onPostExecute(isParsed);

    pd.dismiss();
    if(isParsed)
    {
        //BIND
       rv.setAdapter(new MyAdapter(c,articles));

    }else {
        Toast.makeText(c,"Unable To Parse",Toast.LENGTH_SHORT).show();
    }
}

private Boolean parseRSS()
{
    try
    {
        XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
        XmlPullParser parser=factory.newPullParser();

        parser.setInput(is,null);
        int event=parser.getEventType();

        String tagValue=null;
        Boolean isSiteMeta=true;

        articles.clear();
        Article article=new Article();
 
        do {

            String tagName=parser.getName();
 
            switch (event)
            {
                case XmlPullParser.START_TAG:
                    if(tagName.equalsIgnoreCase("item"))
                    {
                        article=new Article();
                        isSiteMeta=false;
                    }
                    break;
 
                case XmlPullParser.TEXT:
                    tagValue=parser.getText();
                    break;

                case XmlPullParser.END_TAG:

                    if(!isSiteMeta)
                    {

                        if(tagName.equalsIgnoreCase("title"))
                        {
                            article.setTitle(tagValue);
 
                        }else if(tagName.equalsIgnoreCase("description"))
                        {
                            String desc=tagValue;
                            article.setDescription(desc.substring(desc.indexOf("/>")+2));

                        }else if(tagName.equalsIgnoreCase("prontus_ts"))
                        {
                            article.setTsArticle(tagValue);

                        }else if (tagName.equalsIgnoreCase("prontus_horap"))
                        {
                            article.setTsHora(tagValue);
                        }else if (tagName.equalsIgnoreCase("prontus_fechap"))
                        {
                            article.setTsFecha(tagValue);
                        }else if (tagName.equalsIgnoreCase("prontus_foto640"))
                        {
                            article.setImageUrl(tagValue);
                        }

                    }

                    if(tagName.equalsIgnoreCase("item"))
                    {
                        articles.add(article);
                        isSiteMeta=true;
                    }
 
                    break;
            }
 
            event=parser.next();
 
        }while (event != XmlPullParser.END_DOCUMENT);

        return true;

    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

}`

Esta es la clase RSSParser, en donde hago el parseo del archivo XML (en este momento no voy a dejar la clase en donde hago la conexión HttpURLConnection)

public class RSSParserDetail implements Serializable{

    Context c;

private InputStream urlStream;
private XmlPullParserFactory factory;
private XmlPullParser parser;

private List<ArticleDetail> rssFeedList;
private ArticleDetail rssFeed;

private String urlString;
private String tagName;

private  String title;
private String link;
private String description;

public static final String ITEM = "artic_data";
public static final String CHANNEL = "public";
public static final String TITLE = "_txt_titular";
public static final String LINK = "fotofija_port_649x365";
public static final String DESCRIPTION = "vtxt_cuerpo";


  public RSSParserDetail( String urlString ) {
      this.urlString=urlString;
}

 public static InputStream downloadUrl(String urlString) throws IOException 
 {

    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.connect();

    InputStream stream = conn.getInputStream();
    return stream;
 }

  public List<ArticleDetail> parse() {
    try {
        int count = 0;
        factory = XmlPullParserFactory.newInstance();
        parser = factory.newPullParser();
        urlStream = downloadUrl(urlString);
        parser.setInput(urlStream, null);
        int eventType = parser.getEventType();
        boolean done = false;
        rssFeed = new ArticleDetail();
        rssFeedList = new ArrayList<ArticleDetail>();
        while (eventType != XmlPullParser.END_DOCUMENT && !done) {
            tagName = parser.getName();
 
            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    break;
                case XmlPullParser.START_TAG:
                    if (tagName.equals(ITEM)) {
                        rssFeed = new ArticleDetail();
                    }
                    if (tagName.equals(TITLE)) {
                        title = parser.nextText().toString();
                        System.out.println("Muestrame el titulo, 
      RSSParserDetail: "+title);
                    }
                    if (tagName.equals(LINK)) {
                        link = parser.nextText().toString();
                    }
                    if (tagName.equals(DESCRIPTION)) {
                        description = parser.nextText().toString();
                    }
 
                    break;
                case XmlPullParser.END_TAG:
                    if (tagName.equals(CHANNEL)) {
                        done = true;
                    } else if (tagName.equals(ITEM)) {
                        rssFeed=new ArticleDetail(title,link,description);
                        rssFeedList.add(rssFeed);
                    }
                    break;
            }
            eventType = parser.next();
            }
        } catch (Exception e) {
        e.printStackTrace();
       }
 
       return rssFeedList;
   }

}
agrego código de otra clase relacionada
Origen Enlace
Rodrigo
  • 685
  • 1
  • 7
  • 22
public class PictureDetailActivity extends AppCompatActivity implements 
Serializable{

RSSParserDetail rssParserDetail;
private List<ArticleDetail> mRssFeedList;
Context c;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 //setContentView(R.layout.activity_picture_detail);
    setElement();
   // showToolbar("",true);

    getWindow().setEnterTransition(new Fade());
    c = getApplicationContext();

 }
     public void setElement (){
      Article article = (Article) 
     getIntent().getSerializableExtra("article_object");

     //Armando Url para capturar archivo de articulo en servidor
    String tsArticle = article.getTsArticle();
    String baseUrl="https://www.cooperativa.cl/noticias/site/artic/";
    String titleDetail = article.getTitle();
    String dataTs = tsArticle.substring(0,8);
    String aammdd = dataTs;
    String directorioXml="/xml/";
    String finalUrl= tsArticle+".xml";
    String linkXml=baseUrl+aammdd+directorioXml+finalUrl;
    //***********************************************************
    String 
   linkPaso="http://especiales2.cooperativa.cl/
    2017/pruebas/rvargas/prontus_art_view_xml.xml";
    System.out.println("estoy en PictureDetailActivity");

   new DoRssFeedTask().execute(linkPaso);
   }

   public class DoRssFeedTask extends AsyncTask<String, Void, 
    List<ArticleDetail>> {
    ProgressDialog prog;
    String jsonStr = null;
    Handler innerHandler;

    @Override
    protected void onPreExecute() {
        prog = new ProgressDialog(PictureDetailActivity.this);
        prog.setMessage("Loading....");
        prog.show();
    }

    @Override
    protected List<ArticleDetail> doInBackground(String... params) {
        for (String urlVal : params) {
            rssParserDetail = new RSSParserDetail(urlVal);
        }
       // mRssFeedList = mNewsFeeder.parse();
        mRssFeedList=rssParserDetail.parse();
        return mRssFeedList;
    }

    @Override
    protected void onPostExecute(List<ArticleDetail> result) {
        prog.dismiss();
     // new MyAdapterDetail();
        Intent intent = new Intent(PictureDetailActivity.this, 
  MyAdapterDetail.class);
      c.   startActivity(intent);

        System.out.println("PictureDetailActivity onPostExecute");
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

  public void showToolbar(String tittle, boolean upButton/*, View view*/){
    /*se crea el metodo showtoolbar para traer toolbar según maqueta de 
    diseño*/
    /*este metodo no debe llevar view porque estamos en cotexto de 
    activity*/

    /*Estamos en contexto de Activity, es por eso que no debe de llevar el 
     código ((AppCompatActivity)getActivity())
    al llevar este código a un fragment si debe llevar ese codigo
     */

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(tittle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(upButton);
    CollapsingToolbarLayout collapsingtoolbarlayout =  
   (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar);/*aún no 
   funcional, sea crea para el proximo curso*/

   }

 }

No he logrado que me funcioneEsta es la clase MyAdapterDetail, y el error que me figura es esteen donde envío los elementos para comenzar a setear.

E/AndroidRuntime: FATAL EXCEPTION: main
                      public class MyAdapterDetail extends AppCompatActivity implements  
    Serializable {
     //ArrayList<RSSParserDetail> articles;

     //ArticleDetail articles = new ArticleDetail();
    //ArrayList<ArticleDetail> articles;
    Context c;
   //ArticleDetail articles;
   MyViewHolderDetail myViewHolderDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     // Process:ArticleDetail cl.cooperativaarticle=articles.readxmlfrominternetmaterial, PID: 578get(0);
                                                         
  //articles= (ArrayList<ArticleDetail>)  
    getIntent().getSerializableExtra("objeto");
   // System.out.println("MyAdapterDetail tamaño de arreglo que llega es de:  
    "+articles.size());

    java.langsuper.NullPointerException: Attempt to invokeonCreate(savedInstanceState);
 virtual method 'void android.content.Context.startActivitysetContentView(androidR.contentlayout.Intentactivity_picture_detail)' on a null object reference;
                                                    showToolbar("",true);
    System.out.println("Estoy en el AdapterDetail");
    setElementDetail();
   }

    public void setElementDetail(){
    //System.out.println("MyAdapterDetail en setElemetDetail, el tamaño de  
     arreglo ates: cl.cooperativa.readxmlfrominternetmaterial.view.PictureDetailActivity$DoRssFeedTask"+articles.onPostExecutesize(PictureDetailActivity.java:84));
                                                                           
     ArticleDetail article = new ArticleDetail();
     at//String cl.cooperativa.readxmlfrominternetmaterial.view.PictureDetailActivity$DoRssFeedTaskimageUrl=article.onPostExecutegetImageUrlDetail(PictureDetailActivity.java:57);
                                                                                        atString android.os.AsyncTasktitle=article.finishgetTitleDetail(AsyncTask.java:651);
                                                                                        at//String android.os.AsyncTaskdesc=article.-wrap1getContDetail(AsyncTask.java);
                                                                             String baseUrl = "http://www.cooperativa.cl";
   //String cadenaUrl = baseUrl+imageUrl;

  at android//Picasso.oswith(c).AsyncTask$InternalHandlerload(cadenaUrl).handleMessageinto(AsyncTaskmyViewHolderDetail.java:668img);
                                                                                        at android.os//myViewHolderDetail.HandlertitleTxtDetail.dispatchMessagesetText(Handler.java:102title);
                                                                                        at android.os//myViewHolderDetail.LoopertitleDetail.loopsetText(Looper.java:148desc);
                                                                              
    //System.out.println("Mi cadena URL es: "+cadenaUrl);
   at android.appSystem.ActivityThreadout.mainprintln(ActivityThread.java:5417)
      "Mi titulo es: "+title);
  //System.out.println("Mi Detalle es: "+desc);
 }

 public void showToolbar(String tittle, boolean upButton/*, View view*/){
    /*se crea el metodo showtoolbar para traer toolbar según maqueta de  
     diseño*/
    /*este metodo no debe llevar view porque estamos en cotexto de  
     activity*/

    /*Estamos en contexto de Activity, es por eso que no debe de llevar el  
       atcódigo java.lang.reflect.Method.invoke(Native Method(AppCompatActivity)getActivity())
                   al llevar este código a un fragment si debe llevar ese codigo
     */

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(tittle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(upButton);
    CollapsingToolbarLayout collapsingtoolbarlayout =   
    (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar);/*aún no  
    funcional, sea crea para el proximo curso*/
     }
   at}



06-13 com.android.internal.os17:23:45.ZygoteInit$MethodAndArgsCaller032 28631-28631/cl.run(ZygoteInitcooperativa.java:726)
                readxmlfrominternetmaterial  
                               I/System.out: Estoy en el AdapterDetail
06-13 17:23:45.032 28631-28631/cl.cooperativa.readxmlfrominternetmaterial  
                               I/System.out: Mi attitulo com.android.internal.os.ZygoteInit.main(ZygoteInit.javaes:616) null
public class PictureDetailActivity extends AppCompatActivity implements 
Serializable{

RSSParserDetail rssParserDetail;
private List<ArticleDetail> mRssFeedList;
Context c;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 //setContentView(R.layout.activity_picture_detail);
    setElement();
   // showToolbar("",true);

    getWindow().setEnterTransition(new Fade());

 }
 public void setElement (){
   Article article = (Article) 
 getIntent().getSerializableExtra("article_object");

    //Armando Url para capturar archivo de articulo en servidor
    String tsArticle = article.getTsArticle();
    String baseUrl="https://www.cooperativa.cl/noticias/site/artic/";
    String titleDetail = article.getTitle();
    String dataTs = tsArticle.substring(0,8);
    String aammdd = dataTs;
    String directorioXml="/xml/";
    String finalUrl= tsArticle+".xml";
    String linkXml=baseUrl+aammdd+directorioXml+finalUrl;
    //***********************************************************
    String 
   linkPaso="http://especiales2.cooperativa.cl/
    2017/pruebas/rvargas/prontus_art_view_xml.xml";
    System.out.println("estoy en PictureDetailActivity");

   new DoRssFeedTask().execute(linkPaso);
 }

public class DoRssFeedTask extends AsyncTask<String, Void, 
List<ArticleDetail>> {
    ProgressDialog prog;
    String jsonStr = null;
    Handler innerHandler;

    @Override
    protected void onPreExecute() {
        prog = new ProgressDialog(PictureDetailActivity.this);
        prog.setMessage("Loading....");
        prog.show();
    }

    @Override
    protected List<ArticleDetail> doInBackground(String... params) {
        for (String urlVal : params) {
            rssParserDetail = new RSSParserDetail(urlVal);
        }
       // mRssFeedList = mNewsFeeder.parse();
        mRssFeedList=rssParserDetail.parse();
        return mRssFeedList;
    }

    @Override
    protected void onPostExecute(List<ArticleDetail> result) {
        prog.dismiss();
     // new MyAdapterDetail();
        Intent intent = new Intent(PictureDetailActivity.this, 
 MyAdapterDetail.class);
      c.startActivity(intent);

        System.out.println("PictureDetailActivity onPostExecute");
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

  public void showToolbar(String tittle, boolean upButton/*, View view*/){
    /*se crea el metodo showtoolbar para traer toolbar según maqueta de 
    diseño*/
    /*este metodo no debe llevar view porque estamos en cotexto de 
    activity*/

    /*Estamos en contexto de Activity, es por eso que no debe de llevar el 
     código ((AppCompatActivity)getActivity())
    al llevar este código a un fragment si debe llevar ese codigo
     */

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(tittle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(upButton);
    CollapsingToolbarLayout collapsingtoolbarlayout =  
   (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar);/*aún no 
 funcional, sea crea para el proximo curso*/

  }

 }

No he logrado que me funcione, y el error que me figura es este.

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                    Process: cl.cooperativa.readxmlfrominternetmaterial, PID: 578
                                                                                    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference
                                                                                        at cl.cooperativa.readxmlfrominternetmaterial.view.PictureDetailActivity$DoRssFeedTask.onPostExecute(PictureDetailActivity.java:84)
                                                                                        at cl.cooperativa.readxmlfrominternetmaterial.view.PictureDetailActivity$DoRssFeedTask.onPostExecute(PictureDetailActivity.java:57)
                                                                                        at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                        at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                                        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                        at android.os.Looper.loop(Looper.java:148)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
public class PictureDetailActivity extends AppCompatActivity implements 
Serializable{

RSSParserDetail rssParserDetail;
private List<ArticleDetail> mRssFeedList;
Context c;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 //setContentView(R.layout.activity_picture_detail);
    setElement();
   // showToolbar("",true);

    getWindow().setEnterTransition(new Fade());
    c = getApplicationContext();

 }
     public void setElement (){
      Article article = (Article) 
     getIntent().getSerializableExtra("article_object");

     //Armando Url para capturar archivo de articulo en servidor
    String tsArticle = article.getTsArticle();
    String baseUrl="https://www.cooperativa.cl/noticias/site/artic/";
    String titleDetail = article.getTitle();
    String dataTs = tsArticle.substring(0,8);
    String aammdd = dataTs;
    String directorioXml="/xml/";
    String finalUrl= tsArticle+".xml";
    String linkXml=baseUrl+aammdd+directorioXml+finalUrl;
    //***********************************************************
    String linkPaso="http://especiales2.cooperativa.cl/
    2017/pruebas/rvargas/prontus_art_view_xml.xml";
    System.out.println("estoy en PictureDetailActivity");

   new DoRssFeedTask().execute(linkPaso);
   }

   public class DoRssFeedTask extends AsyncTask<String, Void, 
    List<ArticleDetail>> {
    ProgressDialog prog;
    String jsonStr = null;
    Handler innerHandler;

    @Override
    protected void onPreExecute() {
        prog = new ProgressDialog(PictureDetailActivity.this);
        prog.setMessage("Loading....");
        prog.show();
    }

    @Override
    protected List<ArticleDetail> doInBackground(String... params) {
        for (String urlVal : params) {
            rssParserDetail = new RSSParserDetail(urlVal);
        }
       // mRssFeedList = mNewsFeeder.parse();
        mRssFeedList=rssParserDetail.parse();
        return mRssFeedList;
    }

    @Override
    protected void onPostExecute(List<ArticleDetail> result) {
        prog.dismiss();
     // new MyAdapterDetail();
        Intent intent = new Intent(PictureDetailActivity.this, 
  MyAdapterDetail.class);
         startActivity(intent);

        System.out.println("PictureDetailActivity onPostExecute");
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

public void showToolbar(String tittle, boolean upButton/*, View view*/){
    /*se crea el metodo showtoolbar para traer toolbar según maqueta de 
diseño*/
    /*este metodo no debe llevar view porque estamos en cotexto de 
 activity*/

    /*Estamos en contexto de Activity, es por eso que no debe de llevar el 
 código ((AppCompatActivity)getActivity())
    al llevar este código a un fragment si debe llevar ese codigo
     */

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(tittle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(upButton);
    CollapsingToolbarLayout collapsingtoolbarlayout =  
  (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar);/*aún no 
   funcional, sea crea para el proximo curso*/

   }

}

Esta es la clase MyAdapterDetail, que es en donde envío los elementos para comenzar a setear.

public class MyAdapterDetail extends AppCompatActivity implements  
    Serializable {
     //ArrayList<RSSParserDetail> articles;

     //ArticleDetail articles = new ArticleDetail();
    //ArrayList<ArticleDetail> articles;
    Context c;
   //ArticleDetail articles;
   MyViewHolderDetail myViewHolderDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     // ArticleDetail article=articles.get(0);
 
  //articles= (ArrayList<ArticleDetail>)  
    getIntent().getSerializableExtra("objeto");
   // System.out.println("MyAdapterDetail tamaño de arreglo que llega es de:  
    "+articles.size());

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_picture_detail);
    showToolbar("",true);
    System.out.println("Estoy en el AdapterDetail");
    setElementDetail();
   }

    public void setElementDetail(){
    //System.out.println("MyAdapterDetail en setElemetDetail, el tamaño de  
     arreglo es: "+articles.size());
 
     ArticleDetail article = new ArticleDetail();
     //String imageUrl=article.getImageUrlDetail();
     String title=article.getTitleDetail();
    //String desc=article.getContDetail();
    String baseUrl = "http://www.cooperativa.cl";
   //String cadenaUrl = baseUrl+imageUrl;

   //Picasso.with(c).load(cadenaUrl).into(myViewHolderDetail.img);
  //myViewHolderDetail.titleTxtDetail.setText(title);
 //myViewHolderDetail.titleDetail.setText(desc);
 
    //System.out.println("Mi cadena URL es: "+cadenaUrl);
    System.out.println("Mi titulo es: "+title);
  //System.out.println("Mi Detalle es: "+desc);
 }

 public void showToolbar(String tittle, boolean upButton/*, View view*/){
    /*se crea el metodo showtoolbar para traer toolbar según maqueta de  
     diseño*/
    /*este metodo no debe llevar view porque estamos en cotexto de  
     activity*/

    /*Estamos en contexto de Activity, es por eso que no debe de llevar el  
       código ((AppCompatActivity)getActivity())
    al llevar este código a un fragment si debe llevar ese codigo
     */

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(tittle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(upButton);
    CollapsingToolbarLayout collapsingtoolbarlayout =   
    (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar);/*aún no  
    funcional, sea crea para el proximo curso*/
     }
   }



06-13 17:23:45.032 28631-28631/cl.cooperativa.readxmlfrominternetmaterial  
                               I/System.out: Estoy en el AdapterDetail
06-13 17:23:45.032 28631-28631/cl.cooperativa.readxmlfrominternetmaterial  
                               I/System.out: Mi titulo es: null
Origen Enlace
Rodrigo
  • 685
  • 1
  • 7
  • 22
Loading