AndyCr15
AndyCr15

Reputation: 475

Attempt to invoke interface method sharedPreferences.edit()' on a null object reference

I am trying to write a method that will save the maintenance logs for each bike in my app. The method cycles through each bike, which internally cycles through each maintenance log and saves it.

I can see the correct information is there because of the Log.i placed at each point.

The full code for my method -

public static void saveLogs() {

        for (Bike thisBike : bikes) {

            Log.i("Saving Logs", "" + thisBike);
            try {
                ArrayList<String> dates = new ArrayList<>();
                ArrayList<String> logs = new ArrayList<>();
                ArrayList<String> costs = new ArrayList<>();

                for (maintenanceLogDetails thisLog : thisBike.maintenanceLogs) {

                    Log.i("Date :", thisLog.date);
                    dates.add(thisLog.date);
                    Log.i("Log :", thisLog.log);
                    logs.add(thisLog.log);
                    Log.i("Cost :", Double.toString(thisLog.price));
                    costs.add(Double.toString(thisLog.price));

                }

                sharedPreferences.edit().putString("dates", ObjectSerializer.serialize(dates)).apply();
                sharedPreferences.edit().putString("logs", ObjectSerializer.serialize(logs)).apply();
                sharedPreferences.edit().putString("costs", ObjectSerializer.serialize(costs)).apply();

            } catch (Exception e) {
                e.printStackTrace();
                Log.i("Adding details", "Failed attempt");
            }
        }
    }

At the top of the class I have -

static SharedPreferences sharedPreferences;

The full error I am getting is -

Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference

At the line that is -

sharedPreferences.edit().putString("dates", ObjectSerializer.serialize(dates)).apply();

What confuses me, I've pretty much copied the code from somewhere else that works.

What am I doing wrong?

Many thanks!

Upvotes: 0

Views: 1458

Answers (1)

Mercato
Mercato

Reputation: 569

static SharedPreferences sharedPreferences;

Did you even instantiate it..??

getContext().getSharedPreferences(String, int)

https://developer.android.com/reference/android/content/SharedPreferences.html

https://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String,%20int)

Upvotes: 1

Related Questions