i have null pointer exception when put this inside DialogFragment in onCreateView method
AutoCompleteTextView med =(AutoCompleteTextView)getActivity().findViewById(R.id.new_autoCompleteT);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_1, item);
med.setAdapter(adapter);
It seems that you are trying to retrieve a View from the associated Activity. You should check the call to getActivity(), maybe it's returning null because the activity it hasn't attached yet. Check the onActivityCreated (Bundle savedInstanceState) method, from the doc:
Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state.
Related
I am trying to populate my Listview using the data from another fragment.
I am able to get the data from the other fragment, but when I try to make my listview object, it is returning null.
As a result, the app is crashing.
I am getting data from the user from one fragment and then calling a method from another fragment to pass the data. I am making my listview object and array adapter in the poplist() method of the second method. However, the app is crashing due to null pointer exception.
Please help.
public class WishListFragment extends Fragment {
ArrayList<String> wishListTitles = new ArrayList<String>();
View rootView;
ListView wishListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getActivity();
rootView = inflater.inflate(R.layout.fragment_wish_list, container, false);
return rootView;
}
// Another fragment gets the data from user as strings and calls this method
public void popList(String str1, String str2, String str3, Context context)
{
// LibModel is a pojo, I am using its constructor to set the values.
LibModel lm = new LibModel(str1,str2,str3);
Log.w("Title:",lm.getTitle());
Log.w("Author:",lm.getAuthor());
Log.w("Language:",lm.getLang());
wishListTitles.add(lm.getTitle());
// I get this on the log, so the ArrayList is made correctly
Log.w("ArrayList:",wishListTitles.get(0));
// The listView gives Null Pointer exception and crashes the app
wishListView = (ListView) rootView.findViewById(R.id.wl_lv);
ArrayAdapter<String> wishListAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1,wishListTitles);
wishListView.setAdapter(wishListAdapter);
}
}
I have tried the following, but it does not work
Used getView method instead of rootView while making the Listview.
Tried to make the listview inside the onCreateView() method but then the listview object is null, I get null pointer.
I am unable to find a way to put the set the adapter for the listview as it is returning Null.
I would recommend having interface callback in the fragment with the data. Also keep a reference of the list view in the activity containing the fragment.
Upon callback, the interface function will be executed and you can update list view from there.
I don't want to override onCreateView because there is no need. With a ListFragment all I am doing is taking an array of data, putting it in an ArrayAdapter and calling setListAdapter(arrayGoesHere) and then I have my populated ListFragment.
I am calling findViewById inside onActivityCreated() as it is the recommended place to find and store references to your views. And as you know, this is called after onCreateView() in the Android framework.
I can't do viewReturnedFromOnCreateView.findViewById because I'm not using onCreateView.
getActivity().findViewById doesnt work, because I'm actually not sure why.
getListView().findViewById doesnt work (because the element im trying to access is not a child of getListView()).
Edit 1: getView() didn't work either, I forgot to mention I am using the support library, android.support.v4.app.ListFragment. not sure if that matters
This is my code:
public class SomeFragment extends ListFragment {
private int someButtonId;
private Button someButton;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] someList = getResources().getStringArray(R.array.someData);
ArrayAdapter<String> someAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, someList);
setListAdapter(someAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
context = getActivity().getApplicationContext();
someButtonId = context.getResources().getIdentifier("someButton", "id", context.getPackageName());
someButton = (Button) getActivity().findViewById(someButtonId);
Log.i("hello", someButton.toString()); //Null pointer exception
}
}
I have an Activity which holds a ViewPager with 2 Fragments. One fragment is for adding items to ListView and another fragment is holding the ListView.
I've been trying for almost 3 days now without any positive results. How do I update the other fragment's ListView from the first fragment?
I'm trying to call the method that updates ListView from the Activity that holds ViewPager but it doesn't work.
Calling the method from ViewPager activity :
#Override
public void onPageSelected(int position) {
library.populateListView(getApplicationContext());
aBar.setSelectedNavigationItem(position);
}
This is the populateListView method:
public void populateListView(Context context){
CustomListViewAdapter customAdapter = new CustomListViewAdapter(getDatabaseArrayList(context), getActivity());
if (lView != null)
{
lView.setAdapter(customAdapter);
}
customAdapter.notifyDataSetChanged();
}
However this doesn't work because the lView variable (ListView) is null because the fragment isn't shown at the moment when this is being called.
I am assuming that function populateListView() is a function of the Fragment containing the ListView. You are calling populateListView() on every call to onPageSelected. Should you not check what is the position that is being selected. Anyway the populateListView() method should be a public method of the Fragment containing ListView. And You Can Instantiate The Fragment from the Viewpager adapter in the Activity and than call this method. In That way the listView should not be null.
#Override
public void onPageSelected(int position) {
ListViewFragment frag=(ListViewFragment)adapter.instantiateItem(viewPager, 1);
//here adapter is the ViewPager Adapter and you must supply the viewpager that contains
//the fragments and also the position of the fragment to instantiate.
//For example 0 or 1 etc.
frag.populateListView(getApplicationContext());
aBar.setSelectedNavigationItem(position);
}
Understand Fragments
Please see this link. I have gone in great detail explaining the concept of fragments.
Pay particular attention to the definition of rootview:
public void onActivityCreared(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
// Do stuff on creation. This is usually where you add the bulk of your code. Like clickListners
// You can define this object as any element in any of your xml's
View rootview = inflater.inflate(R.layout.xml_the_fragment_uses container,false);
rootview.findViewById(R.id.your_id).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Do something
}
});
}
In the above case I defined a button for an on click listener, but you can just as easily define a ListView along with its appropriate methods.
Alternate Solution
A second method could be using getView or getActivity (check the communicating with activity section).
For example:
ListView listView = (ListView) getView().findViewById(R.id.your_listView_id);
OR (more likely solution for your problem)
View listView = getActivity().findViewById(R.id.list);
Please read this post for additional information.
Good Luck.
To do this safely, you have to keep your listview data in a higher level Parent-Activity not the fragments. Make your MainActivityclass singleton class by making the constructor private and create a getInstance method that return the only initialized instance of your `MainActivity.
This will allow you to keep your data instance safe from being re-initialized or lost. Then, in onResume of your fragment re-set the data (get it from the MainActivity) to your listview adapter and call notifyDataSetChanged() method from the adapter instance.
This will do the trick.
In my OncreateView() set the adapter which is working when i am first loading the page. When i go to another page and make changes then come back to this fragment it is not working adapter.notifyDatasetchanged().
#Override
public void onStart() {
super.onStart();
groupItem.clear();
childItem.clear();
List<String> child_Category;child_Category=new ArrayList<String>();
groupItem = obj_Listdatabase.fetchcategory();
childItem.clear();
ListIterator<String> iterator = groupItem
.listIterator();
while (iterator.hasNext()) {
String categoryname = iterator.next();
child_Category = new ArrayList<String>();
child_Category = obj_Listdatabase
.fetchchildlist(categoryname);
childItem.add(child_Category);
}
adapter.notifyDataSetChanged();
}
Hai I got output for this one:
groupItem.addAll(obj_Listdatabase.fetchcategory());
Instead of This
//groupItem = obj_Listdatabase.fetchcategory();
Because i change the reference in assignment statement(=) for that adapter.So i use addAll() method to store the values only instead of reference.
You should reaaaally indent your code more cleanly, never use several ";" on the same line for example.
And you can definitely use BaseExpandableListAdapter the issu is somewhere else..
You should also notice that onCreate view is more suitable for "creating view" so all the adapter stuff should be somewhere else like onViewCreated, or onActivityCreated as you need (it's just some advices)
I assume your adapter is in a Fragment since you use GetActivity() and in the constructor of your adapter you pass a reference to the activity (context), the group list and the child list.. ok
we ll assume that you are using the fragment onStart. From the official doc :
Called when the Fragment is visible to the user. This is generally tied to Activity.onStart of the containing Activity's lifecycle.
So normally this method is called after onViewCreate, onViewCreated .. etc at least the first time you code is running. So this is ok
Did you try using adapter.notifyDataSetInvalidate() and then do adapter.notidyDataSetChanged ?
One last thing, since you actually pass the data to your adapter by the constructor, when you update your lists how can the adapter be aware of the changes ? Are your lists global (static) ?
If not, before doing adapter.notifyDataSetChanged() you should pass the lists (group and child) to the adapter with some setter..
good luck
Here is the code where I add a list to my list fragmet:
public void onAttach(Activity activity) {
super.onAttach(activity);
System.err.println("Fragment Attach");
String[] MyList = {"Item 1","Item 2","Item 3","Item 4","Item 5"};
System.err.println("File Row ID" + Integer.toString(R.layout.file_row));
ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(), R.layout.file_row, MyList);
//Trying to add a Header View.
TextView tv = (TextView) activity.findViewById(R.layout.file_row);
tv.setText(R.string.FileBrowserHeader);
this.getListView().addHeaderView(tv);
//Setting the adapter
setListAdapter(aa);
}
However the line this.getListView().addHeaderView(tv); gives me the error
06-11 15:24:46.110: ERROR/AndroidRuntime(8532): Caused by: java.lang.IllegalStateException: Content view not yet created
And the program crashes.
Can anyone tell me what am I doing wrong?
The problem is that you are adding the header view too soon.
The error is being caused by you trying to find views that haven't been created yet.
The life cycle for a fragment is (source: http://developer.android.com/reference/android/app/Fragment.html)
onAttach(Activity) called once the fragment is associated with its activity.
onCreate(Bundle) called to do initial creation of the fragment.
onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate.
onStart() makes the fragment visible to the user (based on its containing activity being started).
onResume() makes the fragment interacting with the user (based on its containing activity being resumed).
As you can see, you are trying to use views in onAttach, but the views don't exist until onCreateView! Try moving your code to onActivityCreate, which has happened after the views all exist