-2

I have looked through numerous questions that are very similar to mine and have tried all the fixes that the other questions recommended to no avail. So I decided I'd post my own question in hopes that someone can help.

NewsActivity:

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.Image;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class NewsActivity extends Activity {
private String xmlData;
private ListView listView;
private ArrayList<News> allNews;
private Image newsImage;

public final static String ITEM_TITLE = "newsTitle";
public final static String ITEM_DATE = "newsDate";
public final static String ITEM_DESCRIPTION = "newsDescription";
public final static String ITEM_IMGURL = "newsImageURL";

public Map<String, ?> createItem(String title, String date, String url) {
    Map<String,String> item = new HashMap<>();
    item.put(ITEM_TITLE, title);
    item.put(ITEM_DATE, date);
    item.put(ITEM_IMGURL, url);
    return item;
}

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ActionBar bar = getActionBar();
    bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f8f8f8")));
    bar.setDisplayShowHomeEnabled(false);
    bar.setDisplayShowTitleEnabled(true);
    bar.setDisplayUseLogoEnabled(false);
    bar.setTitle("News");

    setContentView(R.layout.news_layout);

    Bundle newsBundle = getIntent().getExtras();
    xmlData = newsBundle.getString("xmlData");

    final ArrayList<News> newsData = getNewsData(xmlData);

    allNews = new ArrayList<News>();
    List<Map<String, ?>> data = new LinkedList<Map<String, ?>>();

    for(int i = 0; i < newsData.size(); i++) {
        News currentNews = newsData.get(i);
        String newsTitle = currentNews.getNewsTitle();
        String newsDate = currentNews.getNewsDate();
        String newsDescription = currentNews.getNewsDescription();
        String newsImageURL = currentNews.getNewsImageUrl();


        data.add(createItem(newsTitle, newsDate, newsImageURL));
        allNews.add(currentNews);
    }
    listView = (ListView) findViewById(R.id.news_list);
    LazyNewsAdapter adapter = new LazyNewsAdapter(this, newsData);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Map<String, String> item = (HashMap<String, String>) parent.getItemAtPosition(position); //**ERROR IS HERE: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap** //
            String title = item.get(ITEM_TITLE);
            String url = item.get(ITEM_IMGURL);
            String date = item.get(ITEM_DATE);

            Iterator<News> itp = allNews.iterator();
            News currentNews = null;

            while (itp.hasNext()) {
                currentNews = itp.next();
                if (title == currentNews.getNewsTitle() && url == currentNews.getNewsImageUrl() && date == currentNews.getNewsDate())
                    break;
            }

            String newsTitle = currentNews.getNewsTitle();
            String newsDescription = currentNews.getNewsDescription();
            String newsUrl = currentNews.getNewsImageUrl();
            String newsDate = currentNews.getNewsDate();

            Intent detailnewsScreen = new Intent(getApplicationContext(), DetailNewsActivity.class);
            detailnewsScreen.putExtra("newsTitle", newsTitle);
            detailnewsScreen.putExtra("newsDescription", newsDescription);
            detailnewsScreen.putExtra("url", newsUrl);
            detailnewsScreen.putExtra("newsDate", newsDate);

            startActivity(detailnewsScreen);
        }
    });
}

private ArrayList<News> getNewsData(String src) {
    ArrayList<News> newsList = new ArrayList<>();

    News currentNews = new News();
    String newsTitle = new String();
    String newsDate = new String();
    String newsUrl = new String();
    String newsDescription = new String();

    try {
        StringReader sr = new StringReader(src);
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xpp = factory.newPullParser();
        xpp.setInput(sr);

        int eventType = xpp.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String name = null;
            switch (eventType) {
                case XmlPullParser.START_TAG:
                    name = xpp.getName();
                    if (name.equals("news")) {
                        currentNews = new News();
                    }
                    else if (name.equals("ntitle")) {
                        newsTitle = xpp.nextText();
                        newsTitle = newsTitle.trim();
                    }

                    else if (name.equals("ndate")) {
                        newsDate = xpp.nextText();
                        newsDate = newsDate.trim();
                    }

                    else if (name.equals("nimage")) {
                        newsUrl = xpp.nextText();
                        newsUrl = newsUrl.trim();
                    }

                    else if (name.equals("ndescription")) {
                        newsDescription = xpp.nextText();
                        newsDescription = newsDescription.trim();
                    }

                    break;

                case XmlPullParser.END_TAG:
                    name = xpp.getName();

                    if (name.equals("news")) {
                        currentNews.setNewsTitle(newsTitle);
                        currentNews.setNewsDate(newsDate);
                        currentNews.setNewsImageUrl("http://www.branko-cirovic.appspot.com/iWeek/news/images/" + newsUrl);
                        currentNews.setNewsDescription(newsDescription);

                        newsList.add(currentNews);
                    }

                    break;
            }

            eventType = xpp.next();
        }
    }

    catch (Exception e){
        e.printStackTrace();
    }
    return newsList;
}
}

LazyNewsAdapter:

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class LazyNewsAdapter extends BaseAdapter {

private Activity activity;
private ArrayList<News> listData;
private LayoutInflater inflater = null;

public LazyNewsAdapter(Activity activity, ArrayList<News> listData) {
    this.activity = activity;
    this.listData = listData;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public int getCount() {
    return listData.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    News newsItem = listData.get(position);

    View view = convertView;
    if(convertView == null)
        view = inflater.inflate(R.layout.news_cell, null);

    TextView newsTitle = (TextView) view.findViewById(R.id.newsTitle);
    TextView newsDate = (TextView) view.findViewById(R.id.newsDate);
    ImageView image = (ImageView) view.findViewById(R.id.newsImage);

    newsTitle.setText(newsItem.getNewsTitle());
    newsDate.setText(newsItem.getNewsDate());
    String url = newsItem.getNewsImageUrl();

    ImageLoader imageLoader = new ImageLoader(activity, 600, R.mipmap.placeholder);
    imageLoader.displayImage(url, image);

    return view;
}
}

The error that I am getting has a comment next to it in the NewsActivity. It seems to be trying to cast an integer to a HashMap for some reason. I have multiple other classes that use this exact method and have no issue, but for this NewsActivity I am getting this error.

Any suggestions?

Thanks so much!

MattyK14
  • 2,046
  • 2
  • 17
  • 29
  • 1
    Possible duplicate of [Can someone explain "ClassCastException" in Java?](http://stackoverflow.com/questions/907360/can-someone-explain-classcastexception-in-java) – pmbanka Feb 15 '16 at 16:02

2 Answers2

1

your version of getItem is returning an int

public Object getItem(int position) {
    return position;
}

that's why you can't cast to parent.getItemAtPosition(position); to Map<String, String>. Second your Adapter's subclass knows objects of type News. You getItem should return the News at position

public Object getItem(int position) {
    return listData.get(position);
}

and you should cast the returned value of parent.getItemAtPosition(position); to News. Change

 Map<String, String> item = (HashMap<String, String>) parent.getItemAtPosition(position); 

with

 News item = (News) parent.getItemAtPosition(position); 

then use item to access its content

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • I tried this, when I try to access the content from item, it doesn't recognize the item.get(ITEM_TITLE). Any suggestion? – MattyK14 Feb 15 '16 at 16:35
  • is returning a News object. Use its getter to access that info. E.g. `item.getNewsTitle()` – Blackbelt Feb 15 '16 at 16:36
0

My guess is that the position passed into NewsActivity.onItemClick() is wrong. The line parent.getItemAtPosition() returns an Object which you are casting, but if the position is wrong you will be getting the wrong Object, potentially with a different type which cannot be cast to a hashmap, hence the error.

ewanc
  • 1,284
  • 1
  • 12
  • 23