Related
I've been working on this code for weeks with no progress at all, even though it seems like such an easy fix!! Basically I am using TextToSpeech with SpeechRecognizer in order to have the app ask me a question and then listen for my answer. Here's my code... I'm thinking its a thread problem or something.
Basically when I hold down the button, SPeechRecognizer starts listening until i take away finger... this works fine.. but I programmatically want the SpeechRecognizer to start up again after Utterance is Completed or simulate a button press to get it to work but neither works...
public class MainActivity extends AppCompatActivity {
TextToSpeech textToSpeech;
// SpeechRecognizer
SpeechRecognizer mSpeechRecognizer;
Intent mSpeechRecognizerIntent;
// Speech Analysis Support
SpeechToTextAnalyzer speechToTextAnalyzer;
String speechToTextAnalyzerResponse;
String SPEECH_RESPONSE_BACK;
int buttonPressCounter;
boolean responsive;
TextView StatusDisplay, WordingDisplay;
Button SimulateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
buttonPressCounter = 0;
// Initialize TextToSpeech
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.CANADA);
}
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
// Speaking started.
}
#Override
public void onDone(String utteranceId) {
// Speaking stopped.
if(responsive){ // if(utteranceId == "LISTEN_FOR_NEW_RESPONSE")
// possible method one:
SimulateButton.performClick();
// possible method two:
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
// NOTE: SO FAR NEITHER OF THESE LINES MAKE THE SPEECHRECOGNIZER START UP WITHOUT ME TOUCHING THE BUTTON!!!
}
}
#Override
public void onError(String utteranceId) {
// There was an error.
}
});
}
});
// Initialize UI View Components
StatusDisplay = (TextView)findViewById(R.id.StatusUpdater);
WordingDisplay = (TextView)findViewById(R.id.WordsHeard);
// Create Reference to Classes
speechToTextAnalyzer = new SpeechToTextAnalyzer(this, this);
// Initialize SpeechRecognizer and Intent
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int errorCode) {
String errorMessage = getErrorText(errorCode);
//Log.d(LOG_TAG, "FAILED " + errorMessage);
//listeningOn = false; // UNSURE!!
}
// accompanying text for onError
public String getErrorText(int errorCode) {
String message;
switch (errorCode) {
case SpeechRecognizer.ERROR_AUDIO:
message = "Audio Recording Error";
break;
case SpeechRecognizer.ERROR_CLIENT:
message = "Client Side Error";
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
message = "Insufficient Permissions";
break;
case SpeechRecognizer.ERROR_NETWORK:
message = "Network Error";
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
message = "Network TimeOut";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
message = "No Match";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
message = "RecognitionService Busy";
break;
case SpeechRecognizer.ERROR_SERVER:
message = "Error From Server";
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
message = "No Speech Input";
break;
default:
message = "Couldn't Understand, Please Try Again";
break;
}
return message;
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String firstMatch = "";
//displaying the first match
if (matches != null) {
for(int i = 0; i < matches.size(); i++){
firstMatch = matches.get(i); // get the last one, which has the actual words I spoke...
}
matches.clear();
}
//StatusDisplay.setText("Not Listening...");
// ENTRY POINT FOR ALL COMMAND FUNCTIONALITY
speechToTextAnalyzerResponse = speechToTextAnalyzer.AnalyzeSpeechSingleResponse(firstMatch);
buttonPressCounter = speechToTextAnalyzer.AnalyzeSpeechCounter(buttonPressCounter);
responsive = speechToTextAnalyzer.AnalyzeSpeechResponseThenListen(buttonPressCounter);
SPEECH_RESPONSE_BACK = speechToTextAnalyzerResponse;
WordingDisplay.setText(SPEECH_RESPONSE_BACK);
if(responsive){
RESPONSIVE_SPEECH("... okay now say something new ... ");
}
else {
SINGLE_RESPONSE();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
}); // end of mSpeechRecognizer.setRecognitionListener
SimulateButton = (Button)findViewById(R.id.DoSomething);
SimulateButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
//when the user removed the finger
mSpeechRecognizer.stopListening();
StatusDisplay.setText("Not Listening...");
break;
case MotionEvent.ACTION_DOWN:
//finger is on the button
StatusDisplay.setText("Listening...");
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
// WHILE I HOLD BUTTON THIS ACTUALLY WORKS BUT NOT INSIDE ONUTTERANCEPROGRESSLISTENER.........
break;
}
return true;
}
});
} // end of onCreate()
public void SINGLE_RESPONSE(){
if (!textToSpeech.isSpeaking()) {
textToSpeech.speak(SPEECH_RESPONSE_BACK, TextToSpeech.QUEUE_FLUSH, null);
//textToSpeech.speak(WordingDisplay.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
} else {
textToSpeech.stop();
}
}
public void RESPONSIVE_SPEECH(String PleaseSayThis){
SPEECH_RESPONSE_BACK = PleaseSayThis;
// https://android-developers.googleblog.com/2009/09/introduction-to-text-to-speech-in.html
if (!textToSpeech.isSpeaking()) {
HashMap<String, String> stringStringHashMap = new HashMap<String, String>();
stringStringHashMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "LISTEN_FOR_NEW_RESPONSE"); // when using normal text to speech, the ID is "ID_MAIN_CALL" to be searched for in onUtteranceCompleted
textToSpeech.speak(SPEECH_RESPONSE_BACK, textToSpeech.QUEUE_FLUSH, stringStringHashMap);
} else {
textToSpeech.stop();
}
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
protected void onDestroy(){
if(textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
textToSpeech = null;
}
super.onDestroy();
}
According to the UtteranceProgressListener docs, "The callbacks specified in this method can be called from multiple threads."
To verify this, you can add
boolean wasCalledFromBackgroundThread = (Thread.currentThread().getId() != 1);
Log.i("XXX", "was onDone() called on a background thread? : " + wasCalledFromBackgroundThread);
to the onDone() method body.
In my experience, they are called on background threads more often than not.
So, inside your onDone() method body, I would suggest surrounding the UI manipulation with runOnUiThread() like so:
#Override
public void onDone(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// possible method one:
SimulateButton.performClick();
// possible method two:
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
});
}
I am developing an app in which I want to use transliteration from Hindi to English via speech input. for that, I am using google STT API. Everything works when my voice input is short, but when I give long voice input, Dialog gets stuck at "Try Saying Something..." and I don't get results a well.
This is my Main Activity:-
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Record Button
AppCompatButton RecordBtn;
// TextView to show Original and recognized Text
TextView Original,result;
// Request Code for STT
private final int SST_REQUEST_CODE = 101;
// Conversion Table Object...
ConversionTable conversionTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Original = findViewById(R.id.Original_Text);
RecordBtn = findViewById(R.id.RecordBtn);
result = findViewById(R.id.Recognized_Text);
RecordBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.RecordBtn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// For 30 Sec it will Record...
intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 30);
// Use Off line Recognition Engine only...
intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, false);
// Use Hindi Speech Recognition Model...
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "hi-IN");
try {
startActivityForResult(intent, SST_REQUEST_CODE);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.error),
Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SST_REQUEST_CODE:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> getResult = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Original.setText(getResult.get(0));
conversionTable = new ConversionTable();
String Transformed_String = conversionTable.transform(getResult.get(0));
result.setText(Transformed_String);
}
break;
}
}
}
My ConversationTable.class :-
package android.example.com.conversion;
import android.util.Log;
import java.util.ArrayList;
import java.util.Hashtable;
public class ConversionTable
{
private String TAG = "Conversation Table";
private Hashtable<String,String> unicode;
private void populateHashTable()
{
unicode = new Hashtable<>();
// unicode
unicode.put("\u0901","rha"); // anunAsika - cchandra bindu, using ~ to // *
unicode.put("\u0902","n"); // anusvara
unicode.put("\u0903","ah"); // visarga
unicode.put("\u0940","ee");
unicode.put("\u0941","u");
unicode.put("\u0942","oo");
unicode.put("\u0943","rhi");
unicode.put("\u0944","rhee"); // * = Doubtful Case
unicode.put("\u0945","e");
unicode.put("\u0946","e");
unicode.put("\u0947","e");
unicode.put("\u0948","ai");
unicode.put("\u0949","o");
unicode.put("\u094a","o");
unicode.put("\u094b","o");
unicode.put("\u094c","au");
unicode.put("\u094d","");
unicode.put("\u0950","om");
unicode.put("\u0958","k");
unicode.put("\u0959","kh");
unicode.put("\u095a","gh");
unicode.put("\u095b","z");
unicode.put("\u095c","dh"); // *
unicode.put("\u095d","rh");
unicode.put("\u095e","f");
unicode.put("\u095f","y");
unicode.put("\u0960","ri");
unicode.put("\u0961","lri");
unicode.put("\u0962","lr"); // *
unicode.put("\u0963","lree"); // *
unicode.put("\u093E","aa");
unicode.put("\u093F","i");
// Vowels and Consonants...
unicode.put("\u0905","a");
unicode.put("\u0906","a");
unicode.put("\u0907","i");
unicode.put("\u0908","ee");
unicode.put("\u0909","u");
unicode.put("\u090a","oo");
unicode.put("\u090b","ri");
unicode.put("\u090c","lri"); // *
unicode.put("\u090d","e"); // *
unicode.put("\u090e","e"); // *
unicode.put("\u090f","e");
unicode.put("\u0910","ai");
unicode.put("\u0911","o");
unicode.put("\u0912","o");
unicode.put("\u0913","o");
unicode.put("\u0914","au");
unicode.put("\u0915","k");
unicode.put("\u0916","kh");
unicode.put("\u0917","g");
unicode.put("\u0918","gh");
unicode.put("\u0919","ng");
unicode.put("\u091a","ch");
unicode.put("\u091b","chh");
unicode.put("\u091c","j");
unicode.put("\u091d","jh");
unicode.put("\u091e","ny");
unicode.put("\u091f","t"); // Ta as in Tom
unicode.put("\u0920","th");
unicode.put("\u0921","d"); // Da as in David
unicode.put("\u0922","dh");
unicode.put("\u0923","n");
unicode.put("\u0924","t"); // ta as in tamasha
unicode.put("\u0925","th"); // tha as in thanks
unicode.put("\u0926","d"); // da as in darvaaza
unicode.put("\u0927","dh"); // dha as in dhanusha
unicode.put("\u0928","n");
unicode.put("\u0929","nn");
unicode.put("\u092a","p");
unicode.put("\u092b","ph");
unicode.put("\u092c","b");
unicode.put("\u092d","bh");
unicode.put("\u092e","m");
unicode.put("\u092f","y");
unicode.put("\u0930","r");
unicode.put("\u0931","rr");
unicode.put("\u0932","l");
unicode.put("\u0933","ll"); // the Marathi and Vedic 'L'
unicode.put("\u0934","lll"); // the Marathi and Vedic 'L'
unicode.put("\u0935","v");
unicode.put("\u0936","sh");
unicode.put("\u0937","ss");
unicode.put("\u0938","s");
unicode.put("\u0939","h");
// represent it\
// unicode.put("\u093c","'"); // avagraha using "'"
// unicode.put("\u093d","'"); // avagraha using "'"
unicode.put("\u0969","3"); // 3 equals to pluta
unicode.put("\u014F","Z");// Z equals to upadhamaniya
unicode.put("\u0CF1","V");// V equals to jihvamuliya....but what character have u settled for jihvamuliya
/* unicode.put("\u0950","Ω"); // aum
unicode.put("\u0958","κ"); // Urdu qaif
unicode.put("\u0959","Κ"); //Urdu qhe
unicode.put("\u095A","γ"); // Urdu gain
unicode.put("\u095B","ζ"); //Urdu zal, ze, zoe
unicode.put("\u095E","φ"); // Urdu f
unicode.put("\u095C","δ"); // Hindi 'dh' as in padh
unicode.put("\u095D","Δ"); // hindi dhh*/
unicode.put("\u0926\u093C","τ"); // Urdu dwad
unicode.put("\u0924\u093C","θ"); // Urdu toe
unicode.put("\u0938\u093C","σ"); // Urdu swad, se
}
ConversionTable()
{
populateHashTable();
}
public String transform(String s1)
{
StringBuilder transformed = new StringBuilder();
int strLen = s1.length();
ArrayList<String> shabda = new ArrayList<>();
String lastEntry = "";
for (int i = 0; i < strLen; i++)
{
char c = s1.charAt(i);
String varna = String.valueOf(c);
Log.d(TAG, "transform: " + varna + "\n");
String halant = "0x0951";
if (VowelUtil.isConsonant(varna))
{
Log.d(TAG, "transform: " + unicode.get(varna));
shabda.add(unicode.get(varna));
shabda.add(halant); //halant
lastEntry = halant;
}
else if (VowelUtil.isVowel(varna))
{
Log.d(TAG, "transform: " + "Vowel Detected...");
if (halant.equals(lastEntry))
{
if (varna.equals("a"))
{
shabda.set(shabda.size() - 1,"");
}
else
{
shabda.set(shabda.size() - 1, unicode.get(varna));
}
}
else
{
shabda.add(unicode.get(varna));
}
lastEntry = unicode.get(varna);
} // end of else if is-Vowel
else if (unicode.containsKey(varna))
{
shabda.add(unicode.get(varna));
lastEntry = unicode.get(varna);
}
else
{
shabda.add(varna);
lastEntry = varna;
}
} // end of for
for (String string: shabda)
{
transformed.append(string);
}
//Discard the shabda array
shabda = null;
return transformed.toString(); // return transformed;
}
}
My ViewUtil Class:-
package android.example.com.conversion;
public class VowelUtil {
protected static boolean isVowel(String strVowel) {
// Log.logInfo("came in is_Vowel: Checking whether string is a Vowel");
return strVowel.equals("a") || strVowel.equals("aa") || strVowel.equals("i") || strVowel.equals("ee") ||
strVowel.equals("u") || strVowel.equals("oo") || strVowel.equals("ri") || strVowel.equals("lri") || strVowel.equals("e")
|| strVowel.equals("ai") || strVowel.equals("o") || strVowel.equals("au") || strVowel.equals("om");
}
protected static boolean isConsonant(String strConsonant) {
// Log.logInfo("came in is_consonant: Checking whether string is a
// consonant");
return strConsonant.equals("k") || strConsonant.equals("kh") || strConsonant.equals("g")
|| strConsonant.equals("gh") || strConsonant.equals("ng") || strConsonant.equals("ch") || strConsonant.equals("chh") || strConsonant.equals("j")
|| strConsonant.equals("jh") || strConsonant.equals("ny") || strConsonant.equals("t") || strConsonant.equals("th") ||
strConsonant.equals("d") || strConsonant.equals("dh") || strConsonant.equals("n") || strConsonant.equals("nn") || strConsonant.equals("p") ||
strConsonant.equals("ph") || strConsonant.equals("b") || strConsonant.equals("bh") || strConsonant.equals("m") || strConsonant.equals("y") ||
strConsonant.equals("r") || strConsonant.equals("rr") || strConsonant.equals("l") || strConsonant.equals("ll") || strConsonant.equals("lll") ||
strConsonant.equals("v") || strConsonant.equals("sh") || strConsonant.equals("ss") || strConsonant.equals("s") || strConsonant.equals("h") ||
strConsonant.equals("3") || strConsonant.equals("z") || strConsonant.equals("v") || strConsonant.equals("Ω") ||
strConsonant.equals("κ") || strConsonant.equals("K") || strConsonant.equals("γ") || strConsonant.equals("ζ") || strConsonant.equals("φ") ||
strConsonant.equals("δ") || strConsonant.equals("Δ") || strConsonant.equals("τ") || strConsonant.equals("θ") || strConsonant.equals("σ");
}
}
Outputs :-
for Short voice input :-
for Long voice Input, it stuck and can't get the result:-
The Problem is in Google's Implementation. I was facing the same type of difficulty and tried all the things, but did not work on anything.
So, i went on another way to solve this problem and the solution is implementing listeners by yourself. Here is my code for the same, it never popup the Inbuilt dialog (You can implement your custom dialog), but it works like charm.
Here is how you can do it :
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Record Button
AppCompatButton RecordBtn;
// TextView to show Original
TextView Original;
// SpeechRecognizer Object...
private SpeechRecognizer speechRecognizer;
// For TAG
private String TAG = getClass().getName();
// RecognizerIntent
private Intent recognizerIntent;
// Request Code for Permission
private static final int REQUEST_CODE_RECORD_AUDIO = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Original = findViewById(R.id.Original_Text);
RecordBtn = findViewById(R.id.RecordBtn);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, R.string.record);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, false);
}
// For 30 Sec it will Record...
recognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 30);
// Use Hindi Speech Recognition Model...
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "hi-IN");
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
// Permission Dialog
Askpermission();
RecordBtn.setOnClickListener(this);
}
private void Askpermission() {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
REQUEST_CODE_RECORD_AUDIO);
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_RECORD_AUDIO: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Operation();
} else {
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.RecordBtn:
Log.d(TAG, "onClick: ");
if (checkPermission()) {
if (IsAvailable(this)) {
Log.d(TAG, "Speech Recognition Service Available...");
speechRecognizer.startListening(recognizerIntent);
} else {
Toast.makeText(this, "Speech Recognition Service not Available on your device...",
Toast.LENGTH_SHORT)
.show();
}
} else {
Askpermission();
}
break;
}
}
// Check if Speech recognition Service is Available on the Smartphone...
private boolean IsAvailable(Context context) {
return SpeechRecognizer.isRecognitionAvailable(context);
}
#Override
protected void onDestroy() {
super.onDestroy();
speechRecognizer.destroy();
}
// Check Audio Permission
private boolean checkPermission() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED;
}
// Start Operation
private void Operation() {
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "Audio Service is connected to Servers....");
Log.d(TAG, "You can now start your speech...");
}
#Override
public void onBeginningOfSpeech() {
Log.d(TAG, "User has started speech...");
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
Log.d(TAG, "User has Finished... speech...");
}
#Override
public void onError(int error) {
Log.d(TAG, "onError: " + error);
switch (error){
case SpeechRecognizer.ERROR_AUDIO:
Toast.makeText(MainActivity.this, "Error Recording Audio...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_CLIENT:
Toast.makeText(MainActivity.this, "Client Side Error...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
Toast.makeText(MainActivity.this, "Insufficient permissions...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NETWORK:
Toast.makeText(MainActivity.this, "Network Related Error...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NO_MATCH:
Toast.makeText(MainActivity.this, "Please Installed Offline Hindi " +
"Language Data...", Toast.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
Toast.makeText(MainActivity.this, "Recognition Busy...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_SERVER:
Toast.makeText(MainActivity.this, "Please Installed Offline Hindi " +
"Language Data...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
Toast.makeText(MainActivity.this, "Speech Timeout...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
Toast.makeText(MainActivity.this, "Network Timeout Error...", Toast
.LENGTH_SHORT).show();
}
}
#Override
public void onResults(Bundle results) {
ArrayList<String> Results = results.getStringArrayList(SpeechRecognizer
.RESULTS_RECOGNITION);
if (Results != null) {
Original.setText(Results.get(0));
}
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
}
}
I'm Using Yandex Translator in my app, it works great if i'm using Activity, But when i add it to fragment , the app crashes before the launch.
Also no errors shown in the code , like everything is good, what could be the problem :
I looked for similar answers here, but i got nothing, no one had this issue before using fragments.
And here is the code for fragment :
public class FavoritesFragment extends Fragment implements TextToSpeech.OnInitListener{
private TextView header, toText, toLabel, fromLabel;
private ImageView micFrom, volFrom, volTo, reverse;
private EditText fromText;
private CircleButton convertBTN;
private CircleButton convertLayout;
private final int REQ_CODE_SPEECH_INPUT = 100;
private final int SR_CODE = 123;
private String ENGLISH_CONSTANT = "";
private String TURKISH_CONSTANT = "";
private String ENGLISH_CONVERT = "";
private String TURKISH_CONVERT = "";
private String TURKISH_CODE = "";
private String currentFrom = "";
TextToSpeech ttsEnglish, ttsTURKISH;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_favorites, container, false);
setUpInitialConstants();
setUpInteraction();
setUpSpeakingListeners();
setUpListeners();
return v;
}
private void setUpInitialConstants() {
ENGLISH_CONSTANT = ("ENGLISH");
TURKISH_CONSTANT = ("TURKISH");
ENGLISH_CONVERT = ("en") + "-" + ("tr");//"en-zh";
TURKISH_CONVERT = ("tr") + "-" + ("en");
//"zh-en";
TURKISH_CODE = ("tr");
currentFrom = ENGLISH_CONSTANT;
}
private void setUpSpeakingListeners() {
ttsEnglish = new TextToSpeech(getContext().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = ttsEnglish.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported");
} else {
//ConvertTextToSpeech();
}
} else
Log.e("error", "Initilization Failed!");
}
});
ttsTURKISH = new TextToSpeech(getContext().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
Locale locale = new Locale("tr-TR");
int result = ttsTURKISH.setLanguage(locale);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "not supported");
} else {
//ConvertTextToSpeech();
}
} else
Log.e("error", "Initilization Failed!");
}
});
}
#SuppressLint("ClickableViewAccessibility")
private void setUpListeners() {
convertLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
callReverse();
}
});
micFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
askSpeechInput(currentFrom);
}
});
volFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
ConvertTextToSpeech(currentFrom, fromText.getText().toString());
}
});
volTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
String currentFromR = reverseCurrentFrom(currentFrom);
ConvertTextToSpeech(currentFromR, toText.getText().toString());
}
});
convertBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
if (currentFrom.equals(ENGLISH_CONSTANT))
translateText(fromText.getText().toString(), ENGLISH_CONVERT);
else
translateText(fromText.getText().toString(), TURKISH_CONVERT);
}
});
toText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
if (copyToClipboard(getContext().getApplicationContext(), toText.getText().toString())) {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
Toast.makeText(getContext().getApplicationContext(), ("copied"), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext().getApplicationContext(), (" copied successfully "), Toast.LENGTH_SHORT).show();
}
}
}
});
fromText.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
fromText.setFocusableInTouchMode(true);
return false;
}
});
}
private String reverseCurrentFrom(String currentFrom) {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
return TURKISH_CONSTANT;
} else return ENGLISH_CONSTANT;
}
private void callReverse() {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
currentFrom = TURKISH_CONSTANT;
//header.setText(getString(R.string.convertHeaderR));
fromLabel.setText(("TURKISH"));
fromText.setHint(("push to talk"));
toLabel.setText(("English"));
toText.setText(("Click translate Button to get English text"));
} else {
currentFrom = ENGLISH_CONSTANT;
//header.setText(getString(R.string.convertHeader));
fromLabel.setText(("English"));
fromText.setHint(("Speak or type text here"));
toLabel.setText(("TURKISH"));
toText.setText(("click to translate"));
}
fromText.setText("");
fromText.setFocusable(false);
}
private void setUpInteraction() {
this.getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
toText = getView().findViewById(R.id.toText);
toLabel = getView().findViewById(R.id.toLabel);
fromLabel = getView().findViewById(R.id.fromLabel);
micFrom = getView().findViewById(R.id.micFrom);
volFrom = getView().findViewById(R.id.volFrom);
volTo = getView().findViewById(R.id.toVol);
convertBTN = getView().findViewById(R.id.convertBTN);
fromText = getView().findViewById(R.id.fromText);
convertLayout = getView().findViewById(R.id.swapLanguage);
fromText.setFocusable(false);
currentFrom = TURKISH_CONSTANT;
callReverse();
}
private void ConvertTextToSpeech(String lang_type, String text) {
if (text == null || "".equals(text)) {
if (lang_type.equals(ENGLISH_CONSTANT)) {
text = ("Content not available");
} else {
text = ("something wrong !");
}
}
if (lang_type.equals(ENGLISH_CONSTANT)) {
ttsEnglish.speak(text, TextToSpeech.QUEUE_FLUSH, null);
} else {
ttsTURKISH.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
private void askSpeechInput(String lang_type) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
if (lang_type.equals(ENGLISH_CONSTANT)) {
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Hi speak something");
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} else {
//Specify language
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_RESULTS, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, ("speak please"));
startActivityForResult(intent, SR_CODE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
fromText.setText(result.get(0));
}
break;
}
case SR_CODE: {
if (resultCode == RESULT_OK) {
if (data != null) {
ArrayList<String> nBestList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String bestResult = nBestList.get(0);
fromText.setText(bestResult);
}
}
break;
}
}
if (currentFrom.equals(ENGLISH_CONSTANT))
translateText(fromText.getText().toString(), ENGLISH_CONVERT);
else
translateText(fromText.getText().toString(), TURKISH_CONVERT);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
} else {
Log.e("TTS", "Initialization failed");
}
}
String text_to_return = "";
private String translateText(final String text, final String lang) {
class getQData extends AsyncTask<String, String, String> {
ProgressDialog loading;
String ROOT_URL = "https://translate.yandex.net";
Retrofit adapter = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(JacksonConverterFactory.create())
.build();
APICalls api = adapter.create(APICalls.class);
#Override
protected void onPreExecute() {
super.onPreExecute();
showPD();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... params) {
text_to_return = "";
String key = translator_Constants.MY_KEY;
Call<TranslateResponse> call = api.translate(key, text, lang);
call.enqueue(new Callback<TranslateResponse>() {
#Override
public void onResponse(retrofit.Response<TranslateResponse> response, Retrofit retrofit) {
//loading.dismiss();
hidePD();
Log.d("succ", "onResponse:code" + String.valueOf(response.code()));
Log.d("error mesg", String.valueOf(response.message()));
switch (response.code()) {
case 200:
TranslateResponse tr = response.body();
text_to_return = tr.getText().get(0);
toText.setText(text_to_return);
String currentFromR = reverseCurrentFrom(currentFrom);
ConvertTextToSpeech(currentFromR, toText.getText().toString());
break;
default:
if (currentFrom.equals(ENGLISH_CONSTANT))
Toast.makeText(getContext().getApplicationContext(), ("Please Try Again"), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext().getApplicationContext(), ("again"), Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onFailure(Throwable t) {
pd.dismiss();
Log.d("retro error", t.getMessage());
if (currentFrom.equals(ENGLISH_CONSTANT))
Toast.makeText(getContext().getApplicationContext(), ("Failed to Convert!Check Internet Connection"), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext().getApplicationContext(), ("no connexion"), Toast.LENGTH_SHORT).show();
}
});
return text_to_return;
}
}
getQData ru = new getQData();
try {
ru.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return text_to_return;
}
ProgressDialog pd;
private void showPD() {
pd = new ProgressDialog(getActivity());
if (currentFrom.equals(ENGLISH_CONSTANT)) {
pd.setMessage(("Patience, We are translating…"));
} else {
pd.setMessage(("translating ..."));
}
pd.show();
}
private void hidePD() {
pd.dismiss();
}
public boolean copyToClipboard(Context context, String text) {
try {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
.getSystemService(CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText("copy", text);
clipboard.setPrimaryClip(clip);
}
return true;
} catch (Exception e) {
return false;
}
}
}
Call setupInteraction() from onViewCreated(), not from onCreateView(). You are trying to use getView(), which will not work until onCreateView() returns.
I have an activity where the user can update some data related to his profile (for example, his name) and he can also upload a new profile image.
After the update operation, the user is redirected to a new activity.
The problem is that when the user comes back to his profile activity, the showed image is still the old one and not the new one while the name updated correctly.
In order to see the new profile image, the user needs to close the app and open is again.
How can I solve this problem?
I use a function updateInfo(), but it seems to not work as I would like.
Can you help me, please?
public class ProfileActivity extends BaseActivity implements ProfileView {
#BindView(R.id.avatar)
ImageView p_avatar;
#BindView(R.id.ib_back)
ImageButton ibBack;
#BindView(R.id.txt_title)
TextView txtTitle;
#BindView(R.id.ib_right)
ImageButton ibRight;
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.et_fullname)
EditText etFullname;
#BindView(R.id.et_email)
EditText etEmail;
#BindView(R.id.btn_update)
Button btnUpdate;
#BindView(R.id.txt_logout)
TextView txtLogout;
#BindView(R.id.ll_main)
LinearLayout llMain;
private static final String TAG = "ProfileActivity";
private String userName = null, userEmail = null;
private ProfilePresenter profilePresenter;
private Dialog dialog;
Bitmap FixBitmap;
Bitmap bitmap_to_save;
ImageView ShowSelectedImage;
String converted_img;
ByteArrayOutputStream byteArrayOutputStream;
byte[] byteArray ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
ButterKnife.bind(this);
byteArrayOutputStream = new ByteArrayOutputStream();
init_view();
upDateInfo();
}
private void init_view() {
txtTitle.setText(R.string.profileActivity_title);
ibRight.setImageResource(R.drawable.ic_edit);
dialog = commonUtils.createCustomLoader(ProfileActivity.this, false);
profilePresenter = new ProfilePresenterImpl(this);
upDateInfo();
}
private void upDateInfo() {
if (Conts.USERINFO != null) {
String subName = firstTwoChar(Conts.USERINFO.getName());
// Picasso.get().load("http://www.server.com/uploads/avatars/73.png").transform(transformation).into(p_avatar);
final int radius = 30;
final int margin = 1;
final RoundedCornersTransformation transformation = new RoundedCornersTransformation(radius, margin);
Picasso.get().load("http://www.server.com/uploads/avatars/"+Conts.USERINFO.getId()).transform(transformation).into(p_avatar);
etFullname.setText(Conts.USERINFO.getName().toLowerCase());
etFullname.setEnabled(false);
etEmail.setText(Conts.USERINFO.getEmail());
etEmail.setEnabled(false);
btnUpdate.setVisibility(View.INVISIBLE);
}
}
#OnClick({R.id.ib_back, R.id.ib_right, R.id.btn_update, R.id.txt_logout, R.id.avatar})
public void onClick(View view) {
switch (view.getId()) {
case R.id.ib_back:
onBackPressed();
break;
case R.id.ib_right:
etFullname.setEnabled(true);
etFullname.setSelection(etFullname.getText().toString().length());
btnUpdate.setVisibility(View.VISIBLE);
Log.d(TAG, "validate ID: " + Conts.USERINFO.getId());
return;
case R.id.avatar:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image From Gallery"), 1);
return;
case R.id.btn_update:
if (validate()) {
if (!commonUtils.isNetworkAvailable()) {
Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
return;
}
profilePresenter.dataListAPI(Conts.USERINFO.getId(), userName, Conts.USERINFO.getEmail(), converted_img);
}
break;
case R.id.txt_logout:
get_dialog();
break;
}
}
#Override
protected void onActivityResult(int RC, int RQC, Intent I) {
super.onActivityResult(RC, RQC, I);
if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
try {
FixBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
bitmap_to_save = scaleBitmapAndKeepRation(FixBitmap, 320, 320);
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap_to_save);
final float roundPx = (float) bitmap_to_save.getWidth() * 0.15f;
roundedBitmapDrawable.setCornerRadius(roundPx);
roundedBitmapDrawable.setAntiAlias(true);
p_avatar.setImageDrawable(roundedBitmapDrawable);
bitmap_to_save.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byteArray = byteArrayOutputStream.toByteArray();
converted_img = Base64.encodeToString(byteArray, Base64.DEFAULT); // this is the image string to send to the server!
} catch (IOException e) {
e.printStackTrace();
}
}
else {
Toast.makeText(this, "An error has occurred!", Toast.LENGTH_SHORT).show();
}
}
public static Bitmap scaleBitmapAndKeepRation(Bitmap TargetBmp, int reqHeightInPixels, int reqWidthInPixels)
{
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, TargetBmp.getWidth(), TargetBmp.getHeight()), new RectF(0, 0, reqWidthInPixels, reqHeightInPixels), Matrix.ScaleToFit.CENTER);
Bitmap scaledBitmap = Bitmap.createBitmap(TargetBmp, 0, 0, TargetBmp.getWidth(), TargetBmp.getHeight(), m, true);
return scaledBitmap;
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private void get_dialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
View view = LayoutInflater.from(this).inflate(R.layout.dialog_logout, null);
builder.setView(view);
final AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
alertDialog.show();
TextView txtyes, txtno;
txtyes = view.findViewById(R.id.txt_yes);
txtno = view.findViewById(R.id.txt_no);
txtyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
sharedPref.setBoolean(Conts.IsLogin, false);
sharedPref.clearAllPref();
Conts.USERINFO = null;
Intent iLogin = new Intent(ProfileActivity.this, MainActivity.class);
iLogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(iLogin);
}
});
txtno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}
public String firstTwoChar(String str) {
return str.length() < 2 ? str : str.substring(0, 2);
}
#Override
public void showLoader() {
dialog.show();
}
#Override
public void hideLoader() {
if (dialog != null)
dialog.dismiss();
}
#Override
public void showError(String msg) {
Snackbar snackbar = Snackbar
.make(llMain, msg, Snackbar.LENGTH_INDEFINITE)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
// nothing anything
}
});
snackbar.show();
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
#Override
public Context getContextAppp() {
return this;
}
#Override
public void onBackPress() {
}
#Override
public void successResponse(Data data) {
if (data != null) {
Toast.makeText(this, "Profile updated successfully", Toast.LENGTH_SHORT).show();
UserInfo userInfo = new UserInfo(data.getId(), data.getName(), data.getEmail());
Conts.USERINFO = userInfo;
String userinfo = gson.toJson(Conts.USERINFO, UserInfo.class);
sharedPref.setDataInPref(Conts.UserInfo, userinfo);
startActivity(getIntent());
Intent iPlace = new Intent(ProfileActivity.this, AddPlaceActivity.class);
iPlace.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
Toast.makeText(this, "Profile saved!", Toast.LENGTH_SHORT).show();
startActivity(iPlace);
}
}
#Override
public void errorResponce(String msg) {
if (msg != null) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
private boolean validate() {
commonUtils.hideKeyboard(this);
if (etFullname.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Please enter Fullname", Toast.LENGTH_SHORT).show();
} else if (etFullname.getText().toString().trim().length() <= 2) {
Toast.makeText(this, "Minimum 3 character require", Toast.LENGTH_SHORT).show();
} else if (etFullname.getText().toString().trim().length() > 30) {
Toast.makeText(this, "Maximum 30 character require", Toast.LENGTH_SHORT).show();
}
/*else if (etEmail.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Please enter Email", Toast.LENGTH_SHORT).show();
} else if (!validation.checkEmail(etEmail)) {
Toast.makeText(this, "Please enter valid Email", Toast.LENGTH_SHORT).show();
}
*/
if (!etFullname.getText().toString().trim().isEmpty() && etFullname.getText().toString().trim().length() > 2 && etFullname.getText().toString().trim().length() <= 30) {
userName = etFullname.getText().toString().trim();
} else {
userName = null;
}
/*if (!etEmail.getText().toString().trim().isEmpty() && validation.checkEmail(etEmail)) {
userEmail = etEmail.getText().toString().trim();
} else {
userEmail = null;
}
*/
if (userName != null /*&& userEmail != null*/) {
Log.d(TAG, "validate: " + userName);
return true;
} else {
return false;
}
}
}
When you turn back to your profile activity your application's task stack is bringing back your profile activity which is already in memory. So you should inform your profile activity that it was updated. In the onStart callback of your profile activity check if it is updated. If so load the new image. In short put your upDateInfo() method inside onStart().
After you update the information, in callback method onResponse you need to call updateInfo() to make an update on your UI after update of information is successfully finished. Make sure you provide new values from server especially to static variables because they will keep values as long as app is live. If you don't update them with new values they will keep old ones.
Currently on that way you are trying to update informations only in onCreate() which is called when Activity needs to be created. In this scenario it is when you exit and enter app again only by pressing Back button while on Home button it will not work as well until app is destroyed by OS.
You could also use onResume method which is called after Activity is returned from pause and that will happen when you create a new Activity upon already exiting one.
I need to speak multiple language. I created an array for TextToSpeech.
private TextToSpeech[] mTextSpeechs_;
mTextSpeechs_ = new TextToSpeech[5];
mTextSpeechs_[0] = new TextToSpeech(this, new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status)
{
mTextSpeechs_[0].setLanguage(Locale.CHINESE);
mTextSpeechs_[0].speak(getString(R.string.string_main_chineseready), TextToSpeech.QUEUE_FLUSH, null,"Display");
}
});
mTextSpeechs_[1] = new TextToSpeech(this, new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status)
{
mTextSpeechs_[1].setLanguage(Locale.forLanguageTag("yue-HK"));
mTextSpeechs_[1].speak(getString(R.string.string_main_hongkong), TextToSpeech.QUEUE_FLUSH, null,"Display");
}
});
mTextSpeechs_[2] = new TextToSpeech(this, new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status)
{
mTextSpeechs_[2].setLanguage(Locale.JAPAN);
mTextSpeechs_[2].speak(getString(R.string.string_main_japan), TextToSpeech.QUEUE_FLUSH, null,"Display");
}
});
mTextSpeechs_[3] = new TextToSpeech(this, new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status)
{
mTextSpeechs_[3].setLanguage(Locale.KOREA);
mTextSpeechs_[3].speak(getString(R.string.string_main_korea), TextToSpeech.QUEUE_FLUSH, null,"Display");
}
});
mTextSpeechs_[4] = new TextToSpeech(this, new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status)
{
mTextSpeechs_[4].setLanguage(Locale.ENGLISH);
mTextSpeechs_[4].speak(getString(R.string.string_main_english), TextToSpeech.QUEUE_FLUSH, null,"Display");
}
});
....
//type 0 flush
//type 1 add
public void speakMultiLanguage(String text, int type,int langidx)
{
if( type == 0 )
mTextSpeechs_[langidx_].speak(text, TextToSpeech.QUEUE_FLUSH, null,"Display");
else if( type == 1)
mTextSpeechs_[langidx_].speak(text, TextToSpeech.QUEUE_ADD, null,"Display");
}
Now, When I call speakMultiLanguage function to speak specified language, it will delay about 5 seconds to speak. If the last language is same, it will not delay. Does anyone give me a solution to solve the delay?
I wasn't testing your particular case of multiple usage of TTS in array. But for me it looks none productive, especially memory and resources using.
In my case I initialise only one TTS object in onCreate() method of My Activity. And when I need to change languge to another, I'll use tts.setLanguge(Locale).
In my case and with my virtual device this solution working immediately.
initialise:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
tts.setLanguage(Locale.ENGLISH);
}else{
Log.e(TAG, "TTS fault");
}
}
});
//....
}
Change:
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void prepareTTS(Locale newLocale){
if (!tts.getVoice().getLocale().getISO3Language().equals(newLocale.getISO3Language())) {
tts.setLanguage(newLocale);
Log.d(TAG, "ChangeTo: " + newLocale.getISO3Language());
}else{
Log.d(TAG, "The same");
}
}
speech:
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void ttsSpeak21(String text){
String utteranceId = this.hashCode() + "";
int result = tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
if (result == TextToSpeech.ERROR){
Log.d(TAG, "Can't say");
}else {
Log.d(TAG, lang + "speaking!");
}
}
free resources:
#Override
protected void onDestroy() {
if (tts != null){
tts.stop();
tts.shutdown();
}
super.onDestroy();
}