-1

TinyDb class is here

im using it simply by default codes like : TinyDB tinyDB = new TinyDB(MyActivity.this); and tinyDB.putInt("hadi" , 10);

but im getting an error that i cant understand . it say tinyDB is null object reference . you can see the error below :

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.ahmadi.TinyDB.TinyDB.putInt(java.lang.String, int)' on a null object reference
Hadi Ahmadi
  • 129
  • 12

3 Answers3

0

You have to create Object of Your TinyDB class like :-

TinyDB tinyDB = new TinyDB();
Xay
  • 248
  • 3
  • 10
  • not working . error : Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference – Hadi Ahmadi Mar 17 '18 at 06:26
  • error line in tinydb class : line 51 .line 51 code : "preferences = PreferenceManager.getDefaultSharedPreferences(appContext); " – Hadi Ahmadi Mar 17 '18 at 06:27
  • now you are getting N.P.E. on SharedPreference ..Post Shared Preference code – Xay Mar 17 '18 at 06:30
  • TinyDB tinyDB = new TinyDB(Myactivity.this); – Hadi Ahmadi Mar 17 '18 at 06:31
  • i just use this code . " tinyDB.putInt("hadi" , 10); " – Hadi Ahmadi Mar 17 '18 at 06:33
  • If you have only that much of code than why this line generating error! preferences = PreferenceManager.getDefaultSharedPreferences(appContext); – Xay Mar 17 '18 at 06:36
  • im using tinyDB class . that error is in that class – Hadi Ahmadi Mar 17 '18 at 06:39
  • this is the hole class http address : https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo – Hadi Ahmadi Mar 17 '18 at 06:39
0

You should properly initiate your TinyDB before using it!

For Example in Activity:

TinyDB tinyDB = new TinyDB(this); 
tinyDB.putInt("hadi" , 10);

or in Fragment:

TinyDB tinyDB = new TinyDB(getContext()); 
tinyDB.putInt("hadi" , 10);

TinyDB is just a simple wrapper around SharedPreferences so it is important that you provide a valid Context to it to initiate SharedPreferences

Keivan Esbati
  • 3,376
  • 1
  • 22
  • 36
0

You are getting error because you are passing context before Oncreate just pass the context after oncreate donot make it global variable.