how to make barcode work with device keys? - java

I am trying to code an inventory app that can work on UROVO DT40 device. I don't know how to code the barcode scanner so that it will work on keystroke and send the result to edittext. I also want to save the data from the adapter and be able to read from a PC. I am still a rookie so I don't know if am doing it the right way. I need some help please. Thanks!!
here's some of the code
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {ArrayList<String>
listitems = new ArrayList<>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextInputEditText input = findViewById(R.id.textInputEditText);
TextInputEditText input1 = findViewById(R.id.textInputEditText1);
ListView listview = findViewById(R.id.listView);
Button saveBtn = findViewById(R.id.saveBtn);
Button btn_annuler = findViewById(R.id.btn_annuler);
Button OK = findViewById(R.id.btn3);
Button btn2 = findViewById(R.id.btn2) ;
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,listitems);
listview.setAdapter(adapter);
input.setShowSoftInputOnFocus(false);
input1.setShowSoftInputOnFocus(false);
OK.setOnClickListener(v -> {
listitems.add(Objects.requireNonNull(input.getText()).toString() + ';' + Objects.requireNonNull(input1.getText()).toString());
adapter.notifyDataSetChanged();
input.setText("");
input1.setText("");
});
btn_annuler.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
input.setText("");
input1.setText("");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.clear();
}
});
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!adapter.toString().equals(""))
{
String data = adapter.toString();
writeToFile(data);
Toast.makeText(MainActivity.this, "Vidage éffectué!", Toast.LENGTH_LONG).show();
}
}
});
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("ficGloba.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

There are code samples on the Urovo github page for the Android SDK, specifically also one for the Scanner
Steps 1 to 4 from from the ScannerManagerDemo.java javadoc describe how you have to setup the Scanner:
1.Obtain an instance of BarCodeReader with ScanManager scan = new ScanManager().
2.Call openScanner to power on the barcode reader.
3.After that, the default output mode is TextBox Mode that send barcode data to the focused text box. User can check the output mode
using getOutputMode and set the output mode using switchOutputMode.
4.Then, the default trigger mode is manually trigger signal. User can check the trigger mode using getTriggerMode and set the trigger mode
using setTriggerMode.
for full completeness, the extracted javacode:
private void initScan() {
mScanManager = new ScanManager();
boolean powerOn = mScanManager.getScannerState();
if (!powerOn) {
powerOn = mScanManager.openScanner();
if (!powerOn) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Scanner cannot be turned on!");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog mAlertDialog = builder.create();
mAlertDialog.show();
}
}
initBarcodeParameters();
}
That should give you enough to get cracking. Godspeed.

Related

How to get JSON data from localhost in Android Studio (RESTful API)

So i've followed some tutorial on YT on how to get JSON object and JSON array of objects from website using URL and it worked. The code is below. Now, i've tried doing the exact same thing with URL of my localhost database, but it didn't work. I didn't get any errors or anything, and i have no idea what is the problem. I'm trying to do some RESTful API, in which the code in java is creating table with data in database, and it works perfectly, it's just that i cannot connect android app to it.
package com.example.motto_app;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
RadioGroup RG;
RadioButton bA, bB, bC, bD;
TextView tA, tB, tC, tD, tQ;
Button bN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//assigning variables to objects in layout
RG = findViewById(R.id.radioGroup);
bA = findViewById(R.id.answerAButton);
bB = findViewById(R.id.answerBButton);
bC = findViewById(R.id.answerCButton);
bD = findViewById(R.id.answerDButton);
tA = findViewById(R.id.answerAText);
tB = findViewById(R.id.answerBText);
tC = findViewById(R.id.answerCText);
tD = findViewById(R.id.answerDText);
tQ = findViewById(R.id.textQuestion);
bN = findViewById(R.id.NextButton);
//on-click listeners
bN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url ="http://localhost:8080/quiz";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
String question = "";
try {
JSONObject cityInfo = response.getJSONObject(0);
question = cityInfo.getString("question");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Question: " + question, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Something wrong", Toast.LENGTH_SHORT).show();
}
});
queue.add(request);
}
});
bA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "AAA", Toast.LENGTH_SHORT).show();
}
});
bB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "BBB", Toast.LENGTH_SHORT).show();
}
});
bC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "CCC", Toast.LENGTH_SHORT).show();
}
});
bD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "DDD", Toast.LENGTH_SHORT).show();
}
});
}
}
Now i just want to add that the only thing that i've changed from the original code from YT is URL and variable names. The code worked perfectly with standard URL. Here is how my localhost looks: http://localhost:8080/quiz
By localhost do you mean the PC you're programming on, or the android device itself?
In the case you mean the Android device itself- you would never use a RESTful service here. You'd just make direct DB calls.
In the case you meant your PC- that isn't localhost. Not to the device. You need to use the actual IP of the device. Even if you're using an emulator, the emulator thinks its a separate machine and has its own IP address- localhost would only go to the emulator. And if its an actual device and not an emulator, you need to have your WIFI set up to allow traffic to that port (assuming your PC is on the same wifi network as your device. If not, its even more complicated).

2 Edit text get currency format(###,###,###) and mines but (crash when clicked on btn mines)

here is the java code :
package com.aliabbasi.mytamrin;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
public class full extends AppCompatActivity {
EditText full_payment, cash_payment,remain_payment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full);
Toast.makeText(this, "مقادیر را با دقت وارد کنید", Toast.LENGTH_LONG).show();
Button btn_cancel = findViewById(R.id.btn_cancel);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent btn_cancel = new Intent(full.this, MainActivity.class);
startActivities(new Intent[]{btn_cancel});
}
});
try {
Button remain_check = findViewById(R.id.remain_btn);
remain_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
full_payment = findViewById(R.id.edt_full_payment);
cash_payment = findViewById(R.id.edt_cash_payment);
remain_payment = (EditText) findViewById(R.id.edt_remain);
Float a = Float.parseFloat(full_payment.getText().toString());
Float b = Float.parseFloat(cash_payment.getText().toString());
Float s = a - b;
String r = Double.toString(s);
remain_payment.setText(r);
}
});
} catch (Exception e) {
Toast.makeText(this, "خطایی رح داده" + e, Toast.LENGTH_LONG).show();
}
try {
EditText editText= (EditText) findViewById(R.id.edt_full_payment);
editText.addTextChangedListener(new MyNumberWatcher(editText));
}
catch (Exception e){
Toast.makeText(this, "ERR"+e, Toast.LENGTH_LONG).show();
}
try {
EditText editText= (EditText) findViewById(R.id.edt_cash_payment);
editText.addTextChangedListener(new MyNumberWatcher(editText));
}
catch (Exception e){
Toast.makeText(this, "ERR"+e, Toast.LENGTH_LONG).show();
}
/*try {
EditText editText= (EditText) findViewById(R.id.edt_remain);
editText.addTextChangedListener(new MyNumberWatcher(editText));
}
catch (Exception e){
Toast.makeText(this, "ERR"+e, Toast.LENGTH_LONG).show();
}*/
}
}
i try the double variable
there is no Error but program crashed when i press the remain_btn.
i check the Debug and find out there is a problem with this:
at com.aliabbasi.mytamrin.full$2.onClick(full.java:45).
andNumberFormatException** but IDK how to solve it.**
and i really like to know how fix this becase i stuck in this about 2 days...
thanks for reading ...
wish the best
code imag
You can do something like this. Remove that comma.
Float a = Float.parseFloat(full_payment.getText().toString().replace(",", ""));

HTML parsing Android Jsoup

im kinda new to android, im trying to use jsoup to parse a html page to gather some info from a page.
i would like to insert a url via pop-up (altertbox) usinga method called loadwebsite:
private void loadWebsite(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Inserisci url sito");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
linkurl = input.getText().toString();
//linkurl="https://"+linkurl;
url123.setText("https://"+linkurl.toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
and a method called getsiteinfo()
private void getinfoWebsite(){
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect(linkurl).get();
String title = doc.title();
Element image = doc.select("img").first();
String imgSrc = image.absUrl("src");
InputStream in = new java.net.URL(imgSrc).openStream();
bitmap = BitmapFactory.decodeStream(in);
builder.append(title).append("\n");
} catch (IOException e){
builder.append("Error :").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
the problem is that when i try to pass a url via textbox i get that error:
03-26 17:22:16.826 26651-26840/it.uninsubria.pdm.htmlparsingjsoup E/AndroidRuntime: FATAL EXCEPTION: Thread-8
Process: it.uninsubria.pdm.htmlparsingjsoup, PID: 26651
java.lang.IllegalArgumentException: Must supply a valid URL
at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:72)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:36)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at it.uninsubria.pdm.htmlparsingjsoup.MainActivity$3.run(MainActivity.java:78)
at java.lang.Thread.run(Thread.java:764)
here is the full code:
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
private Button getBtn;
private TextView result;
private ImageView img;
private Bitmap bitmap;
private Button button2;
private String linkurl = "";
private TextView url123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
img= (ImageView) findViewById(R.id.image2);
url123 =(TextView)findViewById(R.id.url123);
getBtn =(Button) findViewById(R.id.button2); //
getBtn.setOnClickListener(new View.OnClickListener() { // Pulsante "open website
#Override //
public void onClick(View v) {
openWebsite();
}
});
getBtn =(Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadWebsite();
getinfoWebsite();
img.setImageBitmap(bitmap);
}
});
}
//////////////////////////////////////////// -------------------METHODS------------------////////////////////////////////////////////
private void getinfoWebsite(){
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect(linkurl).get();
String title = doc.title();
Element image = doc.select("img").first();
String imgSrc = image.absUrl("src");
InputStream in = new java.net.URL(imgSrc).openStream();
bitmap = BitmapFactory.decodeStream(in);
builder.append(title).append("\n");
} catch (IOException e){
builder.append("Error :").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void openWebsite(){
Uri uriUrl = Uri.parse(String.valueOf(linkurl));
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//pop-up text per caricare link url
private void loadWebsite(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Inserisci url sito");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
linkurl = input.getText().toString();
//linkurl="https://"+linkurl;
url123.setText("https://"+linkurl.toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
The error says that the argument you are passing to Jsoup.connect is not valid (empty). It looks like you creating onClick listener to set value of linkurl, but you are starting parsing thread immediately, i.e. not waiting for linkurl value to be set. You can for example delay execution of the code by inserting this code in the begining of run method inside getinfoWebsite(): while(linkurl.isEmpty()) { Thread.sleep(1000);}

Cannot Export sharedpreferences to CSV Android

Okay So this is an activity class where I am trying to export my sharedPreferences that are saved to a CSV file. This does not work. What am I doing wrong? How do I correctly write the sharedPreferences items to a CSV file?
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Admin extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
Button btViewContacts = (Button)findViewById(R.id.btnViewContacts);
Button btDeleteContacts = (Button)findViewById(R.id.btnDeleteContacts);
Button btExportCSV = (Button)findViewById(R.id.btnExportCSV);
final Context context = this;
final SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(this);
btViewContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Admin.this, Contacts.class));
}
});
btDeleteContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//DISPLAY ALERT DIALOG
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); //show an alertDialog when user selects delete radio button and clicks process, prompt to confirm
//set title
alertDialogBuilder.setTitle("DELETE ALL CONTACTS?");
//set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete ALL acquired contact info?")
.setCancelable(true)
//no button
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) { //if user selects no, close dialog
// TODO Auto-generated method stub
//if clicked this will close the dialog and do nothing.
dialog.cancel();
}
})
//yes button
.setPositiveButton("Yes", new DialogInterface.OnClickListener() { //if user selects yes, clear the shared preferences and display confirmation message when deleted.
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//if this button is clicked it will erase the values in memory
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.commit();
//displays toast message confirming deletion of race info
Toast.makeText(Admin.this, "Contact Info Deleted.", Toast.LENGTH_SHORT).show();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
Map<String, ?> allEntries = sharedPref.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("TAG", entry.getKey() + ": " + entry.getValue().toString());
}
btExportCSV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
generateCsvFile(Environment.getExternalStorageDirectory().getPath());
}
});
}
private void generateCsvFile(String sFileName)
{
final SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(this);
String delimiter = ",";
try
{
FileWriter writer = new FileWriter(sFileName);
writer.append("First Name");
writer.append(',');
writer.append("Last Name");
writer.append(',');
writer.append("Email");
writer.append(',');
writer.append("Phone");
writer.append(',');
writer.append("Address");
writer.append(',');
writer.append("City");
writer.append(',');
writer.append("State");
writer.append(',');
writer.append("Zip");
writer.append('\n');
Map<String, ?> allEntries = sharedPref.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Map<String,?> all = sharedPref.getAll();
Iterator it = all.entrySet().iterator();
Map.Entry pairs = (Map.Entry)it.next();
if (pairs.getKey().toString().startsWith("contactid_")) {
String strContact = sharedPref.getString((String)pairs.getKey(), "");
String[] data = TextUtils.split(strContact, delimiter);
writer.write(strContact);
writer.append('\n');
}
Toast.makeText(Admin.this, "ContAcq's Exported to .CSV.", Toast.LENGTH_SHORT).show();
//generate whatever data you want
writer.flush();
writer.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}

Bypass Android UI error screen Speech Recognition [duplicate]

Is this possible without modify the android APIs?
I've found a article about this.
There's one a comment that I should do modifications to the android APIs.
But it didn't say how to do the modification.
Can anybody give me some suggestions on how to do that?
Thanks!
I've found this article;
SpeechRecognizer
His needs is almost the same as mine.
It is a good reference for me!
I've totally got this problem solved.
I googled a usable sample code from this China website
Here's my source code
package voice.recognition.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import android.util.Log;
public class voiceRecognitionTest extends Activity implements OnClickListener
{
private TextView mText;
private SpeechRecognizer sr;
private static final String TAG = "MyStt3Activity";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button speakButton = (Button) findViewById(R.id.btn_speak);
mText = (TextView) findViewById(R.id.textView1);
speakButton.setOnClickListener(this);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
}
class listener implements RecognitionListener
{
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB)
{
Log.d(TAG, "onRmsChanged");
}
public void onBufferReceived(byte[] buffer)
{
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech()
{
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error)
{
Log.d(TAG, "error " + error);
mText.setText("error " + error);
}
public void onResults(Bundle results)
{
String str = new String();
Log.d(TAG, "onResults " + results);
ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
Log.d(TAG, "result " + data.get(i));
str += data.get(i);
}
mText.setText("results: "+String.valueOf(data.size()));
}
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "onEvent " + eventType);
}
}
public void onClick(View v) {
if (v.getId() == R.id.btn_speak)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
sr.startListening(intent);
Log.i("111111","11111111");
}
}
}
Be sure to delete the annoying Logs after debugging!
Use the SpeechRecognizer interface. Your app needs to have the RECORD_AUDIO permission, and you can then create a SpeechRecognizer, give it a RecognitionListener and then call its startListening method. You will get callbacks to the listener when the speech recognizer is ready to begin listening for speech and as it receives speech and converts it to text.
GAST has a handy abstract class you can use to use the SpeechRecognizer class with very little new code. There is also an example of running the SpeechRecognizer as a background service using this and this
Thanks for posting this! I found it helpful to define the onclick listener in oncreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView) findViewById(R.id.textView1);
MyRecognitionListener listener = new MyRecognitionListener();
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(listener);
findViewById(R.id.button1).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
sr.startListening(intent);
}
});
}
I end up making Github project to convert Text to speech and speech to text without annoying dialog,
https://github.com/hiteshsahu/Android-TTS-STT/tree/master/app/src/main/java/com/hiteshsahu/stt_tts/translation_engine
//SPEECH TO TEXT DEMO
speechToText.setOnClickListener({ view ->
Snackbar.make(view, "Speak now, App is listening", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
TranslatorFactory
.instance
.with(TranslatorFactory.TRANSLATORS.SPEECH_TO_TEXT,
object : ConversionCallback {
override fun onSuccess(result: String) {
sttOutput.text = result
}
override fun onCompletion() {
}
override fun onErrorOccurred(errorMessage: String) {
erroConsole.text = "Speech2Text Error: $errorMessage"
}
}).initialize("Speak Now !!", this#HomeActivity)
})
//TEXT TO SPEECH DEMO
textToSpeech.setOnClickListener({ view ->
val stringToSpeak :String = ttsInput.text.toString()
if (null!=stringToSpeak && stringToSpeak.isNotEmpty()) {
TranslatorFactory
.instance
.with(TranslatorFactory.TRANSLATORS.TEXT_TO_SPEECH,
object : ConversionCallback {
override fun onSuccess(result: String) {
}
override fun onCompletion() {
}
override fun onErrorOccurred(errorMessage: String) {
erroConsole.text = "Text2Speech Error: $errorMessage"
}
})
.initialize(stringToSpeak, this)
} else {
ttsInput.setText("Invalid input")
Snackbar.make(view, "Please enter some text to speak", Snackbar.LENGTH_LONG).show()
}
})

Categories