Reputation: 71
I have this code but the app crashes on the line setadapter
.
I really don't understand because I set the adptater by the new arrayadapter.
I tried other ways but no one works !
By the way, this code is in a Fragment and not an activity !
So have you an idea of what happens ?
public class Fragment_product_list extends Fragment{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ListView listview = (ListView) getActivity().findViewById(R.id.list_product);
String[] values = new String[] { "item1" , "item2" , "item3" , "item4" , "item5" , "item6" , "item7" };
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.list_content , list);
listview.setAdapter(adapter); /*app crash here*/
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
@Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
@Override
public boolean hasStableIds() {
return true;
}
}
}
Thanks !
Upvotes: 0
Views: 544
Reputation: 2172
Just in case you didn't get NickF's answer, here is the solution: Override the onCreateView method in your fragment and do as follows.
public class Fragment_product_list extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout, container,
false);
ListView listView = (ListView) rootView.findViewById(R.id.list_product);
//Rest of the code
}
}
Upvotes: 0