I am new to Android and having networking issues with an application that I'm making. When I make a request to Android (return client.recognize(new RecognitionRequest(jpeg)).get(0);
) in the doInBackground
of AsyncTask. However, I am getting the error:
com.clarifai.api.exception.ClarifaiThrottledException: TOO MANY REQUESTS.
I assume it is because I am calling client.recognize(new RecognitionRequest(jpeg)).get(0);
in the doInBackground
but when I move it out of the AsyncTask it gives me "Too much work on MainThread".
I'm not sure how to resolve this issue and any help would be appreciated. Thanks!
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri selectedImageUri = getImageUri(getApplicationContext(), photo);
String selectedImagePath = getPath(selectedImageUri);
String[] tags = new String[10];
RecognitionResult result = null;
try {
result = new ClarifaiTask().execute(photo).get();
} catch (ExecutionException ex) {
} catch (InterruptedException ex) {
}
;
if (result != null) {
if (result.getStatusCode() == RecognitionResult.StatusCode.OK) {
// Display the list of tags in the UI.
StringBuilder b = new StringBuilder();
int count = 0;
for (Tag tag : result.getTags()) {
if (count >= 10){
break;
}
tags[count++] = tag.getName();
System.out.println("TAG " + tag.getName());
}
}
}
}
}
private class ClarifaiTask extends AsyncTask<Bitmap, Void, RecognitionResult> {
@Override
protected RecognitionResult doInBackground(Bitmap... bitmaps) {
try {
// Scale down the image. This step is optional. However, sending large images over the
// network is slow and does not significantly improve recognition performance.
Bitmap scaled = Bitmap.createScaledBitmap(bitmaps[0], 320,
320 * bitmaps[0].getHeight() / bitmaps[0].getWidth(), true);
// Compress the image as a JPEG.
ByteArrayOutputStream out = new ByteArrayOutputStream();
scaled.compress(Bitmap.CompressFormat.JPEG, 90, out);
byte[] jpeg = out.toByteArray();
// Send the JPEG to Clarifai and return the result.
return client.recognize(new RecognitionRequest(jpeg)).get(0);
} catch (ClarifaiException e) {
Log.e(TAG, "Clarifai error", e);
return null;
}
}
}