onItemClicked() in Fragment - java

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;
}

Related

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

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;
}
}

Selecting Spinner Item doesen't trigger onItemSelected - method

I have a settings fragment with 2 spinners in it. I'm not able to execute code written into the onItemSelected-method. There are no errors or exceptions.
I searched many similiar questions but none of the solutions worked for me. I have no idea what to try next.
public class SettingsFragment extends Fragment implements AdapterView.OnItemSelectedListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Getting the instance of Spinner and applying OnItemSelectedListener on it
View view = inflater.inflate(R.layout.fragment_settings, container, false);
Spinner spinnerBetrag = (Spinner) view.findViewById(R.id.spinnerBetrag);
Spinner spinnerDetails = (Spinner) view.findViewById(R.id.spinnerDetails);
spinnerBetrag.setOnItemSelectedListener(this);
spinnerDetails.setOnItemSelectedListener(this);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_settings, container, false);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
//>>Problem: Code within this method is never beeing executed<<
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Change your onCreateView() method to return the view
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Getting the instance of Spinner and applying OnItemSelectedListener on it
View view = inflater.inflate(R.layout.fragment_settings, container, false);
Spinner spinnerBetrag = (Spinner) view.findViewById(R.id.spinnerBetrag);
Spinner spinnerDetails = (Spinner) view.findViewById(R.id.spinnerDetails);
spinnerBetrag.setOnItemSelectedListener(this);
spinnerDetails.setOnItemSelectedListener(this);
return view; // add this instead
}
Also for your onItemSelected() add
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Spinner spinner = (Spinner) parent;
if(spinner.getId() == R.id.spinnerBetrag)
{
Log.d("Spinner 1","selected");
}
else if(spinner.getId() == R.id.spinnerDetails)
{
Log.d("Spinner 2","selected");
}
}
Change your return statement in onCreateView to
return view;
Your current return statement is inflating a whole new view

Restore spinner position in Fragment, after screen rotation

As I wrote in title the title, I want restore selected position in spinner, after screen rotation. Tried do this by saving position in bundle, and get position from savedInstanceState after rotation in
onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { }
or
onViewCreated(View view, Bundle savedInstanceState)
or
onActivityCreated(Bundle savedInstanceState)
but no one works :-/
AddRecipeFragment
public class AddRecipeFragment extends Fragment implements ObservableScrollViewCallbacks {
private static final String SELECTED_CATEGORY = "SELECTED_CATEGORY";
private Spinner categoriesSpinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add_recipe, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
categoriesSpinner = (Spinner) view.findViewById(R.id.categories_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.categories, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categoriesSpinner.setAdapter(adapter);
if (savedInstanceState != null) {
categoriesSpinner.setSelection(savedInstanceState.getInt(SELECTED_CATEGORY, 0), true);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SELECTED_CATEGORY, categoriesSpinner.getSelectedItemPosition());
}
}
I have also tried setSelection(position, false) with false.
If all that failed, why don't you use a static variable?!
private static int selectedPosition = 0;
and when spinner item selected
categoriesSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedPosition = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
and inside onViewCreated() method
categoriesSpinner.setSelection(selectedPosition);

Listview inside tabpager fragment not showing

Im trying to add a listview inside a fragment witch is also inside a tabhost. the app is not crashing or anything, but the list view is not showing anything.
Here is my code:
Class for the tabPager
public class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new FragmentHome();
case 1:
return new FragmentBadges();
case 2:
return new FragmentBenefits();
}
return null;
}
Following is the fragment where I want the listview:
public class FragmentBadges extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_badges_list, null);
BadgesListAdapter adapter = new BadgesListAdapter(this.getActivity(), getCurrentBadges());
ListView badgeslist = (ListView) rootView.findViewById(R.id.badges_list);
badgeslist.setAdapter(adapter);
badgeslist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO do some
}
});
return rootView;
}
And following is the adapter:
public class BadgesListAdapter extends ArrayAdapter<String> {
private final Activity context;
private List<Badge> badges;
public BadgesListAdapter(Activity context, List<Badge> badges) {
super(context, R.layout.fragment_badges_listrow);
this.context = context;
this.badges = badges;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.fragment_badges_listrow, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.text);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(badges.get(position).getName());
imageView.setImageResource(badges.get(position).getDrawableValue());
return rowView;
}
while debugging I found out that the getView method inside the badgesListAdapter is never called.
I have this same code for another app but without the tabpager and there it all works perfectly...
Check whether getCurrentBadges() method not returns empty list. If so there is no data to show in ListView.
I was able to make it work by inhering ListFragment in FragmentBadges, following this tutorial https://www.youtube.com/watch?v=heR4zhj_wV0

Categories