1

I have listview in my fragment and i'm trying to get item from my listview in my onclick event. But i got error that suggest me declared my list as final. When i try declare my list to final. I get another error "incompatible...".

this is my code

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.announcement_fragment, container, false);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    ArrayList<Announcement> listAnnouncement = GetlistAnnouncement();
    ListView lv = (ListView)rootView.findViewById(R.id.list_announcement);
    lv.setAdapter(new AnnouncementAdapter(listAnnouncement, getActivity()));
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Announcement item =  lv.getItemAtPosition(i);
        }
    });
    return rootView;
}

i got error in this row

Announcement item =  lv.getItemAtPosition(i);

Answer : change

Announcement item =  lv.getItemAtPosition(i);

to

Announcement item =  listAnnouncement.get(i);

or

Announcement item =  (Announcement)adapterView.getItemAtPosition(i);
huzain07
  • 1,051
  • 2
  • 8
  • 17

1 Answers1

1

But i got error that suggest me declared my list as final

Your lv needs to be final cause it's used in a annonymous inner class.

Cannot refer to a non-final variable inside an inner class defined in a different method

I get another error "incompatible...".

No need to use lv or make final. Change this

Announcement item =  lv.getItemAtPosition(i);

to

Announcement item =  (Announcement)adapterView.getItemAtPosition(i);

getItemAtPosition returns an object requires casting

Docs:

public Object getItemAtPosition (int position)

Added in API level 1
Gets the data associated with the specified position in the list.

Parameters
position    Which data to get
Returns
The data associated with the specified position in the list
Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • oh thanks, actually i was solved my problem by myself just now. But thanks for your answer. I'll vote :D – huzain07 Aug 11 '15 at 03:56