尝试在空对象引用[duplicate]上调用虚方法'java.io.File android.content.Context.getCacheDir()'

一身转战三千里,一剑曾当百万师。这篇文章主要讲述尝试在空对象引用[duplicate]上调用虚方法' java.io.File android.content.Context.getCacheDir()' 相关的知识,希望能为你提供帮助。
这个问题在这里已有答案:

  • What is a NullPointerException, and how do I fix it? 12个答案
我正在尝试使用Volley并在登录后发送GET请求来检查数据。 我有特殊级别的'API',所有的Volley员工都在这里。 我想要做的是在LoginActivity中检查验证后(默认的android studio模板)我想在LoginActivity中创建API实例并向服务器发送GET请求。 这仅用于测试Volley,后来我想在一些Main类中创建一个API实例。
这是我的API类:
import android.app.Application; import android.util.Log; import com.android.volley.*; import com.android.volley.toolbox.Volley; import com.android.volley.toolbox.JsonObjectRequest; import org.json.JSONObject; import java.lang.String; public class API extends Application {protected String ServerURL; protected String GET; protected String POST; protected RequestQueue queue; public API(){ setServerURL("http://localhost:63424"); setGET("http://localhost:63424/api"); setPOST("http://localhost:63424/api"); queue = Volley.newRequestQueue(this); }protected void SendGET (String request) { JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, request, null, new Response.Listener< JSONObject> () { @Override public void onResponse(JSONObject response) { // display response Log.d("ResponseAPI", response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("Error.ResponseAPI", error.toString()); } } ); queue.add(getRequest); }//Logowanie public boolean CheckLogin (String Login, String Password){ setGET(getGET()+"/Search_Users_/login=/"+Login + "/"); SendGET(getGET()); return true; }public String getServerURL() { return ServerURL; }public void setServerURL(String ServerURL) { ServerURL = ServerURL; }public String getGET() { return GET; }public void setGET(String GET) { this.GET = GET; }public String getPOST() { return POST; }public void setPOST(String POST) { this.POST = POST; }}

在这里,我尝试在LoginActivity中创建API实例:
public class UserLoginTask extends AsyncTask< Void, Void, Boolean> {private final String mEmail; private final String mPassword; UserLoginTask(String email, String password) { mEmail = email; mPassword = password; }@Override protected Boolean doInBackground(Void... params) { // TODO: attempt authentication against a network service.try { // Simulate network access. Thread.sleep(2000); } catch (InterruptedException e) { return false; } Log.d("API", "Zaraz utworze API"); API api = new API(); return api.CheckLogin(mEmail, mPassword); // TODO: register the new account here.}@Override protected void onPostExecute(final Boolean success) { mAuthTask = null; showProgress(false); if (success) { finish(); } else { mPasswordView.setError(getString(R.string.error_incorrect_password)); mPasswordView.requestFocus(); } }@Override protected void onCancelled() { mAuthTask = null; showProgress(false); } }

这个解决方案不起作用,我收到一个错误:
FATAL EXCEPTION: AsyncTask #1 Process: pawel.cooker, PID: 2646 java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:353) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383) at java.util.concurrent.FutureTask.setException(FutureTask.java:252) at java.util.concurrent.FutureTask.run(FutureTask.java:271) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) at java.lang.Thread.run(Thread.java:764) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getCacheDir()' on a null object reference at android.content.ContextWrapper.getCacheDir(ContextWrapper.java:256) at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:43) at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78) at pawel.cooker.API.< init> (API.java:17) at pawel.cooker.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:320) at pawel.cooker.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:299) at android.os.AsyncTask$2.call(AsyncTask.java:333) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) at java.lang.Thread.run(Thread.java:764)

Volley有问题,但不知道出了什么问题。
答案
Volley存在问题
不,您的API类存在问题。
确保将其放入清单中
< application android:name=".API"

之后
  1. 不要使用构造函数。使用onCreate。或者,不要使用Application,并使用Volley-scoped singleton-see example from documentation
  2. localhost替换为实际的服务器地址


public class API extends Application {public static final String ServerURL = "http://< Use real server here> :63424"; public static final String GET = ServerURL+"/api"; public static final String POST = ServerURL+"/api"; protected RequestQueue queue; private final API mInstance; private API() { }public API getInstance() { return mInstance; }@Override public void onCreate(){ super.onCreate(); mInstance = this; queue = Volley.newRequestQueue(this); }

  1. 你不能return阻止Async函数的值。使用回调来传回结果


protected void sendGET (String url, Response.Listener< JSONObject> onSuccess) { JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null, onSuccess, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("Error.ResponseAPI", error.toString()); } } ); queue.add(getRequest); }public void checkLogin (String Login, Response.Listener< JSONObject> onSuccess){ SendGET(GET+"/Search_Users_/login=/"+Login, onSuccess); }

  1. 当你应该使用new API()或使用上面的实现时,不要使用((API) getApplicationContext())API.getInstance()
例如,
API api = API.getInstance(); api.checkLogin(mEmail, new Response.Listener< JSONObject> () { @Override public void onResponse(JSONObject response) { // TODO: register the new account here. } });

  1. 最重要的是,在使用Volley时,您不需要AsyncTask。它已经是异步的
【尝试在空对象引用[duplicate]上调用虚方法' java.io.File android.content.Context.getCacheDir()' 】在相关的说明中,如果您使用的是RESTful API,那么Retrofit可能会更有用

    推荐阅读