QuartZ QuartZ - 1 month ago 14
Python Question

Android Volley doesn't seem to be able to connect to Flask localhost address for GET method for return String from Flask?

This is the Android Volley code :

// I already add the uses-permission for INTERNET to manifest
<uses-permission android:name="android.permission.INTERNET" />

// and add volley to gradle depedencies
compile 'com.android.volley:volley:1.0.0'


StringRequest stringRequest;
RequestQueue mRequestQueue;

String url = "http://localhost:5000/bacon"; // This is the localhost to FLask

RequestQueue queue = Volley.newRequestQueue(BaconActivity.this);
stringRequest = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(BaconActivity.this, response, Toast.LENGTH_SHORT).show();
redirectLinkToLogin();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(BaconActivity.this, "That didn't work!", Toast.LENGTH_SHORT).show();
}
}
);

queue.add(stringRequest);


This is the Flask code :

from flask import Flask, request


app = Flask(__name__)
@app.route('/bacon', methods=['GET', 'POST'])
def bacon():
if request.method == 'GET':
return 'You are probably using GET'
else:
return 'You are probably using POST'


if __name__ == "__main__":
app.run(debug=True, host='localhost')


When I run the app, my Volley didn't connect to my Flask (I already run the Flask before running the app). So instead of retrieving the return String, the code runs to the Response.ErrorListener everytime.

I'm trying to get the return String from Flask to the localhost, and Toast the return String.

Answer
String url = "http://localhost:5000/bacon"; // This is the localhost to FLask

Actually, no. That's the localhost to the running device. Whether that is the emulator, or your physical Android device.

You may also need Flask to run on host='0.0.0.0'

You need to use the actual IP of your computer running Flask. Android emulator uses 10.0.2.2, I believe