João Costa
João Costa

Reputation: 33

com.android.volley.NoConnectionError: java.net.ConnectException: Connection refused

I need some help. This is my activity login, and when login button has been clicked he give me an error: com.android.volley.NoConnectionError:java.net.ConnectException:Connection refused. I use 2 permissions

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

There is my login code, at the top we have the variables:

private EditText mPasswordView, mUserName;
    private ProgressBar loading;
    private Button btnLogin;
    private static String URL_LOGIN = "http://localhost/ligacao_bd/login.php";
    private View mProgressView;
    private View mLoginFormView;

There is my button login setup:

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

    loading = findViewById(R.id.loading);


    // Set up the login form.
    mUserName = (EditText) findViewById(R.id.textUserName);
    mPasswordView = (EditText) findViewById(R.id.textPassword);
    btnLogin = (Button) findViewById(R.id.btnLogin); // login button

    btnLogin.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            String email = mUserName.getText().toString().trim();
            String Pwd = mPasswordView.getText().toString().trim();
            if(!email.isEmpty() || !Pwd.isEmpty()){
                Login(email, Pwd);
            }else{
               mUserName.setError("Insira nome de utilizador");
               mPasswordView.setError("Insira palavra-passe");
            }
        }
    });

And there is my Login function with JSON include:

 private void Login(final String email, final String password) {

    loading.setVisibility(View.VISIBLE);
    btnLogin.setVisibility(View.GONE);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                   try {
                       JSONObject jsonObject = new JSONObject(response);
                       String success = jsonObject.getString("Sucesso");
                       JSONArray jsonArray = jsonObject.getJSONArray("login");

                       if(success.equals("1")) {

                            for (int i = 0; i < jsonArray.length(); i++){

                                JSONObject object = jsonArray.getJSONObject(i);

                                String nome = object.getString("nome").trim();
                                String email = object.getString("email").trim();

                                Toast.makeText(LoginActivity.this, "Login efetuado com sucesso\n Bem-Vindo " +nome, Toast.LENGTH_SHORT).show();

                                loading.setVisibility(View.GONE);
                            }
                       }


                   }catch (JSONException e){
                       e.printStackTrace();
                       loading.setVisibility(View.GONE);
                       btnLogin.setVisibility(View.VISIBLE);
                       Toast.makeText(LoginActivity.this, "Erro " + e.toString(), Toast.LENGTH_SHORT).show();

                   }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    loading.setVisibility(View.GONE);
                    btnLogin.setVisibility(View.VISIBLE);
                    Toast.makeText(LoginActivity.this, "Erro " + error.toString(), Toast.LENGTH_SHORT).show();
                }
            })
    {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("email", email);
            params.put("password", password);
            return params;
        }
    };

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

}

Upvotes: 3

Views: 12280

Answers (3)

Dylan
Dylan

Reputation: 454

This is a working string request using volley. Change this as you need. If it does not work, then the problem is on your login.php side

loginButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){
      @Override
      public void onResponse(String s) {
        if(s.equals("Logged In")){
          Intent intent = new Intent(Login.this, Home.class);
          startActivity(intent);
        }
        else{
          Toast.makeText(Login.this, "Incorrect Details", Toast.LENGTH_LONG).show();
        }
      }
    }, new Response.ErrorListener(){
      @Override
      public void onErrorResponse(VolleyError volleyError) {
        Toast.makeText(Login.this, "Some error occurred -> "+volleyError, Toast.LENGTH_LONG).show();;
      }
    }) {
      @Override
      protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("email", emailBox.getText().toString());
        parameters.put("password", passwordBox.getText().toString());
        return parameters;
      }
    };

    RequestQueue rQueue = Volley.newRequestQueue(Login.this);
    rQueue.add(request);
  }
});

Upvotes: 2

Dylan
Dylan

Reputation: 454

Assuming that you're running this code on an Android Emulator and that whatever backend service you're calling is running on localhost also, change your login address to:

//8080 being the port that localhost is assigned to - change it if needs be
private static String URL_LOGIN = "http://10.0.2.2:8080/ligacao_bd/login.php";

http://10.0.2.2:xxxx is the IP that is a special alias to your host loopback interface (127.0.0.1 on your dev machine)

Upvotes: 6

Marvin Klar
Marvin Klar

Reputation: 1917

you also need to request the permission in your code. See: https://developer.android.com/training/permissions/requesting

You only need to add this code, before making the web requests:

requestPermission(Manifest.permission.INTERNET, PERMISSION_INTERNET);
requestPermission(Manifest.permission.ACCESS_NETWORK_STATE, PERMISSION_ACCESS_NETWORK_STATE);

And somewhere else this code:

private static final int PERMISSION_INTERNET = 1;
private static final int PERMISSION_ACCESS_NETWORK_STATE = 2;

private void requestPermission(Manifest.permission permission, int requestId) {
    if (ContextCompat.checkSelfPermission(thisActivity,
        permission)
        != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{permission},
                requestId);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_INTERNET: {
            if (grantResults.length <= 0
                || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
requestPermission(Manifest.permission.INTERNET, PERMISSION_INTERNET);
            }
            return;
        }
        case PERMISSION_ACCESS_NETWORK_STATE: {
            if (grantResults.length <= 0
                || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
requestPermission(Manifest.permission.ACCESS_NETWORK_STATE, PERMISSION_ACCESS_NETWORK_STATE);
            }
            return;
        }
    }
}

Upvotes: 0

Related Questions