gpt4 book ai didi

java - 无法获取父类(super class)中定义的上下文

转载 作者:行者123 更新时间:2023-12-01 09:06:27 25 4
gpt4 key购买 nike

我有一个 super 类:

public abstract class AsyncRequest {
private Context context;
public AsyncRequest(Context context) {
this.context = context;
}
public Context getContext() {
return this.context;
}
protected abstract String getHost();
}

还有两个子类:

public abstract class IRequest extends AsyncRequest{
IRequest(Context context) {
super(context);
}
@Override
public String getHost() {
return getHostFromSharedPreferences();
}
private String getHostFromSharedPreferences(){
SharedPreferences preferences = ((Activity) getContext()).getPreferences(Context.MODE_PRIVATE);
return preferences.getString(IPresenter.SP_HOST,"");
}
}

public class LoginRequest extends IRequest{
public LoginRequest(Context context, String name, String password) {
super(context);
}
}

当我初始化 LoginRequest 并使用 getContext() 获取 IRequest 中的上下文时,我得到 NullPointerException.

不知道为什么,有人知道吗?

最佳答案

确保在实例化 LoginRequest 时将 非 null Context 作为参数发送 LoginRequest(上下文上下文,字符串名称,字符串密码)

关于java - 无法获取父类(super class)中定义的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41234770/

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