Problems Making Plugin - Null Context

lblast

New member
Jan 11, 2018
1
0
0
Visit site
Hi there,
I was trying to develop a simple plugin to get shared preferences (they are stored in a slightly different location than Unity). The problem I'm encountering is that the context is null.

I've tried a lot of methods to get context but it always ends up with some sort of null:

AndroidJavaException: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

This is the plugin I've written currently. One thing I noticed (when I put Log.e in) is that it doesn't seem to call onCreate.

Code:
package com.test;
 
import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.content.SharedPreferences;
 
// This Util is used to help transition from the Android SDK to the Unity SDK
public class SharedPreferencesUtility extends Activity
{
    private Context context;
    private Activity activity;
    private static SharedPreferencesUtility instance;
    SharedPreferences sharedpreferences;
 
    private static final String TAG = "USERID_UTIL";
    public static final String PREFS_NAME = "user_saved_prefs";
 
    [MENTION=93274]overr[/MENTION]ide
    public void onCreate(Bundle savedInstance) {
 
        super.onCreate(savedInstance);
 
        activity = this;
 
        context = this.getApplicationContext();
    }
 
    public SharedPreferencesUtility() {
        this.instance = this;
    }
 
    public static SharedPreferencesUtility instance() {
        if(instance == null) {
            instance = new SharedPreferencesUtility();
        }
 
        return instance;
    }
 
    public String getPreferenceString (String prefKey) {
 
        //context = getApplicationContext();
        //context = instance.getApplicationContext();
        //context = this.getApplicationContext();
 
        sharedpreferences = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String userId = sharedpreferences.getString(prefKey, "");
        return userId;
    }
}

Any help solving this problem is greatly appreciated. I've done a lot of googling but I must be missing something.
 

Members online

Forum statistics

Threads
943,120
Messages
6,917,367
Members
3,158,830
Latest member
unirockers