2015-06-07 8 views
0

Извините, пытается выполнить POST-вызов по URL-адресу.Volley Android: Null Pointer Exception

Я следую этому руководству (http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/) для части ApplicationController.

Мой VolleyController это же его ApplicationController, это мой LoginActivity

public class LoginActivity extends ActionBarActivity { 

    final static String API_URL_LOGIN = "http://www.xxxx/account"; 
    private static String TAG = LoginActivity.class.getSimpleName(); 

    private EditText username; 
    private EditText password; 

    private String jsonResponse; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 

     username = (EditText) findViewById(R.id.login_username); 
     password = (EditText) findViewById(R.id.login_password); 

    } 

public void performLogin(View view) { 

     username = (EditText) findViewById(R.id.login_username); 
     password = (EditText) findViewById(R.id.login_password); 

     final String username_text = username.getText().toString(); 
     final String password_text = password.getText().toString(); 

     Log.d(TAG, username_text); 


     HashMap<String, String> params = new HashMap<String, String>(); 
     params.put("username", username_text); 

     JsonObjectRequest req = new JsonObjectRequest(API_URL_LOGIN, new JSONObject(params), 
       new Response.Listener<JSONObject>() { 
        @Override 
        public void onResponse(JSONObject response) { 
         try { 
          VolleyLog.v("Response:%n %s", response.toString(4)); 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       VolleyLog.e("Error: ", error.getMessage()); 
      } 
     }); 

     // add the request object to the queue to be executed 
     VolleyController.getInstance().addToRequestQueue(req); 

    } 

И это мой activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:orientation="vertical" 
    tools:context=".LoginActivity"> 

    <EditText android:id="@+id/login_username" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:hint="@string/hint_username" /> 

    <EditText android:id="@+id/login_password" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:hint="@string/hint_password" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/btn_login" 
     android:onClick="performLogin" /> 

</LinearLayout> 

Ошибка

FATAL EXCEPTION: main 
     java.lang.IllegalStateException: Could not execute method of the activity 
[...] 
Caused by: java.lang.NullPointerException 
      at com.webtemplum.hq60.LoginActivity.performLogin(LoginActivity.java:121) 

И линия 121 - VolleyController.getInstance().addToRequestQueue(req);

Это VolleyController

package com.webtemplum.hq60; 

import android.app.Application; 
import android.text.TextUtils; 

import com.android.volley.Request; 
import com.android.volley.RequestQueue; 
import com.android.volley.VolleyLog; 
import com.android.volley.toolbox.Volley; 

public class VolleyController extends Application { 

    /** 
    * Log or request TAG 
    */ 
    public static final String TAG = "VolleyPatterns"; 

    /** 
    * Global request queue for Volley 
    */ 
    private RequestQueue mRequestQueue; 

    /** 
    * A singleton instance of the application class for easy access in other places 
    */ 
    private static VolleyController sInstance; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 

     // initialize the singleton 
     sInstance = this; 
    } 

    /** 
    * @return ApplicationController singleton instance 
    */ 
    public static synchronized VolleyController getInstance() { 
     return sInstance; 
    } 

    /** 
    * @return The Volley Request queue, the queue will be created if it is null 
    */ 
    public RequestQueue getRequestQueue() { 
     // lazy initialize the request queue, the queue instance will be 
     // created when it is accessed for the first time 
     if (mRequestQueue == null) { 
      mRequestQueue = Volley.newRequestQueue(getApplicationContext()); 
     } 

     return mRequestQueue; 
    } 

    /** 
    * Adds the specified request to the global queue, if tag is specified 
    * then it is used else Default TAG is used. 
    * 
    * @param req 
    * @param tag 
    */ 
    public <T> void addToRequestQueue(Request<T> req, String tag) { 
     // set the default tag if tag is empty 
     req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); 

     VolleyLog.d("Adding request to queue: %s", req.getUrl()); 

     getRequestQueue().add(req); 
    } 

    /** 
    * Adds the specified request to the global queue using the Default TAG. 
    * 
    * @param req 
    * @param tag 
    */ 
    public <T> void addToRequestQueue(Request<T> req) { 
     // set the default tag if tag is empty 
     req.setTag(TAG); 

     getRequestQueue().add(req); 
    } 

    /** 
    * Cancels all pending requests by the specified TAG, it is important 
    * to specify a TAG so that the pending/ongoing requests can be cancelled. 
    * 
    * @param tag 
    */ 
    public void cancelPendingRequests(Object tag) { 
     if (mRequestQueue != null) { 
      mRequestQueue.cancelAll(tag); 
     } 
    } 
} 

Android Manifest в соответствии с просьбой

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.webtemplum.hq60" > 

    <uses-permission android:name="android.permission.INTERNET" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".LoginActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 
+0

опубликуйте свой 'VolleyController' – Blackbelt

+0

Dont вам нужно отправить пароль в качестве параметра вместе с именем пользователя – Pankaj

+0

@Blackbelt добавил спасибо – sineverba

ответ

1

в прикладном теге добавить

<application 
     android:name=".VolleyController" 
     // the rest stays the same 

вы получаете NPE, потому что вы не используете подкласс Application