Nullpointer exception in fragment (initializing listview) - java

Here's my code for trying to display a list in a Fragment, which as of now keeps reporting a NullPointerException whenever it tries to initialize the ListView:
public class PortfolioFragment extends ListFragment {
ListView l;
ArrayAdapter<String> adapter;
List<String> list;
public PortfolioFragment() {
// Required empty public constructor
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
list = MainActivity.globalArrayTest;
l = (ListView) getView().findViewById(android.R.id.list);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
l.setAdapter(adapter);
return inflater.inflate(R.layout.fragment_portfolio, container, false);
}
I am getting an error at this line:
l = (ListView) getView().findViewById(android.R.id.list);

Change to
View v = inflater.inflate(R.layout.fragment_portfolio, container, false);
l = (ListView) v.findViewById(android.R.id.list);
return v;
You should have the below in xml
<ListView android:id="#android:id/list"
Or override onActivityCreated and use getListView()
Also you can use the below as black belt commented this is better than the above.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
l = getListView(); // since you extend ListFragment
}

since you are extending ListFragment you should use getListView() instead of findViewById and setListAdapter should be called after onCreateView (inside onActivityCreated, for instance)

This is another way to go about this, although I extend only Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle SavedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item, container, false);
ListView itemList = (ListView)rootView.findViewById(R.id.itemListView);
String[] items = {"Alpha", "Orange", "Pineapple", "Venus", "Echo", "Pent", "Mouse",
"Phoenix", "Dent", "Sloppy"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(rootView.getContext(),
R.layout.text_row, items);
itemList.setAdapter(new ArrayAdapter<>(rootView.getContext(),
R.layout.fragment_item, items));
itemList.setAdapter(adapter);
return (rootView);
}

Related

Set adapter for listview in fragment instead of activity

Hello!
I have tried to add a listview in a fragment but it doesn´t accept getApplicationContext:
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
and this:
Toast.makeText(Todo.this, "" + parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
How do I make it work for fragment instead of activity?
Code:
public class Todo extends Fragment {
EditText editText;
Button button;
ListView listView;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
public Todo() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.todo, container, false);
editText = editText.findViewById(R.id.editText);
button = button.findViewById(R.id.button2);
listView = listView.findViewById(R.id.list);
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String YeniVeri = editText.getText() .toString();
arrayList.add(YeniVeri);
adapter.notifyDataSetChanged();
editText.setText("");
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(Todo.this, "" + parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
}
});
// Inflate the layout for this fragment
return view;
}
}
You can use requireActivity() or container.context in onCreatView. So you can also access "contex" via container.
Exp(Kotlin):
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
var mContext:Context? = container.context
use requireActivity() instead of getApplicationContext and "ActivityName.this"

appcompat and fragment in one activity

I'm adding fragments to my menu.....now one of the menufragments is a listview and i need to use both appcompatactivity and fragment class which isn't possible to extends both
The error are in the Screenshots
public class friendjava extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.friends, container, false);
final ListView list = (ListView) findViewById(R.id.listview1);
final ArrayList<String> mylist = new ArrayList<>();
mylist.add("wisdom");
mylist.add("favour");
mylist.add("faith");
mylist.add("chisom");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mylist);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),mylist.get(position),Toast.LENGTH_SHORT).show();
}
});
}
}
the error are in screenshot this is error screenshot
That is a fragment. A fragment is separate from an activity. You have to bind it to an activity. The findViewById() method needs to be tied to a view of an activity.
Get the view reference to a view object first.
public class friendjava extends Fragment {
private View view;
private ListView list;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.friends, container, false);
list = view.findViewById(R.id.listview1);
final ArrayList<String> mylist = new ArrayList<>();
mylist.add("wisdom");
mylist.add("favour");
mylist.add("faith");
mylist.add("chisom");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mylist);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),mylist.get(position),Toast.LENGTH_SHORT).show();
}
});
}
return view;
}
Take care of how view is used and returned in the end.
Try changing
final ListView list = (ListView) findViewById(R.id.listview1);
into
final ListView list = findViewById(R.id.listview1);
and after that run the program and check logcat

How to set onItemClickListener for ListView in a fragment?

I try do it with below code but it not working! Please help me... I am confused ...
In below code all things is good but onItemClickListener is useless and it is in onCreateView method is wrong?
My items layout is not problem..
public class favFrg extends Fragment {
View v;
ListView listView;
List<HashMap<String,Object>> listFav;
DatabaseManager dbManager;
public favFrg() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v= inflater.inflate(R.layout.fragment_fav_frg, container, false);
listView= v.findViewById(R.id.listViewFav);
dbManager=new DatabaseManager(getContext());
dbManager.openDB();
listFav=dbManager.getStoryFavorite();
dbManager.closeDB();
String[] keys={"id","txtName"};
int[] resources={R.id.favTxtViewNumberStory,R.id.favTxtViewTitleStory};
SimpleAdapter adapter=new SimpleAdapter(getContext(),listFav,R.layout.fav_item_layout,keys,resources);
listView.setAdapter(adapter);
Log.i("ListView","Adapter Set");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("ListView","click item");
Toast.makeText(getActivity(),"Clicked",Toast.LENGTH_SHORT).show();
}
});
Log.i("ListView","Return View");
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
Just Only clickable and focusable attr in my item layout should be false... and works for me
https://code.i-harness.com/en/q/1561bd1
instead of getContext() use container.getContext() in creating adapter for listview.
Try making the SimpleAdapter as a public variable and put it outside the class onCreateView

How to modify a ListView in NavigationDrawer that uses a xml layout from AsyncTask

I have a AsyncTask and after it finishes execution I want to modify the NavigationDrawer's ListView, but I do not know how to do this.
This is my onCreateView() in NavigationDrawer Activity.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectItem(position);
}
});
rowItems = new ArrayList<ListItem>();
// Popolo.
for (int i = 0; i < text.length; i++) {
ListItem item = new ListItem(images[i], text[i]);
rowItems.add(item);
}
CustomListViewAdapter adapter = new CustomListViewAdapter(getActionBar()
.getThemedContext(), R.layout.list_item, rowItems);
mDrawerListView.setAdapter(adapter);
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
I want to modify a item in list from example by a AsyncTask.

How to add new Controls (Buttons, TextViews) to a Fragment dynamically

Here's my fragment class:
public class FirstFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
EditText newText = new EditText(getActivity());
newText.setText("This is a fragment");
newText.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
I am trying to add newText to the fragment being created.
simply store the view that was returned from the inflater.inflate call , and add anything you want to it .
in the end , return the stored view .

Categories