Как исправить «com.android.Volley.TimeoutError» в Android при попытке выполнить действия регистрации - PullRequest
0 голосов
/ 11 июля 2019

Я использую wamp-сервер в качестве локального хоста, и у меня есть приложение, которое я хочу записывать при регистрации пользователя. Несмотря на это, приложение отлично работает на моем мобильном телефоне, но когда я заполняю текст редактирования и нажимаю кнопку регистрации, я получаю эту ошибку «Ошибка регистрацииcom.android.Volley.TimeoutError».

Я попытался проверить наличие ошибок в logcat, но не нашел ни одного. Любой, кто хорош в программировании на Android (Java), может помочь мне решить эту проблему. Вот мой код компоновки и код класса Java. Заранее спасибо

My Layout Code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:paddingTop="60dp"
android:background="@color/colorPrimaryDark2"
tools:context=".RegisterActivity">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:contentDescription="@string/todo"
    android:src="@drawable/ic_lock_outline_white" />

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autofillHints=""
        android:hint="@string/name"
        android:inputType="textPersonName"
        android:textColor="@color/ColorText"
        tools:targetApi="o" />

</com.google.android.material.textfield.TextInputLayout>

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/constituency"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autofillHints=""
        android:hint="@string/county"
        android:inputType="textPersonName"
        android:textColor="@color/ColorText"
        tools:targetApi="o" />

</com.google.android.material.textfield.TextInputLayout>

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autofillHints=""
        android:hint="@string/email"
        android:inputType="textEmailAddress"
        android:textColor="@color/ColorText"
        tools:targetApi="o" />

</com.google.android.material.textfield.TextInputLayout>

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true">

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autofillHints=""
        android:hint="@string/password"
        android:inputType="textPassword"
        android:textColor="@color/C2olorText"
        tools:targetApi="o" />

</com.google.android.material.textfield.TextInputLayout>

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true">

    <EditText
        android:id="@+id/c_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autofillHints=""
        android:hint="@string/confirm_password"
        android:inputType="textPassword"
        android:textColor="@color/ColorText"
        tools:targetApi="o" />
enter code here
</com.google.android.material.textfield.TextInputLayout>

<ProgressBar
    android:id="@+id/loading"
    android:layout_marginTop="30dp"
    android:visibility="gone"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<Button
    android:id="@+id/btn_regist"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:layout_marginTop="30dp"
    android:text="@string/register"
    android:backgroundTint="@color/colorPrimary"
    android:textColor="@android:color/white"
    tools:targetApi="lollipop" />

The Java class code

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class RegisterActivity extends AppCompatActivity {
private EditText name, constituency, email, password, c_password;
private Button btn_regist;
private ProgressBar loading;
private static String URL_REGIST = "http://192.168.0.115/kpp/register.php";

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

    loading = findViewById(R.id.loading);
    name = findViewById(R.id.name);
    constituency = findViewById(R.id.constituency);
    email = findViewById(R.id.email);
    password = findViewById(R.id.password);
    c_password = findViewById(R.id.c_password);
    btn_regist = findViewById(R.id.btn_regist);

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

}
private void Regist(){
    loading.setVisibility(View.VISIBLE);
    btn_regist.setVisibility(View.GONE);

    final String name = this.name.getText().toString().trim();
    final String constituency =     this.constituency.getText().toString().trim();
    final String email = this.email.getText().toString().trim();
    final String password = this.password.getText().toString().trim();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
        try{
            JSONObject jsonObject = new JSONObject(response);
            String success = jsonObject.getString("success");

            if(success.equals("1")){
                Toast.makeText(RegisterActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(RegisterActivity.this, "Registration Error" + e.toString(), Toast.LENGTH_SHORT).show();
            loading.setVisibility(View.GONE);
            btn_regist.setVisibility(View.VISIBLE);
        }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(RegisterActivity.this, "Registration Error" + error.toString(), Toast.LENGTH_SHORT).show();
                    loading.setVisibility(View.GONE);
                    btn_regist.setVisibility(View.VISIBLE);
                }
            })
    {
        @Override
        protected Map<String, String> getParams() throws    AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("name",name);
            params.put("constituency",constituency);
            params.put("email",email);
            params.put("password",password);
            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}`enter code here`

}

Я ожидаю, что после успешной регистрации, вы уведомите пользователя «Регистрация успешна!» ...

1 Ответ

0 голосов
/ 11 июля 2019

В вашем запросе задайте политику повторов:

public static int TIMEOUT_MS=10000        //10 seconds

     myRequest.setRetryPolicy(new DefaultRetryPolicy(
                TIMEOUT_MS, 
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Здесь с переменной TIMEOUT_MS вы можете указать время ожидания в миллисекундах.

...