i want know how Read text from editText and show the answer - java

I have a question, by pressing long on imageView imageViewClick.setOnLongClickListener recognizes the voice and answers the question. How do I make the normal press imageViewClick.setOnClickListener recognize the text of the editText and answer the question?
i want know how Read text from editText and show the answer
Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
imageViewClick = (ImageView) findViewById(R.id.imageViewClick);
imageViewClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
imageViewClick.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent voice = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "es-ES");
voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "es-MX");
voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "pr-PR");
startActivityForResult(voice, VOICE_RECOGNIZER);
return false;
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == VOICE_RECOGNIZER){
ArrayList<String> recognized = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String listened = recognized.get(0);
editTextListening.setText(listened);
prepareAnswer(listened);
}
}
private void prepareAnswer(String listened) {
String normalize = Normalizer.normalize(listened, Normalizer.Form.NFD);
String withouttilde = normalize.replaceAll("[^\\p{ASCII}]", "");
int result;
String answer = arrayListAnswer.get(0).getAnswer();
for (int i = 0; i < arrayListAnswer.size(); i++) {
result = withouttilde.toLowerCase().indexOf(arrayListAnswer.get(i).getQuestion());
if(result != -1){
answer = arrayListAnswer.get(i).getAnswer();
}
}
answerTo(answer);
}
private void answerTo(String simpleAnswer) {
textViewAnswer.setText(simpleAnswer);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeechRead.speak(simpleAnswer, TextToSpeech.QUEUE_FLUSH, null, null);
}else {
textToSpeechRead.speak(simpleAnswer, TextToSpeech.QUEUE_FLUSH, null);
}
}
public void initialize(){
editTextListening = (EditText) findViewById(R.id.editTextQuestion);
textViewAnswer = (TextView) findViewById(R.id.textViewAnswer);
arrayListAnswer = provideData();
textToSpeechRead = new TextToSpeech(this, this);
}
#Override
public void onInit(int status) {
}
public ArrayList<AnswersActivity> provideData(){
ArrayList<AnswersActivity> answers = new ArrayList<>();
answers.add(new AnswersActivity("defecto", "No estoy programado para hablar de eso"));
answers.add(new AnswersActivity("puff", "Puff"));
answers.add(new AnswersActivity("chiste", "¿Sabes que mi hermano anda en bicicleta desde los 4 años? Mmm, ya debe estar lejos"));
answers.add(new AnswersActivity("adios", "que descanses"));
answers.add(new AnswersActivity("estas", "esperando serte de ayuda"));
answers.add(new AnswersActivity("dj", "YEY BALBIN"));
return answers;
}
}

To recognize the input in EditText and convert the input to speech, you can use the TextToSpeech class provided by Android. Example of this:
textToSpeech = new TextToSpeech(MainActivity.this, MainActivity.this);
editText = (EditText) findViewById(R.id.editText);
imageViewClick = (ImageView) findViewById(R.id.imageViewClick);
imageViewClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextToSpeechFunction() ;
}});
}
public void TextToSpeechFunction()
{
String text = editText.getText().toString();
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(MainActivity.this , text, Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
textToSpeech.shutdown();
super.onDestroy();
}
#Override
public void onInit(int TexttoSpeechCurrentStatus) {
if (TexttoSpeechCurrentStatus == TextToSpeech.SUCCESS) {
textToSpeech.setLanguage(Locale.US);
imageViewClick.setEnabled(true);
TextToSpeechFunction();
}
}

Related

Speechrecognizer not working for quiz app where After each correct/incorrect it moves to next one

I want to build an app for quiz using a Speech recognizer it only works for 1 question what if I have a series of questions After each correct/incorrect it moves to the next one, which I already used for the loop here is not working code is not going inside the speechRecognizer.setRecognitionListener(new RecognitionListener() this
if code goes inside it my problem will be solved If anyone knows other methods please answer
public class MainActivity extends AppCompatActivity {
EditText tv;
ImageButton btn;
TextToSpeech textToSpeech;
SpeechRecognizer speechRecognizer;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (EditText) findViewById(R.id.edittext);
btn = (ImageButton) findViewById(R.id.btn);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
}
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.ENGLISH);
}
}
});
btn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("UseCompatLoadingForDrawables")
#Override
public void onClick(View v) {
String[] arr = {"2 multiply 2 is", "4 multiply 4 is ", "3 into 3 is", };
int i=0;
while (i<arr.length ) {
textToSpeech.speak(arr[i], TextToSpeech.QUEUE_FLUSH, null);
try {
Thread.sleep(2000);
speechRecognizer.startListening(intent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int finalI = i;
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle results) {
ArrayList<String> data = results.getStringArrayList(speechRecognizer.RESULTS_RECOGNITION);
String res = data.get(0);
tv.setText(res);
if (arr[finalI].equals("2 multiply 2 is")){
if (res.equals("4")) {
textToSpeech.speak("correct", TextToSpeech.QUEUE_FLUSH, null);
speechRecognizer.stopListening();
data.remove(0);
} else {
textToSpeech.speak("Incorrect", TextToSpeech.QUEUE_FLUSH, null);
speechRecognizer.stopListening();
data.remove(0);
}
}
if (arr[finalI].equals("4 multiply 4 is")){
if (res.equals("8")) {
textToSpeech.speak("correct", TextToSpeech.QUEUE_FLUSH, null);
speechRecognizer.stopListening();
data.remove(0);
} else {
textToSpeech.speak("Incorrect", TextToSpeech.QUEUE_FLUSH, null);
speechRecognizer.stopListening();
data.remove(0);
}
}
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
i++; }
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}

Google Cloud Speech API for Android

Currently I`m working on a project where i have to use Google Cloud Speech Api and TextToSpeech. I try-ed to work around with RecognizerIntent but i would like to give a try to Cloud Speech .
Would be great some tutorial material or guide , i checked the sample app
but i`m looking for tutorial , guide anything that could explain something.
Here is my work around with TTS and RecognizerIntent .
private TextToSpeech tts;
private TextToSpeech secondTTS;
private TextView speechInputTextView,correctAnswerTextView,wrongAnswerTextView,currentQuestionTextView;
private ArrayList<String> correctAnswersArrayList, questionArrayList, sayCorrectArrayList, sayWrongArrayList ,toSay ,toASk;
private MediaPlayer mediaPlayer;
private DBHelper dbHelper;
private SQLiteDatabase sqlDB;
private int correctACount,wrongACount,currentQuestion, Unit;
private boolean isStarted;
private String currentLanguage ;
private static int TOTAL_QUESITONS;
private final static int REQ_CODE_SPEECH_INPUT = 100;
private final static String PAUSE_COMMAND = "pos";
private final static String STOP_COMMAND = "stop";
private final static String RESTART_COMMNAD = "restart";
private final static String REPEAT_COMMAND = "repeat";
private final static String EXIT_COMMAND = "exit";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unit);
isStarted = true;
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.unitonemp3);
currentQuestion = 0;
speechInputTextView = (TextView) findViewById(R.id.speechInput);
correctAnswerTextView = (TextView) findViewById(R.id.correctAnswers_TextView);
currentQuestionTextView = (TextView) findViewById(R.id.currentQuestion_TextView);
wrongAnswerTextView = (TextView) findViewById(R.id.wrongAnswer_TextView);
Unit = 1;
currentLanguage = getIntent().getBundleExtra("resultBundle").getString("language");
Button next = (Button) findViewById(R.id.nextButton);
Button changeUnitButton = (Button) findViewById(R.id.changeUnitButton);
Button playButton = (Button) findViewById(R.id.playButton);
Button pauseButton = (Button) findViewById(R.id.pauseButton);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tts.stop();
secondTTS.stop();
Intent pauseI = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putInt("npc", currentQuestion);
pauseI.putExtra("resultBundle", resultBundle);
startActivity(pauseI);
}
});
tts = new TextToSpeech(this, this);
secondTTS = new TextToSpeech(this, this);
changeUnitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
secondTTS.stop();
tts.stop();
Unit ++;
mediaPlayer.start();
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
currentQuestion = getIntent().getBundleExtra("resultBundle").getInt("npc");
}
ImageView micButton = (ImageView) findViewById(R.id.micButton);
micButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!tts.isSpeaking()) {
currentQuestion = 13;
startSayWithID(questionArrayList.get(currentQuestion), 1000, "questionID");
}
}
});
String[] sayCorrectList = getResources().getStringArray(R.array.sayCorrect);
String[] sayWrongList = getResources().getStringArray(R.array.satWrong);
String[] listToSay = getResources().getStringArray(R.array.toSay);
String[] listToAsk = getResources().getStringArray(R.array.toAsk);
toSay = new ArrayList<>(Arrays.asList(listToSay));
toASk = new ArrayList<>(Arrays.asList(listToAsk));
questionArrayList = new ArrayList<>();
correctAnswersArrayList = new ArrayList<>();
addGerCorrect();
addEngQuestions();
sayCorrectArrayList = new ArrayList<>(Arrays.asList(sayCorrectList));
sayWrongArrayList = new ArrayList<>(Arrays.asList(sayWrongList));
TOTAL_QUESITONS = questionArrayList.size();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
startSayWithID("Welcome",1000,"instruction");
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0 ; i< questionArrayList.size();i++){
Log.d(" question List "," item :"+"pisition "+i+ "" +questionArrayList.get(i));
}
currentQuestion++;
tts.stop();
secondTTS.stop();
startSayWithID("",1000,"instruction");
}
});
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(final String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (utteranceId.contains("say")) {
if (correctAnswersArrayList.get(currentQuestion).contains("tensa23")) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
currentQuestion++;
Log.d("Current ", "current Question" + currentQuestion + "" + correctAnswersArrayList.get(currentQuestion));
}else
startSayWithID(questionArrayList.get(currentQuestion), 1000, "question");
}
if (utteranceId.contains("instruction")) {
if (correctAnswersArrayList.get(currentQuestion).contains("tensa23")) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
currentQuestion++;
Log.d("Current ","current Question"+currentQuestion +""+correctAnswersArrayList.get(currentQuestion));
} else if (questionArrayList.get(currentQuestion).contains("?")) {
startSayWithID(toASk.get(new Random().nextInt(toASk.size())), 1000, "say");
} else {
startSayWithID(toSay.get(new Random().nextInt(toSay.size())), 1000, "say");
}
}
if (utteranceId.contains("question")) {
if(questionArrayList.get(currentQuestion).contains("?")){
startSayWithID("in Spanish you ask",1000,"german");
}else{
startSayWithID("In Spanish you say",1000,"german");
}
}
if (utteranceId.contains("german")) {
secondTTS.speak(correctAnswersArrayList.get(currentQuestion),TextToSpeech.QUEUE_FLUSH,null,"ask");
}
if(utteranceId.contains("ask")){
startAsk(1000);
}
}
});
}
#Override
public void onError(String utteranceId) {
}
});
secondTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(final String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(utteranceId.contains("ask")){
startAsk(1000);
}
}
});
}
#Override
public void onError(String utteranceId) {
}
});
// end of MainActivity
}
private void promptSpeechInput() {
Intent prompIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
prompIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "es-ES");
prompIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "How do you say \n" +questionArrayList.get(currentQuestion));
try {
startActivityForResult(prompIntent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
makeText(getApplicationContext(), "speech not supported", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.US);
switch (currentLanguage){
case "Spanish" :
secondTTS.setLanguage(new Locale("es","Es"));
break;
case "Italian" :
secondTTS.setLanguage(Locale.ITALY);
break;
case "German" :
secondTTS.setLanguage(Locale.GERMAN);
break;
case "French" :
secondTTS.setLanguage(Locale.FRENCH);
break;
}
}
}
protected 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);
speechInputTextView.setText(result.get(0));
}
}
String inputSpeechToString = speechInputTextView.getText().toString().toLowerCase();
if (currentQuestion < TOTAL_QUESITONS && inputSpeechToString.contains(correctAnswersArrayList.get(currentQuestion))) {
currentQuestion++;
correctACount++;
correctAnswerTextView.setText(String.valueOf(correctACount));
currentQuestionTextView.setText(String.valueOf(currentQuestion));
Log.d("Onactivity ", "CurrentQ = " + currentQuestion);
startSayWithID(sayCorrectArrayList.get(new Random().nextInt(sayCorrectArrayList.size())), 1000, "instruction");
} else if (inputSpeechToString.contains(STOP_COMMAND)) {
Intent stopIntent = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putBoolean("isStarted", isStarted);
stopIntent.putExtra("resultBundle", resultBundle);
startActivity(stopIntent);
} else if (inputSpeechToString.contains(PAUSE_COMMAND)) {
Intent pauseI = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putInt("npc", currentQuestion);
pauseI.putExtra("resultBundle", resultBundle);
startActivity(pauseI);
} else if (inputSpeechToString.contains(RESTART_COMMNAD)) {
currentQuestion = 0;
startSayWithID("Restarted", 1000, "say");
} else if (inputSpeechToString.contains(REPEAT_COMMAND)) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "question");
} else if (inputSpeechToString.contains(EXIT_COMMAND)) {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
} else {
startSayWithID(sayWrongArrayList.get(new Random().nextInt(sayWrongArrayList.size())), 1000, "instruction");
wrongACount++;
wrongAnswerTextView.setText(String.valueOf(wrongACount));
Log.d("Onactivity ", "CORRECT = " + correctAnswersArrayList.get(currentQuestion));
Log.d("Onactivity ", "You said : " + inputSpeechToString);
}
}
}
private void addEngQuestions() {
dbHelper = new DBHelper(this);
sqlDB = dbHelper.getReadableDatabase();
String queryEngQuestion = "SELECT English FROM " +currentLanguage+ " WHERE " + "Unit = " +Unit+ " ORDER BY Unit ASC";
Cursor cursor = sqlDB.rawQuery(queryEngQuestion, null);
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
questionArrayList.add(cursor.getString(cursor.getColumnIndex("English")));
cursor.moveToNext();
}
} finally {
cursor.close();
}
Log.d("Line 255", " English Arraylist" + questionArrayList.size());
}
private void addGerCorrect() {
dbHelper = new DBHelper(this);
sqlDB = dbHelper.getReadableDatabase();
String queryGerCOrrect = "SELECT "+ currentLanguage +" FROM "+ currentLanguage + " WHERE "+ "Unit = "+Unit+ " ORDER BY Unit ASC";
Cursor cursor2 = sqlDB.rawQuery(queryGerCOrrect, null);
try {
cursor2.moveToFirst();
while (!cursor2.isAfterLast()) {
correctAnswersArrayList.add(cursor2.getString(cursor2.getColumnIndex(currentLanguage))
.replaceAll("\\p{P}", "").toLowerCase());
cursor2.moveToNext();
}
} finally {
cursor2.close();
}
}
private void startSayWithID(final String text, int mSeconds, final String ID) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, ID);
}
}, mSeconds);
}
private void startAsk(int seconds) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
promptSpeechInput();
}
}, seconds);
}
#Override
protected void onDestroy() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
if (tts != null) {
tts.stop();
tts.shutdown();
}
if (secondTTS != null) {
secondTTS.stop();
secondTTS.shutdown();
}
super.onDestroy();
}
Setting up Google Speech cloud on Android is not a straightforward 1,2,3 process, but I will give you some guidance.
Download the Sample project from here, use the Speech example.
https://github.com/GoogleCloudPlatform/android-docs-samples/tree/master/speech/Speech
Setup a google cloud project, enable the Speech API, and link it to
your gmail account's billing (you get 60min of free speech recognition
every month).
Generate an authentication json, and put it into the "raw" folder of
the sample project.
Setup Google cloud on your computer and obtain an access token.
Insert that access token on your SpeechService.java class.
*Documentation on steps 3 and 4:
https://cloud.google.com/speech/docs/getting-started
*If you run into problems when trying to mimic the sample project into your own project, check this:
Cannot import com.google.cloud.speech.v1.SpeechGrpc in Android
The exact steps are too long to list, I can't even remember them all, if you run into specific trouble let me know.

Class variable not changing in IF or Switch statements

Seems simple, but I can't get it to work. I have a public class string variable that should change within a if or switch statement. I haven't declared the variable inside the statement so it should change given the scope, no? But it only reads "FROM" and when I do go to change it in the if statement that applies, it does change to "TO" but only in that instance and reverts back to "FROM". I would pass it along the methods, but the full code is more cluttered and I don't think it's possible to do so.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String typeOfText = "FROM";
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantRequest) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.faboptions_favorite) {
Toast.makeText(MainActivity.this, "FROM", Toast.LENGTH_SHORT).show();
typeOfText = "FROM";
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else if (view.getId() == R.id.faboptions_textsms) {
Toast.makeText(MainActivity.this, "TO", Toast.LENGTH_SHORT).show();
typeOfText = "TO";
Log.d("VARIABLE","" + typeOfText);
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else {
typeOfText = "FROM";
Toast.makeText(MainActivity.this, "Share", Toast.LENGTH_SHORT).show();
createDialogSaveInfo();
}
}
private void createDialogSaveInfo() {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.dialog_confirm_address_scan);
//Establish Dialog Views
Button submit = (Button) dialog.findViewById(R.id.button_dialog_scanner_submit);
Button cancel = (Button) dialog.findViewById(R.id.button_dialog_scanner_cancel);
final EditText fromEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_from);
final EditText toEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_to);
//Set text from captured strings in surface view
fromEditText.setText(fromAddress);
toEditText.setText(toAddress);
//Setup listeners
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO save info to realm
saveLabelInfoIntoRealm(fromEditText.getText().toString(), toEditText.getText().toString());
dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
private void saveLabelInfoIntoRealm(final String from, final String to) {
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Package userPackage = realm.createObject(Package.class, 0);
userPackage.setFromAddress(from);
userPackage.setToAddress(to);
}
});
}
private int getPrimaryKey() {
try {
return realm.where(Package.class).max("primaryKey").intValue() + 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
}
private void configureListeners() {
fabOptions.setOnClickListener(this);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
if (path == null) {
Log.d("TAG", "" + path.toString());
}
return Uri.parse(path);
}
private void cropPicFile(Bitmap file) {
Uri imageToCrop = getImageUri(this, file);
CropImage.activity(imageToCrop)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri photo = result.getUri();
readImage(photo);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void readImage(Uri photo) {
StringBuilder stringBuilder = new StringBuilder();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photo);
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap)
.build();
final SparseArray<TextBlock> items = textRecognizer.detect(imageFrame);
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
Log.d("VARIABLE","" + typeOfText);
if (typeOfText.equals("FROM")) {
fromAddress = stringBuilder.toString();
} else if (typeOfText.equals("TO")){
toAddress = stringBuilder.toString();
}
}
}
The reason the code keeps reverting is because the call to readImage() is in onActivityResult() which recreates the activity when called. So basically, you are getting a fresh object, and the onTypeText() is reinitialized. onActivityResult() is basically a callback from your previous activity.
Your onClick() is not being called due you don't assign clicklistener to R.id.faboptions_favorite and the other View
in onCreate add :
findViewById(R.id.faboptions_favorite).setOnClickListener(this);
and same for the other view.

Taking index of a string

Hello I have an edittext and an button.
I want when the user enters a number by pressing the number to be taken and put a bet on the index penultimate number.
Basically, what should I do? Thank you.
I try to do this with the following code:
public class BarcodScanner extends AppCompatActivity implements OnClickListener {
private Button scanBtn;
private Button nextLevel;
private EditText formatTxt, contentTxt;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scanner);
scanBtn = (Button)findViewById(R.id.scan_button);
nextLevel =(Button)findViewById(R.id.btn_enter);
textView = (TextView) findViewById(R.id.view1);
formatTxt = (EditText) findViewById(R.id.scan_format);
contentTxt = (EditText) findViewById(R.id.scan_content);
nextLevel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String inn = formatTxt.getText().toString();
int length_s = inn.length();
char m = inn.charAt(length_s - 2);
if ( m == 1){
Toast.makeText(BarcodScanner.this, "قبض آب",Toast.LENGTH_LONG).show();
}
}
});
scanBtn.setOnClickListener(this);
}
public void onClick(View v){
if(v.getId()==R.id.scan_button){
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
if (scanContent != null) {
formatTxt.setText(scanContent.substring(0, 13));
contentTxt.setText(scanContent.substring(18));
}
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}

zxing bar code scanner is not returning results

I am trying to make this app to scan for a book's ISBC and then make a http request to fetch for the book's title and other details.
I got the app working in terms of initiating the camera with rootView.findViewById(R.id.scan_button)..... . Now I want to log the bar code and the code format to make sure it's working in onActivityResult but it's not logging or making a toast. The camera activity closes after the camera focuses on the code and returns to the view where I have the button to initiate the scan function but doesn't log anything or making any toast. I used this tutorial - http://code.tutsplus.com/tutorials/android-sdk-create-a-barcode-reader--mobile-17162 - earlier to see how zXing works and the tutorial worked perfectly and now I'm trying to implement some of the codes.
rootView.findViewById(R.id.scan_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
scanIntegrator.setBeepEnabled(true);
scanIntegrator.setBarcodeImageEnabled(true);
scanIntegrator.setPrompt("Scan a barcode");
scanIntegrator.initiateScan();
}
});
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
Log.i("FORMAT ", scanFormat);
Log.i("CONTENT", scanContent);
Log.i("xZing", "contents: "+scanContent+" format: "+scanFormat);
Toast.makeText(getActivity(), "FORMAT " + scanFormat + " CONTENT " + scanContent, Toast.LENGTH_LONG).show();
}else{
Toast toast = Toast.makeText(getActivity(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
full code
public class AddBook extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "INTENT_TO_SCAN_ACTIVITY";
private EditText ean;
private final int LOADER_ID = 1;
private View rootView;
private final String EAN_CONTENT="eanContent";
private static final String SCAN_FORMAT = "scanFormat";
private static final String SCAN_CONTENTS = "scanContents";
private String mScanFormat = "Format:";
private String mScanContents = "Contents:";
private Button scanBtn;
private TextView formatTxt, contentTxt;
public AddBook(){
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(ean!=null) {
outState.putString(EAN_CONTENT, ean.getText().toString());
}
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_add_book, container, false);
ean = (EditText) rootView.findViewById(R.id.ean);
formatTxt = (TextView)rootView.findViewById(R.id.scan_format);
contentTxt = (TextView)rootView.findViewById(R.id.scan_content);
ean.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//no need
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//no need
}
#Override
public void afterTextChanged(Editable s) {
String ean = s.toString();
//catch isbn10 numbers
if (ean.length() == 10 && !ean.startsWith("978")) {
ean = "978" + ean;
}
if (ean.length() < 13) {
clearFields();
return;
}
//Once we have an ISBN, start a book intent
Intent bookIntent = new Intent(getActivity(), BookService.class);
bookIntent.putExtra(BookService.EAN, ean);
bookIntent.setAction(BookService.FETCH_BOOK);
getActivity().startService(bookIntent);
AddBook.this.restartLoader();
}
});
rootView.findViewById(R.id.scan_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
scanIntegrator.setBeepEnabled(true);
scanIntegrator.setBarcodeImageEnabled(true);
scanIntegrator.setPrompt("Scan a barcode");
scanIntegrator.initiateScan();
}
});
rootView.findViewById(R.id.save_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ean.setText("");
}
});
rootView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent bookIntent = new Intent(getActivity(), BookService.class);
bookIntent.putExtra(BookService.EAN, ean.getText().toString());
bookIntent.setAction(BookService.DELETE_BOOK);
getActivity().startService(bookIntent);
ean.setText("");
}
});
if(savedInstanceState!=null){
ean.setText(savedInstanceState.getString(EAN_CONTENT));
ean.setHint("");
}
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
Log.i("FORMAT ", scanFormat);
Log.i("CONTENT", scanContent);
Log.i("xZing", "contents: "+scanContent+" format: "+scanFormat);
Toast.makeText(getActivity(), "FORMAT " + scanFormat + " CONTENT " + scanContent, Toast.LENGTH_LONG).show();
}else{
Toast toast = Toast.makeText(getActivity(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
// Checks for network connection
public boolean checkNetworkConnection(){
ConnectivityManager cm =
(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
private void restartLoader(){
getLoaderManager().restartLoader(LOADER_ID, null, this);
}
#Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
if(ean.getText().length()==0){
return null;
}
String eanStr= ean.getText().toString();
if(eanStr.length()==10 && !eanStr.startsWith("978")){
eanStr="978"+eanStr;
}
return new CursorLoader(
getActivity(),
AlexandriaContract.BookEntry.buildFullBookUri(Long.parseLong(eanStr)),
null,
null,
null,
null
);
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data) {
if (!data.moveToFirst()) {
return;
}
String bookTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.TITLE));
((TextView) rootView.findViewById(R.id.bookTitle)).setText(bookTitle);
String bookSubTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.SUBTITLE));
((TextView) rootView.findViewById(R.id.bookSubTitle)).setText(bookSubTitle);
String authors = data.getString(data.getColumnIndex(AlexandriaContract.AuthorEntry.AUTHOR));
String[] authorsArr = authors.split(",");
((TextView) rootView.findViewById(R.id.authors)).setLines(authorsArr.length);
((TextView) rootView.findViewById(R.id.authors)).setText(authors.replace(",","\n"));
String imgUrl = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.IMAGE_URL));
if(Patterns.WEB_URL.matcher(imgUrl).matches()){
new DownloadImage((ImageView) rootView.findViewById(R.id.bookCover)).execute(imgUrl);
rootView.findViewById(R.id.bookCover).setVisibility(View.VISIBLE);
}
String categories = data.getString(data.getColumnIndex(AlexandriaContract.CategoryEntry.CATEGORY));
((TextView) rootView.findViewById(R.id.categories)).setText(categories);
rootView.findViewById(R.id.save_button).setVisibility(View.VISIBLE);
rootView.findViewById(R.id.delete_button).setVisibility(View.VISIBLE);
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader) {
}
private void clearFields(){
((TextView) rootView.findViewById(R.id.bookTitle)).setText("");
((TextView) rootView.findViewById(R.id.bookSubTitle)).setText("");
((TextView) rootView.findViewById(R.id.authors)).setText("");
((TextView) rootView.findViewById(R.id.categories)).setText("");
rootView.findViewById(R.id.bookCover).setVisibility(View.INVISIBLE);
rootView.findViewById(R.id.save_button).setVisibility(View.INVISIBLE);
rootView.findViewById(R.id.delete_button).setVisibility(View.INVISIBLE);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
activity.setTitle(R.string.scan);
}
}
enter code here
The problem is that I was using IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity()), which effected on onActivityResult being called at the Activity/Parent level. And since onActivityResult doesn't do anything, nothing happened. And since that I am using fragments, the child/fragment's onActivityResult wasn't being called.
To fix it, I replace IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity()) in onClick to IntentIntegrator.forSupportFragment(AddBook.this), with "AddBook.this" in reference to the fragment so onActivityResult in the fragment is called, as opposed to one in Activity. .
:)
Cheers!

Categories

Resources