gpt4 book ai didi

java - 尝试在空对象引用上调用接口(interface)方法sharedPreferences.edit()'

转载 作者:行者123 更新时间:2023-12-02 13:11:05 25 4
gpt4 key购买 nike

我正在尝试编写一种方法来保存应用程序中每辆自行车的维护日志。该方法循环遍历每辆自行车,在内部循环遍历每个维护日志并保存它。

由于每个点都放置了 Log.i,因此我可以看到正确的信息。

我的方法的完整代码 -

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");
}
}
}

我在类名列前茅 -

static SharedPreferences sharedPreferences;

我得到的完整错误是 -

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

在 - 行

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

令我困惑的是,我几乎从其他有效的地方复制了代码。

我做错了什么?

非常感谢!

最佳答案

static SharedPreferences sharedPreferences;

你甚至实例化了它吗??

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)

关于java - 尝试在空对象引用上调用接口(interface)方法sharedPreferences.edit()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43955120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com