The app that I Built connects to a local server which I have built in flask, But the python program takes time to execute and the client app closes the connection without taking the return statement and goes to the catch block and says Failed!!!. So what should I do to maintain the connection. I want to show a processing bar or
**
the server should notify the app when done with processing
** I guess I can even build another button to get the processed data (so I will need notification that the processing is completed) So what should I do. Can someone guide me in detail?Thanks.
enter code here''' `
import flask
import werkzeug
import time
from flask import flash
app = flask.Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def handle_request():
files_ids = list(flask.request.files)
print("\nNumber of Received Images : ", len(files_ids))
image_num = 1
for file_id in files_ids:
print("\nSaving Image ", str(image_num), "/", len(files_ids))
imagefile = flask.request.files[file_id]
filename = werkzeug.utils.secure_filename(imagefile.filename)
print("Image Filename : " + imagefile.filename)
timestr = time.strftime("%Y%m%d-%H%M%S")
imagefile.save(timestr + '_' + filename)
image_num = image_num + 1
print("\n")
// flash("Connected")
return "Image(s) Uploaded Successfully. Come Back Soon."
app.run(host="0.0.0.0", port=5000, debug=True)
''' This is the flask code which accepts the incoming connection.
public void connectServer(View v) {
TextView responseText = findViewById(R.id.responseText);
if (imagesSelected == false) { // This means no image is selected and thus nothing to upload.
responseText.setText("No Image Selected to Upload. Select Image(s) and Try Again.");
return;
}
responseText.setText("Sending the Files. Please Wait ...");
EditText ipv4AddressView = findViewById(R.id.IPAddress);
String ipv4Address = ipv4AddressView.getText().toString();
EditText portNumberView = findViewById(R.id.portNumber);
String portNumber = portNumberView.getText().toString();
Matcher matcher = IP_ADDRESS.matcher(ipv4Address);
if (!matcher.matches()) {
responseText.setText("Invalid IPv4 Address. Please Check Your Inputs.");
return;
}
String postUrl = "http://" + ipv4Address + ":" + portNumber + "/";
MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (int i = 0; i < selectedImagesPaths.size(); i++) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
// Read BitMap by file path.
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagesPaths.get(i), options);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
}catch(Exception e){
responseText.setText("Please Make Sure the Selected File is an Image.");
return;
}
byte[] byteArray = stream.toByteArray();
multipartBodyBuilder.addFormDataPart("image" + i, "Android_Flask_" + i + ".jpg", RequestBody.create(MediaType.parse("image/*jpg"), byteArray));
}
RequestBody postBodyImage = multipartBodyBuilder.build();
postRequest(postUrl, postBodyImage);
}
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();
Log.d("FAIL", e.getMessage());
// 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. Please Try Again.");
}
});
}
@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("Server's Response\n" + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
''' And This is my android studio connect server code
For getting the image from server to your app use
Picasso.get()
.load("*The link of your server*")
.into(imageView);