我无法在此代码中使用 (this)。我从 IDEA 得到的建议是扩展 Context,我绝对不想这样做。我试过导入 Context 并改用 (Context context),但没有成功。为什么我不能使用“this”?
公共(public)类 LastFMLogin {
final String lastFMKeyURL = "http://www.last.fm/api/auth/?api_key=" + R.string.lastfm_api_key;
RequestQueue queue = Volley.newRequestQueue(this);
public void authGetRequest() {
// prepare the Auth Get Request
JsonObjectRequest lastFMAuthRequest = new JsonObjectRequest(Request.Method.GET, lastFMKeyURL, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
});
// add it to the RequestQueue
queue.add(lastFMAuthRequest);
}
我的教程类调用了 lastFMAuthRequest,但出现“无法解析上下文”错误。
public void lastFMButtonListener() {
ImageButton lastfm_login = (ImageButton) findViewById(R.id.lastfm_login);
lastfm_login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Log.d(debug, "LastFM Round clicked");
//Change button image
ImageButton lastfm_login = (ImageButton) findViewById(R.id.lastfm_login);
lastfm_login.setImageResource(R.drawable.lastfm_pressed);
LastFMLogin lastFMLogin = new LastFMLogin();
lastFMLogin.lastFMAuthRequest(Context context);
}
});
}
最佳答案
您可以在服务或 Activity 中使用“this”。等,但不在自定义类中。因为自定义(未扩展)类中的“this”不等于 Context。使用 satti 代码为您的类(class)提供上下文。
或者只为方法提供上下文:
final String lastFMKeyURL = "http://www.last.fm/api/auth/?api_key=" + R.string.lastfm_api_key;
RequestQueue queue = null;
public void authGetRequest(Context context) {
queue = Volley.newRequestQueue(context);
// prepare the Auth Get Request
JsonObjectRequest lastFMAuthRequest = new JsonObjectRequest(Request.Method.GET, lastFMKeyURL, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
});
// add it to the RequestQueue
queue.add(lastFMAuthRequest);
}
当您在许多方法中使用 Context 并且不想在调用它时在每个方法中添加 Context 参数时,使用默认构造函数是很好的。 例如:
MyClass myClass = new MyClass(this); // Called ones
然后只需使用:
myClass.method1();
myClass.method2();
myClass.method3();
myClass.method4();
等等
每个方法都使用您在默认构造函数中提供的上下文。
此外,您不仅可以使用“this”。
getApplicationContext()
getBaseContext()
差异在文档中解释。
尽情享受吧! )
关于android - 这个/扩展上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26044125/