简体   繁体   中英

How can i retrieve data from sharedpreferences into fragment

i have SharedPrefManger class which save user information and retrieve data but when i use this into fragment return null pointer exception

package com.example.e_learning.storage;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.e_learning.jsondata.StudentData;
import com.example.e_learning.pojo.StudentModel;

public class SharedPrefManger {
    private static SharedPrefManger INSTANCE;
    private Context context;
    private static final String SHARED_PREF_NAME = "MySharedPref";

    public SharedPrefManger(Context context) {
        this.context = context;
    }

    public static SharedPrefManger getINSTANCE(Context context) {
        if (INSTANCE == null)
            INSTANCE = new SharedPrefManger(context);
        return INSTANCE;

    }

    public void saveUser(StudentData data) {
        SharedPreferences preferences = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putInt("id", data.getId());
        editor.putString("email", data.getEmail());
        editor.putString("name", data.getName());
        editor.putString("level", data.getLevel());

        editor.apply();
    }

    public boolean isLoggedIn() {
        SharedPreferences preferences = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return preferences.getInt("id", -1) != -1;
    }

    public StudentData getUser() {
        SharedPreferences preferences = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);

        return new StudentData(
                preferences.getInt("id", -1),
                preferences.getString("name", null),
                preferences.getString("email", null),
                preferences.getString("level", null)
        );

    }
    public void clear(){
        SharedPreferences preferences = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear();
        editor.apply();

    }
}

and i have a fragment which i want to retrieve the user into it but when i call getUser Id return null

this is my fragment

package com.example.e_learning.ui.fragments.announcement;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.e_learning.R;
import com.example.e_learning.databinding.FragmentAnnouncementBinding;
import com.example.e_learning.jsondata.AnnouncementsData;
import com.example.e_learning.storage.SharedPrefManger;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class AnnouncementFragment extends Fragment {


    private FragmentAnnouncementBinding binding;
    private AnnouncementsViewModel announcementsViewModel;

    public AnnouncementFragment() {
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_announcement, container, false);
        View view = binding.getRoot();
        return view;


    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        AnnouncementAdapter announcementAdapter = new AnnouncementAdapter();
        binding.announcementRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.announcementRecycler.setAdapter(announcementAdapter);
        announcementsViewModel.getStudentId().setValue(SharedPrefManger.getINSTANCE(this.getActivity()).getUser().getId());

        announcementsViewModel = new ViewModelProvider(requireActivity()).get(AnnouncementsViewModel.class);

        announcementsViewModel.getAnnouncements();
        announcementsViewModel.announcementsModelMutableLiveData.observe(getViewLifecycleOwner(), announcementsModel -> {
            if (announcementsModel.getStatus()) {
                announcementAdapter.setList((ArrayList<AnnouncementsData>) announcementsModel.getData());

            } else if (!announcementsModel.getStatus()) {
                Toast.makeText(getContext(), announcementsModel.getError(), Toast.LENGTH_SHORT).show();
            }
        });


    }


}



this line return null Pointer Exception


        announcementsViewModel.getStudentId().setValue(SharedPrefManger.getINSTANCE(this.getActivity()).getUser().getId());

how i can retrieve userdata into this fragment? this class works good with other activities

You must initialize the announcementsViewModel first before using it so you need to move this line

announcementsViewModel = new ViewModelProvider(requireActivity()).get(AnnouncementsViewModel.class);

before this

announcementsViewModel.getStudentId().setValue(SharedPrefManger.getINSTANCE(this.getActivity()).getUser().getId());

Create the object of the class Shared Preference, having constructor. and where you want to get it, just call the constructor with new keyword and that pref name method. Like: new PrefManager(getActivity).getData();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM