Restore spinner position in Fragment, after screen rotation - java

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

Related

Empty fragment after returning from the Second fragment. (Android App, Java)

I just created my first Android app through Android Studio using Java. I am working with two fragments in the process. The first fragment consists of a gridview with cards. When you click on a card you get to the Second Fragment. So far everything works. My problem is that when returning from the Second Fragment to the First Fragment (CategoryFragment) via the AppBar, the content remains empty. It seems that the method onCreateView is not executed again. What did I do wrong? Did I not understand something correctly?
public class CategoryFragment extends Fragment implements CardViewAdapter.ItemClickListener{
private RecyclerView recyclerView;
private CategoriesService categoriesData;
private SharedPreferences sharedPreferences;
private RequestQueue queue;
private FragmentCategoryBinding binding;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPreferences = this.getActivity().getSharedPreferences("SPOTIFY", 0);
queue = Volley.newRequestQueue(this.getActivity());
Toast.makeText(this.getContext(), "categoryFragment loaded" ,Toast.LENGTH_LONG).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_category, container, false);
categoriesData = new CategoriesService( view.getContext(), this.queue, this.sharedPreferences);
categoriesData.loadData();
CardViewAdapter mAdapter = new CardViewAdapter(view.getContext(), categoriesData.getCategories());
mAdapter.setClickListener(this);
recyclerView = view.findViewById(R.id.categoriesGrid);
recyclerView.setLayoutManager(new GridLayoutManager(view.getContext(), 6));
recyclerView.setAdapter(mAdapter);
return view;
/*
binding = FragmentCategoryBinding.inflate(inflater, container, false);
return binding.getRoot();
*/
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
/*
binding.buttonFirst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(CategoryFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
});
*/
}
#Override
public void onItemClick(View view, int pos) {
SpotifyCategoryCard item = categoriesData.getCategory(pos);
Toast.makeText(getContext(), "Click on '"+ item.getTitle() +"' (Type: '"+item.type+"')" ,Toast.LENGTH_SHORT).show();
NavHostFragment.findNavController(CategoryFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}

childfragment does not work when i click the button

I am trying to create a memory game, at the first page when I click on the play button it shows the categories and I used fragments. When I click on a button to go to another fragment it doesn't work.
Mainactivity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageViewA = findViewById(R.id.play_title);
imageViewA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
FragmentPlay fragA = new FragmentPlay();
transaction.add(R.id.fragmentContainer_main, fragA);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
}
FragmentPlay.java
public class FragmentPlay extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_play,container,false);
return rootView;
}
public void addFragB(){
FragmentManager childFragMan=getChildFragmentManager();
FragmentTransaction childFragTrans = childFragMan.beginTransaction();
FragmentAnimal fragmentAnimal = new FragmentAnimal();
childFragTrans.add(R.id.fragmentContainer_main2, fragmentAnimal);
childFragTrans.addToBackStack(null);
childFragTrans.commit();
}
}
FragmentAnimal.java
public class FragmentAnimal extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_animal,container,false);
return rootView;
}
}

Fragment throwing Nullpointer

So I have problem manipulating my TextView inside Fragment.
I have simple callback interface defining only onCallBackReceived(), when my method onCallbackReceived() is called back I want to change text of my TextView, however method setText("onCallback") throws NullPointerException. Exception says that the method is called on null object reference, but I initialized it first using findViewById(). Please help.
public class MyFragment extends Fragment implements MySimpleCallback {
TextView textView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.panel_fragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
textView = (TextView) view.findViewById(R.id.text_view);
textView.setText("Okay!");
}
#Override
public void onCallbackReceived() {
textView.setText("onCallback");
}
}
Maybe you can findTheViewById in the onCreateView
public class MyFragment extends Fragment implements MySimpleCallback {
TextView textView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.panel_fragment, container, false);
textView = (TextView) view.findViewById(R.id.text_view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
textView.setText("Okay!");
}
#Override
public void onCallbackReceived() {
textView.setText("onCallback");
}
}

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

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