尝试在空对象引用上调用虚拟方法“java.io.File android.content.Context.getCacheDir()”

Ned*_*vid 1 android nullpointerexception android-volley

我正在尝试使用 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

在这里,我试图在 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

此解决方案不起作用,我收到错误消息:

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) 
Run Code Online (Sandbox Code Playgroud)

Volley 有问题,但不知道出了什么问题。

cri*_*007 6

Volley 有问题

不,您的 API 类有问题。

确保你把它放在清单中

<application
    android:name=".API"
Run Code Online (Sandbox Code Playgroud)

在那之后

  1. 不要使用构造函数。使用onCreate. 或者,不要使用Application,并使用 Volley 范围的单例——参见文档中的示例
  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);
    }
Run Code Online (Sandbox Code Playgroud)
  1. 您不能return阻止异步函数的值。使用回调传回结果

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);
}
Run Code Online (Sandbox Code Playgroud)
  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.
    }
});
Run Code Online (Sandbox Code Playgroud)
  1. 最重要的是,使用 Volley 时不需要 AsyncTask。它已经是异步的

在相关说明中,如果您使用 RESTful API,那么 Retrofit 可能更有用