Home > front end >  Sharedpreferences Context() on a null object reference
Sharedpreferences Context() on a null object reference

Time:02-15

I'm new to Sharedpreferences. I followed tutorial on youtube and his code works good. but my code didnot. What I am doing is make an class for Sharedpreferences. Then Another class to create the Acions on it. Then my third class to Acsses these Actions and make them work in the Adapter. Here's my code, and the error that I have.


PrefConfig

object PrefConfig {
private const val MY_PREFERENCE_NAME = "com.moataz.afternoonhadeeth.utils.helper"
private const val PREF_TOTAL_KEY = "pref_total_key"

fun saveTotalInPref(context: Context, total: Int) {
    val pref = context.getSharedPreferences(MY_PREFERENCE_NAME, Context.MODE_PRIVATE)
    val editor = pref.edit()
    editor.putInt(PREF_TOTAL_KEY, total)
    editor.apply()
}

fun loadTotalFromPref(context: Context): Int {
    val pref = context.getSharedPreferences(MY_PREFERENCE_NAME, Context.MODE_PRIVATE)
    return pref.getInt(PREF_TOTAL_KEY, 0)
    }
}

CounterActions

class CounterActions : AppCompatActivity() {

var counter = PrefConfig.loadTotalFromPref(this)

fun displayCounter(buttonCounter: Button) {
    buttonCounter.text = counter.toString()
}

fun addCounter(buttonCounter: Button) {
    counter  
    PrefConfig.saveTotalInPref(applicationContext, counter)
    buttonCounter.text = counter.toString()
    if (buttonCounter.text == 999.toString()) {
        counter = 0
        PrefConfig.saveTotalInPref(applicationContext, counter)
        buttonCounter.text = counter.toString()
    }
}

fun resetCounter(buttonCounter: Button) {
    counter = 0
    PrefConfig.saveTotalInPref(applicationContext, counter)
    buttonCounter.text = counter.toString()
  }
}

manifest for CounterActions class

        <activity
        android:name=".utils.helper.CounterActions"
        android:exported="true" />

HomeAdapter and there I call the mehouds from CounterActions class

    static class CounterViewHolder extends RecyclerView.ViewHolder {
    ItemHomeCounterBinding itemHomeCounterBinding;
    CounterActions counter = new CounterActions();

    CounterViewHolder(@NonNull ItemHomeCounterBinding itemView) {
        super(itemView.getRoot());
        itemHomeCounterBinding = itemView;
        counter.displayCounter(itemHomeCounterBinding.buttonCounter);
    }

    void setOnClick() {
        itemHomeCounterBinding.buttonCounter.setOnClickListener(v -> {
            counter.addCounter(itemHomeCounterBinding.buttonCounter);
            counter.vibrateOnce(itemView.getContext());
        });

        itemView.setOnClickListener(v -> {
            counter.addCounter(itemHomeCounterBinding.buttonCounter);
            counter.vibrateOnce(itemView.getContext());
        });

        itemHomeCounterBinding.resetButtonOnClick.setOnClickListener(v -> {
            counter.resetCounter(itemHomeCounterBinding.buttonCounter);
            counter.vibrateOnce(itemView.getContext());
        });
    }
}

Error code

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
    at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:174)
    at com.moataz.afternoonhadeeth.utils.helper.PrefConfig.loadTotalFromPref(PrefConfig.kt:19)
    at com.moataz.afternoonhadeeth.utils.helper.CounterActions.<init>(CounterActions.kt:13)
    at com.moataz.afternoonhadeeth.ui.adapter.HomeAdapter$CounterViewHolder.<init>(HomeAdapter.java:339)
    at com.moataz.afternoonhadeeth.ui.adapter.HomeAdapter.onCreateViewHolder(HomeAdapter.java:88)

CodePudding user response:

your CounterActions isn't used as an Activity, thus should extend it (remove : AppCompatActivity())

class CounterActions {

also remove related manifest entry

but how to obtain proper Context in there? just get it from buttonCounter, every View needs Context to be created. And Views are placed inside Activity, which is actually properly running (started by system/user interaction or by startActivity method)

class CounterActions {

    fun displayCounter(buttonCounter: Button) {
        var counter = PrefConfig.loadTotalFromPref(buttonCounter.context)
        buttonCounter.text = counter.toString()
    }

    fun addCounter(buttonCounter: Button) {
        var counter = PrefConfig.loadTotalFromPref(buttonCounter.context)
        counter  
        PrefConfig.saveTotalInPref(buttonCounter.context, counter)
        buttonCounter.text = counter.toString()
        if (buttonCounter.text == 999.toString()) {
            resetCounter(buttonCounter)
        }
    }

    fun resetCounter(buttonCounter: Button) {
        counter = 0
        PrefConfig.saveTotalInPref(buttonCounter.context, counter)
        buttonCounter.text = counter.toString()
      }
}
  • Related