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

时间:2017-09-10 22:07:52

标签: 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;
    }

}

这里我尝试在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有问题,但不知道出了什么问题。

1 个答案:

答案 0 :(得分:3)

  

Volley存在问题

不,您的API类存在问题。

确保将其放入清单

<application
    android:name=".API"

之后

  1. 不要使用构造函数。使用onCreate,请勿使用Application,并使用排球范围的单身人士 - see example from documentation
  2. localhost替换为实际的服务器地址
  3. 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阻止来自异步功能的值。使用回调传回结果
    2. 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())
      2. 时,请不要使用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。它已经异步
        2. 在相关的说明中,如果您使用的是RESTful API,那么Retrofit可能会更有用