【问题标题】:Android Volley Library Works on Genymotion Emulator But always return timeouterror on deviceAndroid Volley 库在 Genymotion 模拟器上工作但总是在设备上返回 timeouterror
【发布时间】:2016-12-21 00:21:50
【问题描述】:

最近我刚刚使用 volley 库构建了一个 android 应用程序。它在 Genymotion 模拟器中运行良好,但是当我尝试在我的手机(三星 Galaxy s4 Api 21)上运行它时,一切都发生了变化。

甚至没有发送一个请求,volley 只返回一个错误:

android.volley.TimeoutError.

下面是我的清单代码和我的应用程序的首页。随意评论,我还是初学者,所以需要一个很大的帮助:)

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.andre.edec">

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".Login">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!-- FRAGMENT CONTAINER-->
    <activity android:name=".Container" />
    <!-- CREATE REPORT-->
    <activity android:name=".Fragment.Report.Activity_Create_Report" />
    <!-- CREATE MATERIAL-->
    <activity android:name=".Fragment.Material.Activity_Create_Material">
    </activity>
    <!-- CREATE ANNOUNCEMENT-->
    <activity android:name=".Fragment.Announcement.Activity_Create_Announcement">
    </activity>
    <!-- REGISTER-->
    <activity
        android:name=".Register"
        android:label="Register User Info" />
</application>

public class Login extends AppCompatActivity {

private AppCompatButton Login_ACB_Login, Login_ACB_Forget_Password;
private TextInputLayout TIL_Login_Username, TIL_Login_Password;
private TextInputEditText TIE_Login_Username, TIE_Login_Password;
private String Login_URL = "http://192.168.56.1/EDEC/Login.php";//PHP MYSQL URL
private String ID, Status = null;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);//Login XML
    //Init Object
    TIE_Login_Username = (TextInputEditText)         findViewById(R.id.TextInputEditText_Login_Username);
    TIE_Login_Password = (TextInputEditText) findViewById(R.id.TextInputEditText_Login_Password);
    TIL_Login_Username = (TextInputLayout) findViewById(R.id.TextInputLayout_Login_Username);
    TIL_Login_Password = (TextInputLayout) findViewById(R.id.TextInputLayout_Login_Password);
    //Text_Watcher_Validation
    TIE_Login_Username.addTextChangedListener(new Login.TextWatcher_Validation(TIE_Login_Username));
    TIE_Login_Password.addTextChangedListener(new Login.TextWatcher_Validation(TIE_Login_Password));
    //Login
    Login_ACB_Login = (AppCompatButton)findViewById(R.id.AppCompatButton_Login_Button);
    Login_ACB_Login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Validate Input
            if(Submit_Data()){
                Login();
                //getDefaultSharedPreferences(getApplicationContext());
                /*SharedPreferences Preferences =    getSharedPreferences("Preference", MODE_PRIVATE);
                SharedPreferences.Editor Temp_Value = Preferences.edit();
                Temp_Value.putString("ID", ID);
                Temp_Value.putString("STATUS", Status);
                Temp_Value.apply();*/
                //Intent
                /*final Intent Move_to_Container = new Intent(Login.this, Container.class);
                Bundle Extra_Value = new Bundle();
                Extra_Value.putString("ID", ID);
                Extra_Value.putString("STATUS", Status);
                startActivity(Move_to_Container);
                finish();*/
            }

        }
    });
}
private class TextWatcher_Validation implements TextWatcher{
    private View view;

    private TextWatcher_Validation(View view) {
        this.view = view;
    }
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

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

    }

    @Override
    public void afterTextChanged(Editable editable) {
        switch (view.getId()) {
            case R.id.TextInputEditText_Login_Username:
                Validate_Username();
                break;
            case R.id.TextInputEditText_Login_Password:
                Validate_Password();
                break;
        }
    }
}
//Submit Data Check
private boolean Submit_Data() {
    if (!Validate_Username()) {
        return Validate_Username();
    }
    if (!Validate_Password()) {
        return Validate_Password();
    }
    return true;
}
//View Focus
private void RequestFocus(View view) {
    if (view.requestFocus()) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}
//Validate Username
private boolean Validate_Username() {
    final String Username = TIE_Login_Username.getText().toString();
    if (Username.length() == 0) {
        TIL_Login_Username.setError("Please Fill Username");
        RequestFocus(TIL_Login_Username);
        return false;
    } else if (Username.startsWith(" ", 0)) {
        TIL_Login_Username.setError("Username Must Not Start With Whitespace");
        RequestFocus(TIL_Login_Username);
        return false;
    } else {
        TIL_Login_Username.setErrorEnabled(false);
    }
    return true;
}
//Validate Password
private boolean Validate_Password() {
    final String Password = TIE_Login_Password.getText().toString();
    if (Password.length() == 0) {
        TIL_Login_Password.setError("Please Fill Password");
        RequestFocus(TIL_Login_Password);
        return false;
    } else if (Password.startsWith(" ", 0)) {
        TIL_Login_Password.setError("Password Must Not Start With Whitespace");
        RequestFocus(TIL_Login_Password);
        return false;
    } else {
        TIL_Login_Password.setErrorEnabled(false);
    }
    return true;
}
//Login
private void Login(){
    StringRequest Login_Request = new StringRequest(Request.Method.POST, Login_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            /*Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();*/
            if(response.contains("Failed")){
                Toast.makeText(getApplicationContext(), "Data Not Found", Toast.LENGTH_SHORT).show();
            }else{
                Show_Json(response);
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
        }
    }){
        @Override
        protected Map<String, String> getParams(){
            Map<String, String> String_Map = new HashMap<String, String>();
            String_Map.put("Username", TIE_Login_Username.getText().toString());
            String_Map.put("Password", TIE_Login_Password.getText().toString());
            return String_Map;
        }
    };
    Volley.newRequestQueue(getApplicationContext()).add(Login_Request);
   Changes in here-> Login_Request.setRetryPolicy(new DefaultRetryPolicy(100000 , DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
//ShowJsonArray
private void Show_Json(String Response){
    try {
        JSONObject Response_JSON = new JSONObject(Response);
        JSONArray Array_Result = Response_JSON.getJSONArray("Result");
        JSONObject Object_Getter = Array_Result.getJSONObject(0);
        ID = Object_Getter.getString("USER_ID");
        Status = Object_Getter.getString("STATUS");
        Toast.makeText(getApplicationContext(), ID + Status, Toast.LENGTH_SHORT).show();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

【问题讨论】:

    标签: android android-volley android-library android-networking


    【解决方案1】:

    在我头疼了几个小时后,我终于找到了答案。故障在我的字符串 URL 上。该链接上的 ip 仅适用于以太网 virtualbox 主机。所以我更改为另一个 IP 地址并在其后面添加端口号。 enter image description here

    我的想法是,我不知道要使用 Web 服务器,我必须编写整个内容,例如 IP:PortNumber。所以我尝试更改 URL 和 viola 上的 IP 地址。The Current app are able to return the value 感谢 Varundroid 花时间帮助我解决此案。

    【讨论】:

      【解决方案2】:

      请求在设备上花费的时间很可能比预期的要长,请尝试更新 Volley 的重试策略 -

      volleyRequestObject.setRetryPolicy(new DefaultRetryPolicy(
              CUSTOME_TIMEOUT, 
              DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
              DefaultRetryPolicy.DEFAULT_BACKOFF_MULTI));
      

      参数 -

      **CUSTOME_TIMEOUT** - Timeout in millis per every retry attempt.
      **DEFAULT_MAX_RETRIES** - Number of times retry is attempted (You can changes this number).
      **DEFAULT_BACKOFF_MULTI** - Multiplier that is used to determine the number of retry attempts(You can changes this as well).
      

      通常设备上还有其他应用程序也在消耗网络,这会增加网络延迟,其中模拟器可能只为您的应用程序提供服务。试试上面的解决方案,让我知道它是否有效。

      【讨论】:

      • 我已经尝试了上面的解决方案但仍然无法正常工作,响应没有发生T_T
      • 这很有趣!你能告诉我上述解决方案的代码吗?我感觉可能还有其他问题。
      • 你也可以试试下面的 - RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); queue.add(Login_Request); queue.start();
      • 我已经编辑了我之前的代码,添加了之前的解决方案。现在我正在尝试这个 RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); queue.add(Login_Request); queue.start();
      • 仍然返回 TimeoutError ,无论如何我必须根据我的 ipconfig 更改 ip 基础,并且不知何故我将 url 字符串的属性从私有 final 更改为 final 等等。我已经关闭了防火墙但没有希望。T_T
      猜你喜欢
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 2012-08-19
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多