appcompat and fragment in one activity - java

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

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"

listView items are repeating and becoming more each time app runs

I am implementing a sample app for android and in the list view I don't use view holder so I couldn't get my answer from other answers. my list view items are repeating and becoming more each time I run the app unless I uninstall the app from emulator.
here is my code where in the first class I declare the list view and set adapter and the next class is the customized adapter(I removed unnecessary functions):
public class CrimeListFragment extends Fragment {
private ListView crimesListView;
private CrimeAdapter adapter;
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View CrimesList=inflater.inflate(R.layout.fragment_crime_list,container,false);
crimesListView=(ListView) CrimesList.findViewById(R.id.crimesList);
adapter=new CrimeAdapter(inflater.getContext(),R.layout.list_item_crime,CrimeLab.get(inflater.getContext()).getCrimes());
crimesListView.setAdapter(adapter);
}
public class CrimeAdapter extends ArrayAdapter {
Context _context;
List<Crime> _crimes;
static Crime currentCrime;
public CrimeAdapter( Context context, int resource, List crimes) {
super(context, resource, crimes);
_context=context;
_crimes=crimes;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View _convertView = convertView; // re-use an existing view, if one is available
if (_convertView == null)
_convertView= ((Activity)_context).getLayoutInflater().inflate(R.layout.list_item_crime,null);
currentCrime=_crimes.get(position);
((TextView)_convertView.findViewById(R.id.crimeTitleText)).setText(currentCrime.getTitle().toString());
((TextView)_convertView.findViewById(R.id.crimeDateText)).setText(currentCrime.getCrimeDate().toString());
((ImageView)_convertView.findViewById(R.id.crimeImageSolved)).setVisibility(currentCrime.getSolved() ? View.VISIBLE : View.GONE);
return _convertView;
}
public void setCrimes(List<Crime> crimes){
_crimes=crimes;
}
}
Change
_convertView= ((Activity)_context).getLayoutInflater().inflate(R.layout.list_item_crime,null);
to
_convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_crime, parent, false);
Try replacing your CrimeListFragment code with below snippet. Hope it will solve your problem.
public class CrimeListFragment extends Fragment {
private ListView crimesListView;
private CrimeAdapter adapter;
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View CrimesList=inflater.inflate(R.layout.fragment_crime_list,container,false);
crimesListView=(ListView) CrimesList.findViewById(R.id.crimesList);
List<Crime> _crimes = new ArrayList();
_crimes.clear();
_crimes = CrimeLab.get(inflater.getContext()).getCrimes();
adapter=new CrimeAdapter(inflater.getContext(),R.layout.list_item_crime, _crimes);
crimesListView.setAdapter(adapter);
}
public class CrimeAdapter extends ArrayAdapter {
Context _context;
List<Crime> _crimes;
static Crime currentCrime;
public CrimeAdapter( Context context, int resource, List crimes) {
super(context, resource, crimes);
_context=context;
_crimes=crimes;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View _convertView = convertView; // re-use an existing view, if one is available
if (_convertView == null)
_convertView= ((Activity)_context).getLayoutInflater().inflate(R.layout.list_item_crime,null);
currentCrime=_crimes.get(position);
((TextView)_convertView.findViewById(R.id.crimeTitleText)).setText(currentCrime.getTitle().toString());
((TextView)_convertView.findViewById(R.id.crimeDateText)).setText(currentCrime.getCrimeDate().toString());
((ImageView)_convertView.findViewById(R.id.crimeImageSolved)).setVisibility(currentCrime.getSolved() ? View.VISIBLE : View.GONE);
return _convertView;
}
public void setCrimes(List<Crime> crimes){
_crimes=crimes;
}
}

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

android can't use getLayoutInflater in fragment

I am using fragments and i trying to build a list i am getting from the database. Everything seems to be fine except for the following piece of code
listadapter = new charitylist(this, getLayoutInflater());
I already set the layout inflater here
LayoutInflater lf = getActivity().getLayoutInflater();
But i don't have any idea how to use the layoutinflater lf int the listadapter.
This is the full code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LayoutInflater lf = getActivity().getLayoutInflater();
View view = lf.inflate(R.layout.activity_charity, container, false);
listView = (ListView) view.findViewById(R.id.charityList);
listadapter = new charitylist(this, getLayoutInflater());
listView.setAdapter(listadapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//String trackName = listadapter.getItem(position).optString("track_name", "");
}
});
setType = "favourite";
getlist(setUrl, setType);
return view;
}
I have no idea how to get this working. I tried several things to get this to work. But i need to initiate the adapter.
Thank for your help.
LayoutInflater inflater is already provided in onCreateView of Fragment. Why don't you use like this:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.activity_charity, container, false);
listView = (ListView) view.findViewById(R.id.charityList);
listadapter = new charitylist(getActivity(), inflater);
...

onItemClicked() in Fragment

I created a ListView within a fragment and populated it with data from a class called Workout within the onStart() method. I set an Adapter and the list shows up fine. I would like to now be able to get the value of the specific row that the user clicks but am unable to implement an onItemClicked() method. Does anyone know how I can get this value? Thank you.
public class WorkoutListFragment extends Fragment {
static interface WorkoutListListener{
void itemClicked(long id);
}
private WorkoutListListener listener;
private ListView workoutList;
private LayoutInflater inflate;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflate = inflater;
return inflater.inflate(R.layout.fragment_workout_list, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.listener = (WorkoutListListener)activity;
}
#Override//ISSUE IS IN HERE
public void onStart() {
super.onStart();
View view = getView();
String[]names = new String[Workout.workouts.length];
for (int i = 0; i < names.length; i++){
names[i] = Workout.workouts[i].getName();
}
if (view!=null){
workoutList = (ListView)view.findViewById(R.id.listView);
ArrayAdapter<String>adapter = new ArrayAdapter<String>(inflate.getContext(),
android.R.layout.simple_list_item_1,names);
workoutList.setAdapter(adapter);
}
//HOW CAN I NOW GET THE VALUE OF THE ITEM CLICKED?
// I TRIED THIS BUT IT'S NOT RECOGNIZED
workoutList.setOnClickListener(new onItemClickListener);
}
Use this:
workoutList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// the 'position' argument is the position you are looking for
}
});
EDIT:
I noticed that you are not initializing the workoutList listView. You should do that in the OnCreateView method:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_workout_list, container, false);
workoutList = (ListView) view.findViewById(R.id.workoutListView); // assuming that your listView's id is "#+id/workoutListView"
return view;
}

Categories