How to Build a Simple Android App with Flask Backend? - GeeksforGeeks

27 Oct, 2021
Flask is an API of Python that allows us to build up web applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries that helps the developer to write applications without writing the low-level codes such as protocols, thread management, etc. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. The following article will demonstrate how to use Flask for the backend while developing an Android Application. 
Step1: Installing Flask
Open the terminal and enter the following command to install the flask
pip install flask
Step 2: Add OkHttp Dependencies to the build.gradle file
OkHttp is a library developed by Square for sending and receiving HTTP-based network requests. For making HTTP requests in the Android Application we make use of OkHttp. This library is used to make both Synchronous and Asynchronous calls. If a network call is synchronous, the code will wait till we get a response from the server we are trying to communicate with. This may give rise to latency or performance lag. If a network call is asynchronous, the execution won’t wait till the server responds, the application will be running, and if the server responds a callback will be executed.
Android Dependencies
Add the following dependencies to the build.gradle file in Android Studio
implementation("com.squareup.okhttp3:okhttp:4.9.0")
Step 3: Working with the AndroidManifest.XML file
Add the following line above <application> tag
<uses-permission android:name="android.permission.INTERNET"/>
Add the following line inside the <application> tag
android:usesCleartextTraffic="true">
Step 4: Python Script
@app.route(“/”) is associated with showHomePage() function. Suppose the server is running on a system with IP address 192.168.0.113 and port number 5000. Now, if the URL “http://192.168.0.113:5000/” is entered into a browser, showHomePage function will be executed and it will return a response “This is home page”.
app.run() will host the server on localhost, whereas, app.run(host=”0.0.0.0′′) will host the server on machine’s IP address
By default port 5000 will be used, we can change it using ‘port’ parameter in app.run()
Python
from flask import Flask # Flask Constructorapp = Flask(__name__) # decorator to associate# a function with the url@app.route("/")def showHomePage():      # response from the server    return "This is home page" if __name__ == "__main__":  app.run(host="0.0.0.0")
  
Running The Python Script
 
run the python script and the server will be hosted.
 
 
Step 5: Working with the activity_main.xml file
 
Create a ConstraintLayout.
Add a TextView with ID ‘pagename’ to the Constraint Layout for displaying responses from the server
So, add the following code to the activity_main.xml file in android studio.
 
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"    android:background="@color/white"    tools:context=".MainActivity">     <TextView        android:id="@+id/pagename"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_marginStart="12dp"        android:layout_marginEnd="12dp"        android:textAlignment="center"        android:textColor="@color/black"        android:textSize="16sp"        android:textStyle="bold"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent" />     </androidx.constraintlayout.widget.ConstraintLayout>
  
Step 6: Working with the MainActivity.java file
 
Go to the MainActivity.java file and refer to the following code. Firstly, we need an OkHttp Client to make a request
 
OkHttpClient okhttpclient = new OkHttpClient();
 
Next, create a request with the URL of the server. In our case, it is “http://192.168.0.113:5000/”. Notice ‘/’ at the end of URL, we are sending a request for the homepage.
 
Request request = new Request.Builder().url("http://192.168.0.113:5000/").build();
 
Now, make a call with the above-made request. The complete code is given below. onFailure() will be called if the server is down or unreachable, so we display a text in TextView saying ‘server down’. onResponse() will be called if the request is made successfully. We can access the response with the Response parameter we receive in onResponse()
 
// to access the response we get from the server
response.body().string; 
 
Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
 
Java
import android.os.Bundle;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; 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 {         // declare attribute for textview    private TextView pagenameTextView;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        pagenameTextView = findViewById(R.id.pagename);         // creating a client        OkHttpClient okHttpClient = new OkHttpClient();         // building a request        Request request = new Request.Builder().url("http://192.168.0.113:5000/").build();         // making call asynchronously        okHttpClient.newCall(request).enqueue(new Callback() {            @Override            // called if server is unreachable            public void onFailure(@NotNull Call call, @NotNull IOException e) {                runOnUiThread(new Runnable() {                    @Override                    public void run() {                        Toast.makeText(MainActivity.this, "server down", Toast.LENGTH_SHORT).show();                        pagenameTextView.setText("error connecting to the server");                    }                });            }             @Override            // called if we get a            // response from the server            public void onResponse(                    @NotNull Call call,                    @NotNull Response response)                    throws IOException {pagenameTextView.setText(response.body().string());            }        });    }}
  
Note:
Make sure the Android Application runs on a device that is connected to the same network as the system which hosted the server. (if the flask server is running on a machine that is connected to ‘ABC’ WIFI, we need to connect our android device to the same ‘ABC’ network)
If the Application is failing to connect to the server, make sure your firewall allows connections on port 5000. If not, create an inbound rule in firewall advanced settings.
 
Output:
 
Android App running
 
Step 7: Checking Requests Made in Python Editor
 
If a request is made, we can see the IP address of the device making the request, the time at which the request was made, and the request type(in our case the request type is GET).
 
 
We can use okhttp client to send data over the server. Add the following line to the import statements
 
from flask import request
 
We need to set the method of a route as POST. Let’s add a method and associate a route to it. The method prints the text we entered in the android application to the console in pycharm. Add the following lines after the showHomePage() method.
 
@app.route("/debug", methods=["POST"])
def debug():
    text = request.form["sample"]
    print(text)
    return "received"
 
The complete script is given below
 
Python
from flask import Flask # import requestfrom flask import requestapp = Flask(__name__) @app.route("/")def showHomePage():    return "This is home page" @app.route("/debug", methods=["POST"])def debug():    text = request.form["sample"]    print(text)    return "received"    if __name__ == "__main__":  app.run(host="0.0.0.0")
  
Create a DummyActivity.java in Android Studio. This activity will be started once we get a response from the server from the showHomePage() method. Add the following lines in onResponse() callback in MainActivity.java.
 
Intent intent = new Intent(MainActivity.this, DummyActivity.class);
startActivity(intent);
finish();
 
Step 1: Working with the activity_dummy.xml file
 
Add an EditText with id dummy_text.
Add a Button with id dummy_send and with the text “send”.
 
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"    android:background="@color/white"    tools:context=".DummyActivity">     <EditText        android:id="@+id/dummy_text"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginStart="12dp"        android:layout_marginEnd="12dp"        android:backgroundTint="@color/black"        android:hint="enter any text"        android:textColor="@color/black"        android:textColorHint="#80000000"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent" />     <Button        android:id="@+id/dummy_send"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Send"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toBottomOf="@+id/dummy_text"        app:layout_constraintVertical_bias="0.1" /> </androidx.constraintlayout.widget.ConstraintLayout>
  
Step 2: Working with the DummyActivity.java file
 
We use a form to send the data using the OkHTTP client.
We pass this form as a parameter to post() while building our request.
Add an onClickListener() to make a POST request.
If the data is sent, and we get a response, we display a toast confirming that the data has been received.
 
Below is the code for the DummyActivity.java file. Comments are added inside the code to understand the code in more detail.
 
Java
import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import org.jetbrains.annotations.NotNull; import java.io.IOException; import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response; public class DummyActivity extends AppCompatActivity {     private EditText editText;    private Button button;    private OkHttpClient okHttpClient;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_dummy);        editText = findViewById(R.id.dummy_text);        button = findViewById(R.id.dummy_send);        okHttpClient = new OkHttpClient();         button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                                 String dummyText = editText.getText().toString();                 // we add the information we want to send in                // a form. each string we want to send should                // have a name. in our case we sent the                // dummyText with a name 'sample'                RequestBody formbody                        = new FormBody.Builder()                        .add("sample", dummyText)                        .build();                 // while building request                // we give our form                // as a parameter to post()                Request request = new Request.Builder().url("http://192.168.0.113:5000/debug")                        .post(formbody)                        .build();                okHttpClient.newCall(request).enqueue(new Callback() {                    @Override                    public void onFailure(                            @NotNull Call call,                            @NotNull IOException e) {                        runOnUiThread(new Runnable() {                            @Override                            public void run() {                                Toast.makeText(getApplicationContext(), "server down", Toast.LENGTH_SHORT).show();                            }                        });                    }                     @Override                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {                        if (response.body().string().equals("received")) {                            runOnUiThread(new Runnable() {                                @Override                                public void run() {                                    Toast.makeText(getApplicationContext(), "data received", Toast.LENGTH_SHORT).show();                                }                            });                        }                    }                });            }        });    }}
  
Output:
 
 
Checking Flask Console
 
Here we can see the android application made a POST request. we can even see the data we send over the server
 
 
anikakapoor
Android
Java
Python
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Flexbox-Layout in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Stream In Java