263

I am working on an Android Studio project with several activities. I am currently trying to read the output from a Java Servlet on localhost but it seems to be crashing due to a socket permission.

I've made a new project, used the exact same code and worked perfectly. So I dont understand why is not willing to work on my project.

public class LoginActivity extends AppCompatActivity {


String apiUrl = "http://10.0.2.2:8080/ProyectService/Servlet?action=login";
EditText username;
EditText password;
AlertDialog dialog;
Usuario session;

@Override
public void onCreate(Bundle savedInstanceState) {
    // Inicializacion de ventana
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    getSupportActionBar().hide();

    // Inicializacion de componentes
    username = findViewById(R.id.username);
    password = findViewById(R.id.password);

    // Inicializacion de funcionalidad de botones
    Button button= (Button) findViewById(R.id.login);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            UserLoginTask mAuthTask = new UserLoginTask();
            mAuthTask.execute();
        }
    });

    password = findViewById(R.id.password);
    createAlertDialog("Usuario o Contraseña Incorrectos");
    }

    private void createAlertDialog(String message){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(message)
            .setTitle("Error");
    dialog = builder.create();
    }



    // ASYNCRONUS NETWORK PROCESS

    public class UserLoginTask extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
    }


    @Override
    protected String doInBackground(String... params) {

        // implement API in background and store the response in current variable
        String current = "";
        try {
            URL url;
            HttpURLConnection urlConnection = null;
            try {
                url = new URL(apiUrl);
                System.out.println(apiUrl);
                urlConnection = (HttpURLConnection) url
                        .openConnection();

                InputStream in = urlConnection.getInputStream();

                InputStreamReader isw = new InputStreamReader(in);

                int data = isw.read();
                while (data != -1) {
                    current += (char) data;
                    data = isw.read();
                    //System.out.print(current);

                }
                System.out.print(current);
                // return the data to onPostExecute method
                return current;

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "Exception: " + e.getMessage();
        }
        return current;
        }
    }

    protected void onPostExecute(String success) {
        Log.i(success, "");
       //attemptLogin();
    }
}

I Expect it to read the data but it crashes at this line:

InputStream in = urlConnection.getInputStream();

This is the error output:

java.net.SocketException: socket failed: EPERM (Operation not permitted)
at java.net.Socket.createImpl(Socket.java:492)
at java.net.Socket.getImpl(Socket.java:552)
at java.net.Socket.setSoTimeout(Socket.java:1180)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:248)
at com.example.controller.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:114)
at com.example.controller.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:93)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Zoe stands with Ukraine
  • 25,310
  • 18
  • 114
  • 149
Aaron Villalobos
  • 9,779
  • 3
  • 7
  • 9

14 Answers14

714

Solved: All I needed to do was to uninstall the app from the emulator or physical connected device and run it again.

Pooja
  • 396
  • 3
  • 13
Aaron Villalobos
  • 9,779
  • 3
  • 7
  • 9
  • 12
    it did work for me too, ever found why it was happening in the first place? – Vikas Pandey Jun 04 '19 at 13:18
  • 22
    In my case I had to provide ACCESS_NETWORK_STATE permission. Add to manifest. And uninstall too – sk md Jun 13 '19 at 12:46
  • 3
    Same here. It's odd that the question is so young. Maybe this is a bug. – user1511417 Jul 01 '19 at 11:43
  • java.net.ConnectException: Failed to connect to still not working – Fahad Bhuyian Jul 26 '19 at 21:42
  • @FahadBhuyian try to add permission to use INTERNET inside of `AndroidManifest.xml` file `````` right before the application tag. – Silambarasan R.D Aug 28 '19 at 07:23
  • 2
    Removed application from an emulator and install again solved my problem, thanks. Seems that firebase cache something to the filesystem and reuse it, I suppose clear application data also will solve a problem. – Onregs Sep 12 '19 at 08:47
  • 1
    Why does this happen in the first place thought? Anyone have a hint on what may be the cause of this? – Pedro Lopes Sep 20 '19 at 18:06
  • 4
    maybe permission are cached already and ruining it again and again is not updating permission and instead of updating src files only.? that's re-installation helped. – Atif AbbAsi Oct 09 '19 at 11:05
  • worked for me too. I've been suffering with this problem for DAYSSSSSS lol. oh silly android – Ben Akin Nov 01 '19 at 17:29
  • This worked, have had this problem for a few days now.. Thanks! – dnwjn Dec 08 '19 at 15:31
  • Great answer! You saved my time. Thanks – leeyang Sep 18 '20 at 01:42
  • It worked perfect, uninstall the app from the physical phone and then run again from Android Studio – Andy Luis Dec 03 '20 at 17:26
  • Uninstall and Re-install worked for me. But am providing an update to my existing app and so cannot just ask all my users to just uninstall and re-install the new version for my production release. Is there any way around if anyone has figure out yet? – Malay Shah Jan 28 '21 at 20:37
  • it did work for me too, uninstall my app and run on Android Studio 4.1.2 – Andy Luis May 18 '21 at 18:22
  • I was getting the same error trying to load image URLs with Glide using `` Uninstalling the app fixed it for me! – TecBrat Jun 09 '21 at 20:00
  • As a beginner, I've been around 3 days figuring out why my simple load image app not working, I've make sure permission added also add clearTextHttp as true in the manifest, little did I know I have to do this, we need better developer experience – Nald Dev Mar 18 '22 at 22:32
  • You should mark this as the answer. – lcj Mar 21 '22 at 22:44
86

Just uninstall the app from the emulator then run again and it’ll work. I had the same issue

To uninstall the app run your project when "the application had stopped" message appear click "app info" then uninstall.

Reid
  • 554
  • 1
  • 7
  • 22
John Alexander
  • 861
  • 4
  • 3
58

First of all you need change your android manifest .xml But after this action you must uninstall application and run it again. https://developer.android.com/training/basics/network-ops/connecting

and code here:

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

in AndroidManifest.xml

Archil Labadze
  • 3,361
  • 4
  • 24
  • 39
28

If you forgot to add <uses-permission android:name="android.permission.INTERNET" /> to your Manifest.xml, do it now

If you already added it but the error persists, uninstall the app first then run i again.
More often than not I run into the same issue because I forgot <uses-permission android:name="android.permission.INTERNET" /> in my first installation.
The OS thought the app doesn't need Internet permission (which is dumb IMO) and would not check any permission update to the app (which is even dumber IMO).

The only way to tell the Android OS to check your updated permission requests is to uninstall the app first before installing again.

I think neither

  • <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  • nor android:usesCleartextTraffic="true" really matters here
ericn
  • 11,596
  • 13
  • 72
  • 115
18

I had to uninstall the app from the emulator and then everything started to work. I just needed the folowing permission on the AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
Juan Cabello
  • 321
  • 3
  • 4
13
  1. Add ACCESS_NETWORK_STATE permission in manifest
  2. Reinstallation emulator
AK IJ
  • 409
  • 4
  • 8
10

I had the same issue in android emulator, even after adding

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

and

android:usesCleartextTraffic="true"

and reinstalling the app still had the issue on my emulator.

AVD Manager -> Right click -> Cold Boot now

solved my issue, looks like if we ran the app initially without adding internet permissions / clearTextTraffic we might need to cold boot as it store some cache.

Mazhar Ghulam
  • 131
  • 1
  • 9
6

Set android:usesCleartextTraffic="true" in the manifest file. Add the permission INTERNET. Uninstall app and then install again.

Gilbert
  • 1,591
  • 17
  • 23
5

Set android:usesCleartextTraffic="true" in the manifest file. Add the permission INTERNET. Uninstall app and then install again.its work to me

4

If you are using a localhost server on your Mac then use the local IP address that is assigned for your machine as your API address. i.e. 192.168.x.x (find it in Settings -> Network) not localhost nor 127.0.0.1.

As they mentioned above, uninstall the app and then put these tags in your manifest:

in the application section:

android:usesCleartextTraffic="true"

Then in your manifest section:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.a.myapp">
    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Mujtaba Mahmood
  • 749
  • 2
  • 6
  • 19
4

Working solution.

  1. check if you have INTERNET permission and ACCESS_NETWORK_STATE permission, if not add these.
  1. uninstall the app and install again. If not try in different device. It will work 100%. I face same issue and solved this by using these steps.
sudhanshu
  • 331
  • 1
  • 3
  • 10
0

If anyone still has this issue I encountered it when I used VPN and tried to connect to wifi while cellular was on. I was using Anyconnect VPN client. Solution is to enable the allow bypass that will let you bind a socket to a specific network if this is what you are looking for.

AnyConnect only uses allowBypass if it's configured in its managed restrictions (by EMM), via this key: vpn_connection_allow_bypass.

ovidiur
  • 308
  • 2
  • 9
0

I had to delete this

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

and keep this

android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET" />
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
khoane
  • 31
  • 1
  • 4
0

I am a little late to this but I encountered this problem and I found out that android:usesCleartextTraffic requires minimum API version of 23. Therefore, in the module gradle build file, switch the minimum version to 23 and it should work.

Dharman
  • 26,923
  • 21
  • 73
  • 125