-2

i am trying to call a method in string from sharedpreference but when i am calling i am facing method invocation getText may produce 'nullpointerexception' warning

public class RetrofitClient  {
   
        Sharedpreference sharedpreference;
        private final  String token = sharedpreference.getTEXT();

following is my sharedpreference code from where i am calling my method getText where i returning a string which is TEXT

  public class Sharedpreference  {
        
        public static String TEXT = "text";
        public static final String Otp = "1234";
        
     SharedPreferences prefs;
     SharedPreferences.Editor editor;
    
    public Sharedpreference(Context context){
        prefs=context.getSharedPreferences("App_key",0);
        editor=prefs.edit();
        editor.apply();
    }
   public  void setTEXT(String prize) {
    
            editor.putString(TEXT,prize);
            editor.commit();
    
        }
    
        public  String getTEXT() {
            return prefs.getString(TEXT,"");
        }
        public  void setotp(String otp) {
    
            editor.putString("otp",otp);
            editor.commit();
    
        }
        public  String getotp() {
            return prefs.getString("otp","");
        }
    
     }
  • Also paste the code of `SharedPreferences` class. – Jignesh M. Khatri Apr 09 '21 at 04:22
  • i had already paste sharepreference code and i want to call getText method in RetrofitClient class where i am facing warning and my app is crashing – Santosh Kumar Apr 09 '21 at 04:28
  • In which line you get the NPE? Take care of java naming conventions. Variable names should start with uppercase character and method names should be camelCase. – Jens Apr 09 '21 at 04:40

1 Answers1

0

You should create an instance of Sharedpreference inside RetrofitClient class.

Eg:

Sharedpreference sharedpreference = new Sharedpreference(...)
String token = sharedpreference.getTEXT();
Chathurika Sandarenu
  • 1,368
  • 13
  • 25