从AsyncTask,java.lang.NullPointerException中的SharedPreferences获取字符串

时间:2018-04-04 19:07:12

标签: java android-studio sharedpreferences

我正在尝试在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);

    }
}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

也许你应该添加一个构造函数参数Context context