0

Recently I just built an android application using volley library. It works really fine in Genymotion emulator, but somehow when I try to run it on my phone (samsung galaxy s4 Api 21) everyhting changes.

Not even a single request was sent and volley only returns one error:

android.volley.TimeoutError.

Below is my manifest code and front page of my app. Feel free to comment and I'm still beginner, so need a big help for this one :)

<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();
    }
}
Right leg
  • 16,080
  • 7
  • 48
  • 81

2 Answers2

1

After i got headache fr some hours i finally found an answer. the fauit is on my string URL. the ip on that link is only for ethernet virtualbox host only. so i change to another ip address and adding the port number behind it. enter image description here

the idea is that i don't know that to use the web server i got to write the whole thing like IP:PortNumber. so i try i change the ip address on URL and viola.The Current app are able to return the value Thank you for Varundroid to spend his time to help me to solve this case.

0

There is good chances that request is taking longer than expected on device, try updating the Volley's retry policy -

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

Parameters -

**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).

Usually there are other apps on device that is consuming the network as well which adds up to network delay, where emulator might be serving only your app. Try the above solution and let me know if it works.

Varundroid
  • 9,135
  • 14
  • 63
  • 93
  • I have try the solution above but still not working, the response is nothing happen T_T – Andre Sumantri Dec 21 '16 at 00:58
  • That's interesting! Can you show me the code with the above solution? I have a feeling there could be some other issue. – Varundroid Dec 21 '16 at 01:04
  • Also can you try the following - `RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); queue.add(Login_Request); queue.start();` – Varundroid Dec 21 '16 at 01:05
  • I have edit my previous code adding with the previous solution. now i'm trying this one RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); queue.add(Login_Request); queue.start(); – Andre Sumantri Dec 21 '16 at 01:10
  • Still returning TimeoutError , anyway i have to change the ip base on my ipconfig, and somehow i change the property of the url string from private final, to final only and so on. I already turn off the firewall but no hope.T_T – Andre Sumantri Dec 21 '16 at 01:13
  • I noticed that you setting retry policy after adding the request to RequestQueue, you need to do it before the add method gets called. – Varundroid Dec 21 '16 at 02:03
  • `Login_Request.setRetryPolicy() – Varundroid Dec 21 '16 at 02:04
  • Still not moving an inch, and still response with timeoutError.I just recently read the guide in android developer, is it important to set up a network and cache? – Andre Sumantri Dec 21 '16 at 02:18
  • Your request should work fine, you don't need to set up a cache unless you want to cache the data or images. – Varundroid Dec 21 '16 at 02:29
  • I had another look at your code, seems like you are hosting backend on your local machine and as your emulator runs under the same machine, it isn't having any trouble connecting to the server but when your device try to connect, it might be getting timeout error due to some restriction like firewall or something. It would be good idea if you look into your backend and check if your firewall isn't blocking any requests. – Varundroid Dec 21 '16 at 02:34
  • Hmm i wonder what kind of an application using that. is that xampp do such thing? because what i launched is android studio, genymotion, and not long a wifi router. but now i have close the program, maybe it worth a try? – Andre Sumantri Dec 21 '16 at 02:39