I am using ML kit's on device translation API to translate a text.Although the translation is working perfectly fine but I am unable to display the translated text in my text view.I tried using setText method but nothing is being displayed in text view.Everything is being displayed in the logcat.
I am working in Android Studio
edit:
This shows the model being downloaded
TranslatorOptions options =
new TranslatorOptions.Builder()
.setSourceLanguage(TranslateLanguage.ENGLISH)
.setTargetLanguage(TranslateLanguage.BENGALI)
.build();
final Translator englishBengaliTranslator =
Translation.getClient(options);
//DOWNLOAD THE MODEL
DownloadConditions conditions = new DownloadConditions.Builder()
.requireWifi()
.build();
englishBengaliTranslator.downloadModelIfNeeded(conditions)
.addOnSuccessListener(
new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
}
//#Override
public void onSuccess(Void v) {
// Model downloaded successfully. Okay to start translating.
// (Set a flag, unhide the translation UI, etc.)
Toast.makeText(getApplicationContext(), "Model Downloaded.Translation will start ", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Model couldn’t be downloaded or other internal error.
// ...
Toast.makeText(getApplicationContext(), "Model could not be Downloaded. ", Toast.LENGTH_SHORT).show();
}
});
In this snippet of the code I have called the translate function (as the model is now downloaded)
englishBengaliTranslator.translate(stringResult)
.addOnSuccessListener(
new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
}
//#Override
public void onSuccess(#NonNull String translatedText1) {
textViewTranslatedText.setText(translatedText1);
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Error.
// ...
Toast.makeText(getApplicationContext(), "Text could not be translated. ", Toast.LENGTH_LONG).show();
}
});
I have used the setText function but still the translated text gets displayed in logcat and not in the textview(The translation works completely fine).How do I display it in my textView instead of logcat?Any leads would be helpful!
here is the image of logcat where translated text is displayed:enter image description here
Try this code,
englishBengaliTranslator.downloadModelIfNeeded(conditions)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// Model downloaded successfully. Okay to start translating.
// (Set a flag, unhide the translation UI, etc.)
Toast.makeText(getApplicationContext(), "Model Downloaded.Translation will start ", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Model couldn’t be downloaded or other internal error.
// ...
Toast.makeText(getApplicationContext(), "Model could not be Downloaded. ", Toast.LENGTH_SHORT).show();
}
});
The above code does nothing. I have just removed the unnecessary interface.
But the below code does something. I mean it specifies the return type.
englishBengaliTranslator.translate(stringResult)
.addOnSuccessListener(new OnSuccessListener<String>() {
#Override
public void onSuccess(String s) {
if(textViewTranslatedText!=null)
textViewTranslatedText.setText(translatedText1);
else
Log.d(TAG, "onSuccess: translation Done but text view null");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//Handle onFailure
}
});
Related
I'm trying to make a database of users with profile pictures(stored in storage) related to their IDs.
I'm using Firebase auth,Realtime database and Realime storage.
The code work like this : In user registration process, they choose username and picture. The database is filled with Users -> userUUid -> username and URL of picture stored.
The storage stores the picture.
If I keep such name of the table (Users) code works fine, however if I try to manipulate the tables, for example if I want to make more categories like Users -> SpecialUsers / NormalUsers -> userUUid -> ... the app just crashes.. I tried debugging but saw no errors.
Is there any way how to catch these Firebase exceptions (if there is any) or any explanation why if I change the structure of the tables, the code doesn't work ?
These is the method responsible for the registration :
(this one works)
public void signUp(String email,String password,String userName)
{
auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(task -> {
if (task.isSuccessful())
{
dbReference.child("Users").child(auth.getUid()).child("userName").setValue(userName);
//if user choose some picture
if(imageControl)
{
UUID randomID = UUID.randomUUID(); //create random UUID for the picture
final String imageName = "images/"+randomID+".jpg";
storageReference.child(imageName).putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
StorageReference myStorageRef = firebaseStorage.getReference(imageName);
myStorageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String filePath = uri.toString();
dbReference.child("Users").child(auth.getUid()).child("image").setValue(filePath).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RegistrationActivity.this, "Write to database is successful.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Write to database is not successful.", Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
}
else
{
dbReference.child("Users").child(auth.getUid()).child("image").setValue("null");
}
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(RegistrationActivity.this, "There is a problem.", Toast.LENGTH_SHORT).show();
}
});
}
This doesn't work :
(As you can see the only thing changed is the structure of the tables from only 'Users' to 'superUsers' -> 'anotherCategory')
public void signUp(String email,String password,String userName)
{
auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(task -> {
if (task.isSuccessful())
{
dbReference.child("superUsers").child('anotherCategory').child(auth.getUid()).child("userName").setValue(userName);
//if user choose some picture
if(imageControl)
{
UUID randomID = UUID.randomUUID(); //create random UUID for the picture
final String imageName = "images/"+randomID+".jpg";
storageReference.child(imageName).putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
StorageReference myStorageRef = firebaseStorage.getReference(imageName);
myStorageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String filePath = uri.toString();
dbReference.("superUsers").child('anotherCategory').child(auth.getUid()).child("image").setValue(filePath).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RegistrationActivity.this, "Write to database is successful.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Write to database is not successful.", Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
}
else
{
dbReference.("superUsers").child('anotherCategory').child(auth.getUid()).child("image").setValue("null");
}
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(RegistrationActivity.this, "There is a problem.", Toast.LENGTH_SHORT).show();
}
});
}
I suspect that the errors occurs somewhere after imageControl check.
In the second example of the code, the tables superUsers -> anotherCategory tables are created in the database, however the reference to the picture UUids is empty (not even null is placed)
What could be the error if nothing relevant to the process of storing pictures is changed ?
I wrote the following code that deletes two documents from the cloud Firebase database:
fireDB.document(groupPath).collection("users").document(phoneNumber).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
fireDB.collection("users").document(phoneNumber).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(this.getClass().getName(), "DocumentSnapshot successfully deleted");
Toast.makeText(getApplicationContext(),R.string.successfully_deleted_user,Toast.LENGTH_LONG).show();
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(this.getClass().getName(), "Error deleting document", e);
Toast.makeText(getApplicationContext(),R.string.failed_to_delete_user,Toast.LENGTH_LONG).show();
}
});
Log.d(this.getClass().getName(), "DocumentSnapshot successfully deleted");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(this.getClass().getName(), "Error deleting document", e);
Toast.makeText(getApplicationContext(),R.string.failed_to_delete_user,Toast.LENGTH_SHORT).show();
}
});
The problem with that code is that it deletes first document and then deletes second document, meaning if the first try will delete it successfully and the second one will fail to delete it, there is going to be a problem. Is it possible to delete two documents in Firebase cloud database so the result could be of of the following two options:
Both of the documents are deleted.
Both of the document are not deleted.
Is it possible to do?
As robsiemb commented, you'll want to use a batch write or transaction for this.
As far as I can see, the equivalent from your code would be something like this:
// Get a new write batch
WriteBatch batch = db.batch();
DocumentReference docRef1 = fireDB.document(groupPath).collection("users").document(phoneNumber);
DocumentReference docRef2 = fireDB.collection("users").document(phoneNumber)
DocumentReference laRef = db.collection("cities").document("LA");
batch.delete(docRef1);
batch.delete(docRef2);
// Commit the batch
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
I created a function to upload an image to AWS S3 bucket. The function is
called when a button is pressed. This works for first instance after a new
Gradle build. But when I try to call the function again, I get the following
error:
E/StorageQuickstart: The client issued a subsequent call to `Amplify.configure`
after the first had already succeeded.
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Upload to AWS S3
File imageFile = new File(imgFilePath);
uploadImage(imageFile.getName(), imgFilePath);
finish();
}
});
Function:
// AWS Amplify
private void uploadImage(String imageName, String imageAbsolutePath) {
// Amplify Initialize
AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {
#Override
public void onResult(UserStateDetails userStateDetails) {
try {
Amplify.addPlugin(new AWSS3StoragePlugin());
Amplify.configure(getApplicationContext());
Log.i("StorageQuickstart", "Amplify Initialized");
Amplify.Storage.uploadFile(
imageName,
imageAbsolutePath,
new ResultListener<StorageUploadFileResult>() {
#Override
public void onResult(StorageUploadFileResult result) {
Log.i("StorageQuickStart", "Successfully uploaded: " + result.getKey());
Log.i("ImageURL", getS3ObjectUrl(imageName));
}
#Override
public void onError(Throwable error) {
Log.e("StorageQuickstart", "Upload error.", error);
}
}
);
} catch (Exception e) {
Log.e("StorageQuickstart", e.getMessage());
}
}
#Override
public void onError(Exception e) {
Log.e("StorageQuickstart", "Initialization error.", e);
}
});
}
This is because AWSMobileClient.getInstance().initialize() method gets called, every time you click the button. Whereas initialization should be done only once. So, You can call AWSMobileClient.getInstance().initialize() method either in the Launcher Activity or you can use it in Application class as mentioned in the initialize Amplify section in the docs
I set up ML-Kit like AndroidExample and using on-device recognition mode.
It's working so well.
but
If we have a single character like 'A','5','K','9' it can't recognize anything! it only works for more than one length of string!
I need to recognize only one character.
What am I missing?!
This is my Function that gets a bitmap of an image and finds the texts from it.
private void RecognizeText(Bitmap bitmap) {
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
FirebaseVisionTextRecognizer detector = FirebaseVision.getInstance()
.getOnDeviceTextRecognizer();
Task<FirebaseVisionText> result =
detector.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
String s = firebaseVisionText.getText() + " | " + firebaseVisionText.getText().length();
Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
textView.setText(s);
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(Exception e) {
Log.d("EEEEEEEEVVVVVV", e.toString());
}
});
}
I try to delete a node from my FirebaseDatabase with removeValue() but it doesn't work .The strange thing is that when i delete it inside Recyclerview the node deleted successfully .
I pass the ref from Recyclerview with onclick in a new Activity using the code below .
final DatabaseReference itemRef = getRef(position);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// itemRef.removeValue();
Intent intentshowall2one= new Intent(Showcase.this, ShowProduct.class);
intentshowall2one.putExtra("S2Skey", itemRef.toString());
Showcase.this.startActivity(intentshowall2one);
and on the other activity
key = myIntent.getStringExtra("S2Skey");
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReferenceFromUrl(key);
mDatabase.removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getApplicationContext(), "deleted ", Toast.LENGTH_SHORT)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT)
.show();
}
});
Make sure you have given proper reference before you remove a value. then,
you can use Completion listener instead of OnSuccessListener, Completion listener gives accurate result.
Try this out in Your Button or any Listener :
mDatabase.child(key).removeValue();
Toast.makeText(getApplicationContext(),"The Post has been removed Successfully ",Toast.LENGTH_LONG).show();
Or use this
mDatabase.chlid(key).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getApplicationContext(), "deleted ", Toast.LENGTH_SHORT)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT)
.show();
}
});
Instead of :
mDatabase.removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getApplicationContext(), "deleted ", Toast.LENGTH_SHORT)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT)
.show();
}
});
Hope it works for You
Thanks for your answers Lutaaya Huzaifah Idris and Vignesh Kumar.I found out that the error was because i was using Greek words inside my path.Everything worked fine upload download and query the ref with Greek words but when i passing the ref to the other activity the ref changed .That is also strange.