我正在尝试在AsyncTask中的SharedPreferences中保存一个字符串,但不幸的是我收到以下错误:
java.lang.NullPointerException:尝试在空对象引用上调用虚方法'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String,int)'
以下是相关代码:
public class FetchData extends AsyncTask<Void, Void, String> {
private Context context;
String deviceId;
private AsyncInterface asyncInterface;
public FetchData(AsyncInterface asyncInterface) {
this.context = context;
this.asyncInterface = asyncInterface;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
SharedPreferences sharedPreferences = context.getSharedPreferences("deviceId", MODE_PRIVATE); //Error here
deviceId = sharedPreferences.getString("deviceId", deviceId);
}
}
我做错了什么?
答案 0 :(得分:1)
也许你应该添加一个构造函数参数Context context
。