null对象引用上的NullPointerException addToRequestQueue(com.android.volley.Request,java.lang.String)'

ʍѳђ*_*ઽ૯ท 21 android android-volley

我正在使用AndroidHive寄存器登录,它在这个登录寄存器的示例项目中工作正常.

但经过多次尝试使用CardViews和其他小部件尝试后,此错误出现在LogCat:

java.lang.NullPointerException: Attempt to invoke virtual method 'void client.myproject.app.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference
            at client.myproject.RegisterActivity.registerUser(RegisterActivity.java:185)
            at client.myproject.RegisterActivity.access$300(RegisterActivity.java:35)
            at client.myproject.RegisterActivity$1.onClick(RegisterActivity.java:81)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Run Code Online (Sandbox Code Playgroud)

虽然这些代码在单个应用程序中正常工作(只需注册登录).

我正在使用Volley库.

Dam*_*lak 69

在你的AndroidManifest.xml添加

<application android:name="YOURPACKAGENAME.AppController" 
             android:allowbackup="true" 
             android:icon="@drawable/ic_launcher" 
             android:label="@string/app_name"
             android:theme="@style/AppTheme">
Run Code Online (Sandbox Code Playgroud)

  • 这是因为`AppController`,它扩展了`Application`. (2认同)
  • 在这里,您可以阅读"应用程序"用于:http://developer.android.com/reference/android/app/Application.html (2认同)

ism*_*a3l 7

正如N1to所说,你需要添加你的控制器AndroidManifest.xml,如果你不添加它,那么onCreate()永远不会调用,当你调用AppController.getInstance()实例时为null.

<application android:name="YOURPACKAGENAME.AppController" 
         android:allowbackup="true" 
         android:icon="@drawable/ic_launcher" 
         android:label="@string/app_name"
         android:theme="@style/AppTheme">
Run Code Online (Sandbox Code Playgroud)

它也适用于我:

<application android:name=".AppController" 
         android:allowbackup="true" 
         android:icon="@drawable/ic_launcher" 
         android:label="@string/app_name"
         android:theme="@style/AppTheme">
Run Code Online (Sandbox Code Playgroud)


小智 6

在我的情况下,我忘了初始化变量rq,请确保你做到了

    ...
    private RequestQueue rq;   // rq = null (NullPointerException if you use)
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        rq = Volley.newRequestQueue(YourActivity.this);  // rq != null
    }
    ...
    rq.add(request);
Run Code Online (Sandbox Code Playgroud)