我是 android 新手,我刚刚 checkout 了 volley android 库,我想在我的自定义 http 请求中使用它,但这在 android studio 的 .getInstance 中失败并出现错误
我尝试过以下方法
所以我使用 android studio 并具有以下文件夹结构
com.geowan .....
frontend
1.LoginActivity
helpers
ApiSingleTon
所以在我的 ApiSingleton 中我有
public class ApiSingleton {
private static ApiSingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private ImageLoader mImageLoader;
private ApiSingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
....stuff copy pasted from volley docs on IMage disc cache loader
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
现在我有我的java登录代码
ApiSingleton singleton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
trylogin(); //login method
}
});
}
tryLogin(){ //trying to emulate a http request
//proceed with authentication
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, loginurl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(TAG, response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.i(TAG, error.toString());
}
});
}
singleton.getInstance(this).addToRequestQueue(jsonObjectRequest); //fails
以上抛出错误
singleton.getInstance(this)
我哪里可能出错了。
最佳答案
首先,我想您需要阅读有关 Singleton 的更多内容
第二
singleton.getInstance(this)
这意味着您有一个名为 getInstance 的函数返回类中的类类型
所以我想你需要添加这个
public static synchronized AppSingleton getInstance(Context context) {
if (mAppSingletonInstance == null) {
mAppSingletonInstance = new AppSingleton(context);
}
return mAppSingletonInstance;
}
关于java - Android volley singleton getInstance(this) 在执行http请求时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49218191/