onCreate外的getApplicationContext()上传图像

时间:2017-02-20 17:57:46

标签: android android-studio android-sharedpreferences

我想将图片上传到服务器。但是我需要发送来自发送图像的用户的用户名。

我在SharedPreferences中有用户名记录,所以我想我可以得到它:

public class UploadRequest extends StringRequest {
    private static final String REGISTER_REQUEST_URL = "http://160.128.0.10/up.php";
    private Map<String, String> params;

    public UploadRequest(String image, String name, Response.Listener<String> listener){
        super(Method.POST, REGISTER_REQUEST_URL, listener, null);

        SharedPreferences pref = getApplicationContext().getSharedPreferences("pref01", MODE_PRIVATE); 
// CANNOT RESOLVE SYMBOL getApplicationContext
        String user = pref.getString("username", null);

        params = new HashMap<>();
        params.put("image",image);
        params.put("name",name);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }
}

是不是错了?我怎样才能获得这个用户名?

3 个答案:

答案 0 :(得分:3)

/只能从Context的子类调用,Activity就是其中之一,这就是您可以从Activity调用getApplicationContext()的原因。

您需要做的是在Application类中初始化getApplicationContext()(不建议)或将Context作为参数传递给此类。

答案 1 :(得分:2)

您需要做的是,只需通过构造函数将主活动的上下文传递给此类。因此,创建构造函数为:

public UploadRequest(Context context, String image, String name, Response.Listener<String> listener){
    super(Method.POST, REGISTER_REQUEST_URL, listener, null);

    SharedPreferences pref = context.getSharedPreferences("pref01", MODE_PRIVATE); 
// CANNOT RESOLVE SYMBOL getApplicationContext
    String user = pref.getString("username", null);

    params = new HashMap<>();
    params.put("image",image);
    params.put("name",name);
}

当您从活动中初始化它时,将this参数作为活动的上下文传递。像这样:

UploadRequest ur = new UploadRequest(this, OTHER_PARAMETERS_HERE);

正如其他人的评论中所提到的,您的代码无效,因为getApplicationContext()是一个函数,当且仅当对象定义了该函数时才可以调用它。

答案 2 :(得分:1)

你不能在android的任何地方轻松使用getApplicationContext()。所以从android的角度来看错误是完全正确的。

主要在网络呼叫的情况下,不要在任何地方使用上下文引用。很多时候情境与Ui(活动)有关。您将遇到NullPointersExpetions的困难时期。

解决方案:

将您的用户名作为参数传递。

public class UploadRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://160.128.0.10/up.php";
private Map<String, String> params;

public UploadRequest(String image, String usernName,String name, Response.Listener<String> listener){
    super(Method.POST, REGISTER_REQUEST_URL, listener, null);

    SharedPreferences pref = getApplicationContext().getSharedPreferences("pref01", MODE_PRIVATE); 
// CANNOT RESOLVE SYMBOL getApplicationContext
    String user = pref.getString("username", null);

    params = new HashMap<>();
    params.put("image",image);
    params.put("name",name);
}

@Override
public Map<String, String> getParams() {
    return params;
}
}