Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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!

share|improve this question

closed as off-topic by Toby Speight, user1803551, Soner Gönül, bpeterson76, heenenee Feb 15 at 21:08

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example." – Toby Speight, Soner Gönül, bpeterson76, heenenee
If this question can be reworded to fit the rules in the help center, please edit the question.

1  
Possible duplicate of Can someone explain "ClassCastException" in Java? – pmbanka Feb 15 at 16:02
up vote 0 down vote accepted

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

share|improve this answer
    
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 at 16:35
    
is returning a News object. Use its getter to access that info. E.g. item.getNewsTitle() – Blackbelt Feb 15 at 16:36
    
Thanks, working! – MattyK14 Feb 15 at 17:01

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.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.