I am trying to create a simple android app that comunicates with a Flask python server Here is the app code:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".MainActivity">
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java:
package com.example.flasktest2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url("http://127.0.0.1:5000/").build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
TextView textView = findViewById(R.id.textview);
textView.setText("network not found");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
TextView textView = findViewById(R.id.textview);
textView.setText(response.body().string());
}
});
}
}
Hello.py:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello Ani'
@app.route('/one')
def hello_one():
return 'Hello one'
@app.route('/two')
def hello_two():
return 'Hello two'
if __name__ == "__main__":
app.run(host = '0.0.0.0')
The server is working fine in my network. If I connect to my ipv4 adress followed by the port number 5000, like http://127.0.0.1:5000/ from my browser, or even from my phone's browser, "Hello Ani" appears on the screen, but my app doesn't seem to connect to the server and I can't figure out why.
I would really appreciate if you could help me solve this issue. Thanks !