gpt4 book ai didi

java - Volley AppController 类对象返回 null

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:45:13 24 4
gpt4 key购买 nike

我正在制作一个应用程序,该应用程序生成 JsonObjectRequest 并使用 Android 的 Volley 网络库从 URL 检索 JSON 数据。

AppController.java

public class AppController extends AppCompatActivity {

public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mInstance = this;
}

public static synchronized AppController getInstance(){
return mInstance;
}

public RequestQueue getRequestQueue(){
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}

return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
}

MainActivity.class 中的方法

private void makeJSONObjectRequest() {

showDialog();

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
urlJsonObj, (String) null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());

try {

//Parsing JSON Object response
String name = response.getString("name");
String email = response.getString("email");
JSONObject phone = response.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");

jsonResponse = "";
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n";

txtResponse.setTag(jsonResponse);

}

catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}

hideDialog();
}
},

new ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.d(TAG+"Error:"+ volleyError.getMessage());
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_SHORT).show();
hideDialog();
}
});

/*THE ERROR OCCURS HERE! */
//adding request to the RequestQueue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}

它给出了以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.h8pathak.volleyjson.AppController.addToRequestQueue(com.android.volley.Request)' on a null object reference

我怎样才能纠正这个代码?

最佳答案

你的 AppController class需要扩展 Application 类而不是 AppCompatActivity 类。

并记得更新您的 list 。 IE。使用 <application> 的名称属性在您的 AndroidManifest.xml 中添加此类标签。

<application
android:name=".AppController"/>

关于java - Volley AppController 类对象返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34479808/

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