Android Volley onErrorResponse not giving error

China☆狼群 提交于 2019-12-22 14:58:34

问题


I am trying to use volley for my user login and registration but have encountered a problem when trying to login or register. The server I am trying to connect to is on my localhost and it is turned on and working, I am able to access it from other applications.

When I enter in the credentials for login/register and press the button I get a log saying that the error message is null. The issue is that the application doesnt crash and the log cat doesnt point to any lines causing the error, so I have no idea really whats going wrong.

I have tried the different volley error methods like error.networkResponseand a few other to try get more information but none return any information.

I have looked at other solutions on the site to people experiencing similar problems but nothing seems to work.

Can anyone explain to me why I am getting this error?

Log cat log

Login Error: null

Class printing the log - 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 Class

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

Manifest

<?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>

Log Cat when trying to register, (Same result for login attempts)

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

Log Cat Print Stack

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

回答1:


getMessage() can be null sometimes. This is how I read volley onErrorResponse(), volley has direct/sub direct exception classes as follows

Known Direct Subclasses
AuthFailureError, NetworkError, ParseError, ServerError, TimeoutError

Known Indirect Subclasses
NoConnectionError

check particular error using instanceOf

if(error instanceof TimeOutError)
   *show timeout error occured*
else if(error instanceof ServerError)
   *show server error occured*
same for others 

I have tried the different volley error methods like error.networkResponse

Yes this is good to read error response also, well you can be sure that what exactly happened at server end. (server must return error response when error occurred on server side) Do not forget to read error.networkResponse.statusCode also.

To get more info on this visit Java doc VolleyError

UPDATED
While working on local machine server : things to keep in mind

  1. Always use System IP Address (instead of localhost)
  2. Make sure local path is correct.
  3. Always test API/urls on browser or check with Postman and move to Android Project. while testing with these things you solve many server errors.



回答2:


After many different failed attempts and with the help of bharat, I have found the issue to the problem.

I was using the wrong IP address in the volley commands. I wasnt using the machines IP address which is found by typing ifconfig into the command line. Adding the correct IP address was the solution.

So warning to anyone else with the same problem, use ifcong to find the IP address and not a Google search for Whats my IP as this will not return the machines IP address.



来源:https://stackoverflow.com/questions/35561957/android-volley-onerrorresponse-not-giving-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!