androidlayoutandroid-recyclerviewsharedpreferencesstaggeredgridlayoutmanager

How to save spanCount of RecyclerView on Shared Preferences?


my question is is there a way to save the SpamCount of a ReciclerView in SharedPreferences? I try to make a List that can change the view from a "List mode" to "Grid mode" and save that information in SharedPreferences so that the "List View" will remain after killing the app. The example of what I am trying to do would be the following ... example of what i try to do on button click

And the code that I try to change is the following ...


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static RecyclerView recyclerView;   
    private ReciclerAdapter reciclerAdapter;
    ImageView viewGridS, viewListS;

    SharedPreferences vSettings;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recicler_main);


        vSettings =  this.getSharedPreferences("Vision", 0);

        notesRecyclerView = findViewById(R.id.recycler_view);
        notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        viewListS = findViewById(R.id.viewList);
        viewGridS = findViewById(R.id.viewGrid);


    @Override
    public void onClick(View v) {
        SharedPreferences vSettings =  this.getSharedPreferences("Vision", 0);
        SharedPreferences.Editor viEdit = vSettings.edit();

        switch (v.getId())
        {
            case R.id.viewList:
                viewGridS.setVisibility(View.GONE);
                viewListS.setVisibility(View.VISIBLE);
                viEdit.putString("Vision",listView());
                viEdit.apply();
                break;
            case R.id.viewGrid:
                viewListS.setVisibility(View.GONE);
                viewGridS.setVisibility(View.VISIBLE);
                listWiew();
                viEdit.putString("Vision",gridView());
                viEdit.apply();
                break;
          }
     });
    }

    public int gridView(){
          notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        return null;
    } 

    public int listView(){
          notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL));
        return null;
    } 
}

When trying to start the Activity the RecyclerView does not show anything and the button does not work. if someone could help me I would appreciate it in advance ... thanks


Solution

  • You have done couple of things wrong here.

    Incorrect use of SharedPreferences

    Adapter on RecycleView not setup

    Manage LinearLayout and StaggeredGridLayoutManager

    I will try to accomplished kind similar end result which you are looking for, a simple button which is switching layout on click. Code as follows -

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
    
        private String LIST_VIEW = "List View";
        private String GRID_VIEW = "Grid View";
        private RecyclerView recyclerView;
        private LinearLayoutManager linearLayoutManager;
        private StaggeredGridLayoutManager staggeredGridLayoutManager;
        private SharedPreferences sharedPreferences;
        private RecycleViewAdapter recycleViewAdapter;
    
    
        @Override
        protected void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            //Simple List setup for data to show in recycle view
            List<String> stringList = new ArrayList<>();
            stringList.add("Monday\nI'll ask her out.");
            stringList.add("Tuesday");
            stringList.add("Wednesday\nI'll take her to garden to talk.");
            stringList.add("Thursday\nI'll give her a gift");
            stringList.add("Friday");
            stringList.add("Saturday");
            stringList.add("Sunday\nI'll propose her. ");
    
            sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    
            recyclerView = findViewById(R.id.recycler_view);
            recycleViewAdapter = new RecycleViewAdapter(this, stringList);
            
            linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
            
            staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
            
            /*
            * SharedPreferences value will be null for very first install of app
            * ELSE SharedPreferences will have use last saved value
            * */
            
            String CURRENT_VIEW = sharedPreferences.getString("LAYOUT_TYPE", null);
            if (CURRENT_VIEW == null) {
                CURRENT_VIEW = LIST_VIEW;
                sharedPreferences.edit().putString("LAYOUT_TYPE", LIST_VIEW).apply();
                recyclerView.setLayoutManager(linearLayoutManager);
                recyclerView.setAdapter(recycleViewAdapter);
            } else
                switchView(CURRENT_VIEW);
    
            Button buttonPanel = findViewById(R.id.buttonPanel);
            buttonPanel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(sharedPreferences.getString("LAYOUT_TYPE", null).equals(LIST_VIEW))
                        switchView(GRID_VIEW);
                    else
                        switchView(LIST_VIEW);
                }
            });
        }
    
        /*
        * Method will switch Layout on RecycleView and update new Adapter
        * @param: Required Layout Type (LIST_VIEW or GRID_VIEW)
        * */
        private void switchView(String layoutTypeValue) {
            if (layoutTypeValue.equals(LIST_VIEW))
                recyclerView.setLayoutManager(linearLayoutManager);
            else if (layoutTypeValue.equals(GRID_VIEW))
                recyclerView.setLayoutManager(staggeredGridLayoutManager);
    
            sharedPreferences.edit().putString("LAYOUT_TYPE", layoutTypeValue).apply();
            recyclerView.setAdapter(recycleViewAdapter);
        }
    }
    

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
        <Button
            android:padding="8dp"
            android:layout_margin="16dp"
            android:layout_gravity="end|bottom"
            android:id="@+id/buttonPanel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:background="@android:color/holo_orange_dark"
            android:text="Change Layout"/>
    </FrameLayout>
    

    RecycleViewAdapter.java

    public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.CustomViewHolder> {
    
        private Context context;
        private List<String> stringList;
    
        public RecycleViewAdapter(Context context, List<String> stringList) {
            this.context = context;
            this.stringList = stringList;
        }
    
        @NonNull
        @Override
        public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.recycle_item_layout, parent, false));
        }
    
        @Override
        public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
            holder.textView.setText(stringList.get(position));
        }
    
        @Override
        public int getItemCount() {
            return stringList.size();
        }
    
        public class CustomViewHolder extends RecyclerView.ViewHolder {
    
            private TextView textView;
    
            public CustomViewHolder(@NonNull View itemView) {
                super(itemView);
                textView = itemView.findViewById(R.id.text);
            }
        }
    }
    

    recycle_item_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_margin="8dp">
    
        <TextView
            android:id="@+id/text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp"
            android:background="@android:color/holo_blue_dark"
            android:textColor="@android:color/white"
            android:textSize="24sp" />
    
    </LinearLayout>
    

    Above code will give you following result -

    enter image description here

    Happy Coding !