简体   繁体   English

注册期间Volley Timeout错误

[英]Volley Timeout error during registration

I am trying to build a chat application using GCM. 我正在尝试使用GCM构建聊天应用程序。 I am using this for reference 我正在用它作为参考

http://www.androidhive.info/2016/02/android-push-notifications-using-gcm-php-mysql-realtime-chat-app-part-2/ http://www.androidhive.info/2016/02/android-push-notifications-using-gcm-php-mysql-realtime-chat-app-part-2/

The username and email id is not added in database. 用户名和电子邮件ID未添加到数据库中。 When I am using Postman it works well. 当我使用Postman时,效果很好。 During registration i am facing problem 在注册过程中我遇到了问题

This is my LoginActivity 这是我的LoginActivity

   public class LoginActivity extends AppCompatActivity {

private String TAG = LoginActivity.class.getSimpleName();
private EditText inputName, inputEmail;
private TextInputLayout inputLayoutName, inputLayoutEmail;
private Button btnEnter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /**
     * Check for login session. It user is already logged in
     * redirect him to main activity
     * */
    if (MyApplication.getInstance().getPrefManager().getUser() != null) {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    setContentView(R.layout.activity_login);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_name);
    inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email);
    inputName = (EditText) findViewById(R.id.input_name);
    inputEmail = (EditText) findViewById(R.id.input_email);
    btnEnter = (Button) findViewById(R.id.btn_enter);

    inputName.addTextChangedListener(new MyTextWatcher(inputName));
    inputEmail.addTextChangedListener(new MyTextWatcher(inputEmail));

    btnEnter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            login();
        }
    });
}

/**
 * logging in user. Will make http post request with name, email
 * as parameters
 */
private void login() {
    if (!validateName()) {
        return;
    }

    if (!validateEmail()) {
        return;
    }

    final String name = inputName.getText().toString();
    final String email = inputEmail.getText().toString();

    Log.e("endpoint loginb url",""+EndPoints.LOGIN);
    StringRequest strReq = new StringRequest(Request.Method.POST,
            EndPoints.LOGIN, new Response.Listener<String>() {



        @Override
        public void onResponse(String response) {
            Log.e(TAG, "response: " + response);

            try {
                JSONObject obj = new JSONObject(response);

                // check for error flag
                if (obj.getBoolean("error") == false) {
                    // user successfully logged in

                    JSONObject userObj = obj.getJSONObject("user");
                    User user = new User(userObj.getString("user_id"),
                            userObj.getString("name"),
                            userObj.getString("email"));

                    // storing user in shared preferences
                    MyApplication.getInstance().getPrefManager().storeUser(user);

                    // start main activity
                    startActivity(new Intent(getApplicationContext(), MainActivity.class));
                    finish();

                } else {
                    // login error - simply toast the message
                    Toast.makeText(getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
                }

            } catch (JSONException e) {
                Log.e(TAG, "json parsing error: " + e.getMessage());
                Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                Log.e("Timeout", "timeout");
            } else if (error instanceof AuthFailureError) {
                Log.e("AuthFailureError","AuthFailureError");

            } else if (error instanceof ServerError) {
                Log.e("ServerError","ServerError");
            } else if (error instanceof NetworkError) {
                Log.e("NetworkError","NetworkError");
            } else if (error instanceof ParseError) {
                Log.e("ParseError","ParseError");
            }
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("name", name);
            params.put("email", email);

            Log.e(TAG, "params: " + params.toString());
            return params;
        }
    };

    //Adding request to request queue
    MyApplication.getInstance().addToRequestQueue(strReq);
    strReq.setRetryPolicy(new RetryPolicy() {
        @Override
        public int getCurrentTimeout() {
            return 50000;
        }

        @Override
        public int getCurrentRetryCount() {
            return 50000;
        }

        @Override
        public void retry(VolleyError error) throws VolleyError {

        }
    });

}

private void requestFocus(View view) {
    if (view.requestFocus()) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}

// Validating name
private boolean validateName() {
    if (inputName.getText().toString().trim().isEmpty()) {
        inputLayoutName.setError(getString(R.string.err_msg_name));
        requestFocus(inputName);
        return false;
    } else {
        inputLayoutName.setErrorEnabled(false);
    }

    return true;
}

// Validating email
private boolean validateEmail() {
    String email = inputEmail.getText().toString().trim();

    if (email.isEmpty() || !isValidEmail(email)) {
        inputLayoutEmail.setError(getString(R.string.err_msg_email));
        requestFocus(inputEmail);
        return false;
    } else {
        inputLayoutEmail.setErrorEnabled(false);
    }

    return true;
}

private static boolean isValidEmail(String email) {
    return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

private class MyTextWatcher implements TextWatcher {

    private View view;
    private MyTextWatcher(View view) {
        this.view = view;
    }

    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    public void afterTextChanged(Editable editable) {
        switch (view.getId()) {
            case R.id.input_name:
                validateName();
                break;
            case R.id.input_email:
                validateEmail();
                break;
        }
    }
}
}

This is MyApplication.java 这是MyApplication.java

   public class MyApplication extends Application {

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

private RequestQueue mRequestQueue;

private static MyApplication mInstance;

private MyPreferenceManager pref;

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

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

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

    }

    return mRequestQueue;
}

public MyPreferenceManager getPrefManager() {
    if (pref == null) {
        pref = new MyPreferenceManager(this);
    }

    return pref;
}

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

public void logout() {
    pref.clear();
    Intent intent = new Intent(this, LoginActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
}

EDIT I used this but still not working. 编辑我用这个,但仍然无法正常工作。

   MyApplication.getInstance().addToRequestQueue(strReq);

    strReq.setRetryPolicy(new DefaultRetryPolicy(
            50000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    requestQueue.add(strReq);

In logged the error and i am getting TimeOutError. 在记录错误,我越来越TimeOutError。 Please help 请帮忙

Add following piece of code for your request. 根据您的请求添加以下代码。

        strReq.setRetryPolicy(new DefaultRetryPolicy(
            30*1000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(strReq);

Thank you for your answers. 谢谢您的回答。 I found out my mistake. 我发现了我的错误。 I was running it on localhost using IP address and application was running on device which has no netowrk connection with PC so the IP address were different. 我在使用IP地址的本地主机上运行它,而应用程序在与PC没有网络连接的设备上运行,因此IP地址不同。 so i was getting timeout error everytime. 所以我每次都收到超时错误。 Thanks 谢谢

Use this code snippet it will help me to solve the volley timeout error 使用此代码段将帮助我解决截击超时错误

 stringRequest.setRetryPolicy(new DefaultRetryPolicy(
            50000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    requestQueue.add(stringRequest);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM