0

i have an ActionBar that has 2 tabs and each tabs layout is a fragment. in 1 of these tabs , there is a listView. and i want to set ArrayAdapetr for it. but when i run app, error occurred and error is about my application context. my code is :

public class TarfandFrag extends Fragment {



String values[] = new String[]{"sadeq","ali"};
ListView listView;
Context context;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tarfad_layout,container,false);
    listView = (ListView) view.findViewById(R.id.list_tarfand);


    return view;
}

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

ArrayAdapter adapter = new ArrayAdapter(context,android.R.layout.simple_list_item_1,values);
    listView.setAdapter(adapter);
}

}

but its not working. notice that i don't want use listFragment or anything else. i replace context with getActivity() , context.getApplicationContext, getActivity.getApplicationContext. but not working. plz help meeeee

Sadeq Shajary
  • 427
  • 6
  • 17

2 Answers2

0

In a fragment, onCreate() is called before onCreateView(). the consequence of this is that, at the point onCreate() is called, your ListView is not yet associated with an element in the layout (as your are doing this in onCreateView() which gets called later) and will hence resolve to null and you will get a null pointer exception when you set the adapter for the ListView. Move the code setting the adapter to within the onCreateView() method and use getActivity() and you should be fine.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tarfad_layout,container,false);
    listView = (ListView) view.findViewById(R.id.list_tarfand);

    // Here listview will not be null as it is now bound to an object
    ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,values);
    listView.setAdapter(adapter);
    return view;
}
ucsunil
  • 7,378
  • 1
  • 27
  • 32
0

Assing getActivity() to context in onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context=getActivity();

}
Figen Güngör
  • 12,169
  • 14
  • 66
  • 108