Android Volley onErrorResponse没有给出错误

时间:2016-02-22 19:15:56

标签: android android-volley

我正在尝试使用volley进行用户登录和注册,但在尝试登录或注册时遇到了问题。我尝试连接的服务器在我的localhost上,它已打开并正常工作,我可以从其他应用程序访问它。

当我输入登录/注册凭据并按下按钮时,我会得到一条日志,说明错误消息为空。问题是应用程序没有崩溃,并且日志cat没有指向导致错误的任何行,所以我不知道发生了什么问题。

我尝试了不同的排球错误方法,例如error.networkResponse和其他一些尝试获取更多信息但没有返回任何信息。

我已经在网站上看到了遇到类似问题的其他解决方案,但似乎没有任何效果。

有人可以向我解释为什么我会收到此错误吗?

记录日志

Login Error: null

类打印日志 - LoginActivity

import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    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 com.example.rory.pocketchef.R;
    import com.example.rory.pocketchef.app.AppConfig;
    import com.example.rory.pocketchef.app.AppController;
    import com.example.rory.pocketchef.helper.SQLiteHandler;
    import com.example.rory.pocketchef.helper.SessionManager;

    public class LoginActivity extends Activity {
        private static final String TAG = RegisterActivity.class.getSimpleName();
        private Button btnLogin;
        private Button btnLinkToRegister;
        private EditText inputEmail;
        private EditText inputPassword;
        private ProgressDialog pDialog;
        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.btnLogin);
            btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

            // Progress dialog
            pDialog = new ProgressDialog(this);
            pDialog.setCancelable(false);

            // 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, FirstActivity.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();
                    }
                }

            });

            // Link to Register Screen
            btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    Intent i = new Intent(getApplicationContext(),
                            RegisterActivity.class);
                    startActivity(i);
                    finish();
                }
            });

        }

        /**
         * 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";

            pDialog.setMessage("Logging in ...");
            showDialog();

            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());
                    hideDialog();

                    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, FirstActivity.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();
                    hideDialog();
                }
            }) {

                @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);
        }

        private void showDialog() {
            if (!pDialog.isShowing())
                pDialog.show();
        }

        private void hideDialog() {
            if (pDialog.isShowing())
                pDialog.dismiss();
        }
    }

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);
            }
        }
    }

清单

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

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

    <android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


    <application
        android:name=".app.AppController"
        android:allowBackup="true"
        android:icon="@mipmap/ic_logo"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/MyMaterialTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SingleRecipeDisplay"
            android:label="@string/title_activity_single_recipe_display"
            android:theme="@style/MyMaterialTheme" >
        </activity>
        <activity android:name=".Favourites" >
        </activity>
        <activity android:name=".Help" >
        </activity>
        <activity android:name=".activity.RegisterActivity">
        </activity>
        <activity android:name=".activity.LoginActivity">
        </activity>

    </application>

</manifest>

尝试注册时记录Cat(登录尝试的结果相同)

02-25 12:09:19.558 20001-20001/com.example.rory.loginandregistration E/RegisterActivity: Login Error: null
02-25 12:09:19.579 20001-20001/com.example.rory.loginandregistration D/Volley: [1] Request.finish: 7636 ms: [ ] http://178.167.255.22:8886/android_login_api/login.php 0x1d219ab4 NORMAL 1

记录Cat打印堆栈

02-25 12:28:17.680 9729-9729/com.example.rory.pocketchef W/System.err: com.android.volley.TimeoutError
02-25 12:28:17.680 9729-9729/com.example.rory.pocketchef W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:147)
02-25 12:28:17.680 9729-9729/com.example.rory.pocketchef W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:114)
02-25 12:28:28.391 9729-9743/com.example.rory.pocketchef I/art: Background sticky concurrent mark sweep GC freed 32313(1656KB) AllocSpace objects, 2(40KB) LOS objects, 35% free, 15MB/23MB, paused 9.512ms total 135.206ms

2 个答案:

答案 0 :(得分:6)

getMessage()有时可能为空。这就是我如何阅读volley onErrorResponse(),volley有直接/子直接异常类,如下所示

  

已知直接子类
  AuthFailureError,NetworkError,ParseError,ServerError,TimeoutError

     

已知的间接子类
  NoConnectionError

使用instanceOf

检查特定错误
if(error instanceof TimeOutError)
   *show timeout error occured*
else if(error instanceof ServerError)
   *show server error occured*
same for others 
  

我尝试过不同的凌空错误方法,例如error.networkResponse

是的,这也很好地阅读错误响应,你可以确定服务器端到底发生了什么。 (服务器端发生错误时服务器必须返回错误响应) 别忘了阅读 error.networkResponse.statusCode也是。

要获取有关此次访问的更多信息Java doc VolleyError

<强>已更新
在本地机器服务器上工作时:要记住的事情

  1. 始终使用系统IP地址(而不是localhost)
  2. 确保本地路径正确。
  3. 始终在浏览器上测试 API /网址或查看Postman并转到Android项目。 在使用这些东西进行测试时,您可以解决许多服务器错误。

答案 1 :(得分:2)

经过多次尝试失败后,在巴拉特的帮助下,我找到了问题所在。

我在volley命令中使用了错误的IP地址。我没有使用通过在命令行中键入ifconfig找到的机器IP地址。添加正确的IP地址是解决方案。

警告其他人遇到同样问题,请使用ifcong查找IP地址,而不是Google搜索Whats my IP,因为这不会返回机器的IP地址。