0

I've been trying some code in this link here. It is in the part how to connect android to python with flask. The code running well in the server. When i try to run the android application, it work well untill when i click the "connect to server" button, the result is always failed to connect. There are no error in the android studio

layout application

This is the python code

import flask

app = flask.Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def handle_request():
    return "Flask Server & Android are Working Successfully"

app.run(host="0.0.0.0", port=5000, debug=True)

This is the terminal in the python code.

 * Serving Flask app "flaskcoba1" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 189-748-501
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

I tried to do test connection using ping from cmd to my mobile device to check the connection, and it's connect.

This is the main.activity

package com.example.flaskcoba;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {

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

    public void connectServer(View v){
        EditText ipv4AddressView = findViewById(R.id.IPAddress);
        String ipv4Address = ipv4AddressView.getText().toString();
        EditText portNumberView = findViewById(R.id.portNumber);
        String portNumber = portNumberView.getText().toString();

        String postUrl= "http://"+ipv4Address+":"+portNumber+"/";

        String postBodyText="Hello";
        MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
        RequestBody postBody = RequestBody.create(mediaType, postBodyText);

        postRequest(postUrl, postBody);
    }

    public void postRequest(String postUrl, RequestBody postBody) {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(postUrl)
                .post(postBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // Cancel the post on failure.
                call.cancel();

                // In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView responseText = findViewById(R.id.responseText);
                        responseText.setText("Failed to Connect to Server");
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                // In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView responseText = findViewById(R.id.responseText);
                        try {
                            responseText.setText(response.body().string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

}

This is the 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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="IPv4 Address" />
        <EditText
            android:layout_weight="4"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/IPAddress"
            android:text="192.168.1.7" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Port Number" />
        <EditText
            android:layout_weight="4"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/portNumber"
            android:text="5000"/>
    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Connect to Server"
        android:onClick="connectServer"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Message from the Server ..."
        android:id="@+id/responseText" />



</LinearLayout>

Finally find the error inthe logcat

2020-06-29 13:28:46.182 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute *filter
    -nvx -L tetherctrl_counters
    COMMIT
2020-06-29 13:28:46.186 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute done, res : 0
2020-06-29 13:28:46.186 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute *filter
    -nvx -L tetherctrl_counters
    COMMIT
2020-06-29 13:28:46.190 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute done, res : 0
2020-06-29 13:28:57.283 3287-3768/? E/Watchdog: !@Sync 718 [2020-06-29 13:28:57.283] FD count : 517
2020-06-29 13:31:46.659 3645-4181/? E/ImsAdaptorImpl: setSSACInfo : ImsAdaptorImpl.
2020-06-29 13:31:46.661 3889-4332/? E/EPDG -- SIM0 [RILRECEIVER]: Incorrect EpdgIilIpcMessage IPC Message -- not initialized
2020-06-29 13:31:46.663 3645-4181/? E/ImsAdaptorImpl: setSSACInfo : ImsAdaptorImpl.
2020-06-29 13:31:46.664 3889-4332/? E/EPDG -- SIM0 [RILRECEIVER]: Incorrect EpdgIilIpcMessage IPC Message -- not initialized
2020-06-29 13:31:46.670 3889-4332/? E/EPDG -- SIM0 [RILRECEIVER]: RX [NET_REGIST] -- RESPONSE -- not initialized

Please help me to fix the error

  • We cannot see wich ip address the client uses. – blackapps Jun 25 '20 at 08:38
  • `host="127.0.0.1"` I would not bind that to localhost. Try local lan ip instead. Or maybe 0.0.0.0 opens for all. – blackapps Jun 25 '20 at 08:40
  • Think you do not need runOnUiThread() in onFailure() and onResponse(). – blackapps Jun 25 '20 at 08:42
  • check this answer (https://stackoverflow.com/a/62535200/12368419) it may be useful – cizario Jun 25 '20 at 09:44
  • The client uses the ip address of the server, it is inputted in the android application. I've tried using host="0.0.0.0" before, but when i check on the browser it said "site can't be reached". Therefore i used host="127.0.0.1" @blackapps – Atna Diafahma Jun 25 '20 at 13:05
  • Which browser did you try? On that pc? Use a browser on the Android device. Did you try the local ip of the server? I suggested that before but you are not reacting. – blackapps Jun 25 '20 at 13:16
  • I'm sorry, i think i'm missunderstand abt that. I've try use 0.0.0.0 in the server, access with local ip adress of the server and it works in the android brwoser, thankyou. But it still not work in android application @blackapps – Atna Diafahma Jun 26 '20 at 04:59

3 Answers3

0

Change this line:

app.run(host="0.0.0.0", port=5000, debug=True)

This should be the accepted answer. For more info why 0.0.0.0 works and localhost or 127.0.0.1 doesn't work - check this answer

Relevant bit:

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

DarkSector
  • 13
  • 4
Balaji Ambresh
  • 4,977
  • 2
  • 5
  • 17
  • I've tried using host="0.0.0.0" before, but when i check on the browser it said "site can't be reached". I don't know why. Therefore i used host="127.0.0.1" – Atna Diafahma Jun 25 '20 at 14:30
  • @AtnaDiafahma Are you using the browser on your physical android device to reach your desktop flask application on `http://0.0.0.0/`? – Balaji Ambresh Jun 25 '20 at 15:15
  • I get it and sorry, i think i'm missunderstand abt that too. I've try again using 0.0.0.0 in the server, access with local ip adress of the server and it works in the android browser, thankyou. But it still not work in the android application – Atna Diafahma Jun 26 '20 at 05:00
  • Have you seen this [post](https://stackoverflow.com/questions/5806220/how-to-connect-to-my-http-localhost-web-server-from-android-emulator) ? – Balaji Ambresh Jun 26 '20 at 05:39
  • I think that way is for android emulator, whereas i use physical Android device – Atna Diafahma Jun 26 '20 at 09:07
  • If you're using a physical android device, what address do specify for the flask instance? See this [post](https://stackoverflow.com/questions/4779963/how-can-i-access-my-localhost-from-my-android-device) as well. – Balaji Ambresh Jun 26 '20 at 11:39
0

I see nothing wrong with your code so im going to assume your are putting in the wrong IP address . If youre on windows type wifi settings in search

enter image description here

similar steps apply to linux

Input the Ipv4 address you find there and also make sure in You allow remote connections in your flask app something similar to app.run(host='0.0.0.0')

alvinMemphis
  • 185
  • 2
  • 14
  • I put the right ip address. When i access in my android browser, it works. But when i access on my android application it said "failed to connect" – Atna Diafahma Jun 26 '20 at 09:11
0

After hours of trying I thought of switching ports, which then did the trick for me. I used port = 4985. I had the same problem, everything worked fine in my Computers and the androids browser, but not in the app.

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 03 '23 at 06:55