簡體   English   中英

嘗試調用虛擬方法Volley Android Api

[英]Attempt to invoke virtual method Volley Android Api

我正在為Android App登錄編寫代碼。 應用程序將使用排球庫從網站api發出請求。 一切似乎都正常,但是當我在登錄框中輸入電子郵件和密碼並單擊登錄按鈕時,應用崩潰。 Logcat顯示嘗試調用虛擬方法的嘗試。 我試圖弄清楚一整天,但沒有任何解決方案

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import my.afamily.rrmn.app.AppConfig;
import my.afamily.rrmn.app.AppController;
import my.afamily.rrmn.helper.SQLiteHandler;
import my.afamily.rrmn.helper.SessionManager;


public class LoginActivity extends Activity {
private static final String TAG = LoginActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressBar progressBar;
private SessionManager session;
private SQLiteHandler db;`

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

    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    btnLogin = (Button) findViewById(R.id.btnRegister);
    btnLinkToRegister = (Button) findViewById(R.id.btnLinkToForgotPassword);
    progressBar = findViewById(R.id.progress_bar);

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Session manager
    session = new SessionManager(getApplicationContext());

    // Check if user is already logged in or not
    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    // Login button Click Event
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            // Check for empty data in the form
            if (!email.isEmpty() && !password.isEmpty()) {
                // login user
                checkLogin(email, password);
            } else {
                // Prompt user to enter credentials
                Toast.makeText(getApplicationContext(),
                        "Please enter the credentials!", Toast.LENGTH_LONG)
                        .show();
            }
        }

    });



}

/**
 * function to verify login details in mysql db
 */
private void checkLogin(final String email, final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_login";

    //Visible Progress Bar
    progressBar.setVisibility(View.VISIBLE);

    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_LOGIN, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Login Response: " + response.toString());
            //Hide Progress Bar
            progressBar.setVisibility(View.GONE);

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                // Check for error node in json
                if (!error) {
                    // user successfully logged in
                    // Create login session
                    session.setLogin(true);

                    // Now store the user in SQLite
                    String uid = jObj.getString("uid");

                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String created_at = user
                            .getString("created_at");

                    // Inserting row in users table
                    db.addUser(name, email, uid, created_at);

                    // Launch main activity
                    Intent intent = new Intent(LoginActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    // Error in login. Get the error message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Login Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            //Hide Progress Bar
            progressBar.setVisibility(View.GONE);
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}}

這就是Logcat所顯示的

java.lang.NullPointerException: Attempt to invoke virtual method 'void my.afamily.rrmn.app.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference
at my.afamily.rrmn.LoginActivity.checkLogin(LoginActivity.java:174)
    at my.afamily.rrmn.LoginActivity.access$200(LoginActivity.java:30)
    at my.afamily.rrmn.LoginActivity$1.onClick(LoginActivity.java:75)
    at android.view.View.performClick(View.java:6325)
    at android.view.View$PerformClick.run(View.java:25098)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:192)
    at android.app.ActivityThread.main(ActivityThread.java:6717)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:445)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:875)

這是AppController類的代碼

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

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

public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}

}

這條線

AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

在這里,您正在調用擴展Application class AppController實例,您需要在AndroidManifest.xml添加此類,否則它將返回NullException

因此,將其添加到manifest file

<application android:name="package.AppController" 
         android:allowbackup="true" 
         android:icon="@drawable/ic_launcher" 
         android:label="@string/app_name"
         android:theme="@style/AppTheme">

另請參閱以獲取更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM