[英]How do I instantiate Volley in this class?
I am trying to learn about MVVM so i am building an app based on this principle, I understand that i need to separate functionalities under different packages, such as model, view, viewmodel.我正在尝试了解 MVVM,因此我正在基于此原理构建应用程序,我知道我需要在不同的包下分离功能,例如 model、视图、视图模型。 What i am trying to do here is populate my HighSchoolDataModel, from my class HighSchoolDataModleProvider.我在这里要做的是从我的 class HighSchoolDataModleProvider 填充我的 HighSchoolDataModel。 Issue, i am having is i do not know how to instantiate volley, in this class.问题,我不知道如何在这个 class 中实例化凌空。 I know ordinarily you would so something such as RequestQueue queue = Volley.newRequestQueue(this);
我知道通常你会这样,例如RequestQueue queue = Volley.newRequestQueue(this);
But when trying to do this here i get a message that reads cannot resolve constructor, can someone help me out with this?但是当在这里尝试这样做时,我收到一条消息,上面写着无法解析构造函数,有人可以帮我解决这个问题吗?
public class HighSchoolModelDataProvider {
private ArrayList<HighSchoolModel> highSchoolModelArrayList = new ArrayList<>();
private HighSchoolModel highSchoolModel;
private JSONObject highSchoolJsonData;
private RequestQueue requestQueue = new RequestQueue(this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
"",
null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
highSchoolJsonData = response.getJSONObject(i);
highSchoolModel = new HighSchoolModel(highSchoolJsonData.getString("school_name"), highSchoolJsonData.getString("overview_paragraph"), highSchoolJsonData.getString("location"));
highSchoolModelArrayList.add(highSchoolModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("error", error.toString());
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}
Yo, you made a small mistake.哟,你犯了一个小错误。
private RequestQueue requestQueue = new RequestQueue(this);
this
in above code represents context
of component from which you are making requestQueue
object.上面代码中的this
表示您从中创建requestQueue
object 的组件的context
。 context
object is present in activity/fragment etc. You need to pass it to constructor. context
object 存在于活动/片段等中。您需要将其传递给构造函数。
If you got the answer you want please accept my answer by giving green check.如果你得到你想要的答案,请通过绿色检查接受我的答案。 If I haven't got your question then give me more details in comment section of this answer.如果我没有收到您的问题,请在此答案的评论部分中给我更多详细信息。 Love from India.❤️来自印度的爱❤️
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.