I'm using setVisibility() to hide some UI components at onStart(), with the aim of making them reappear under certain conditions at onActivityResult().
I have set variables as global variable, and assigned to the component at onCreate().
Code to make the component invisible works correctly, such as auth_btn.setVisibility(View.INVISIBLE);
However, at onActivityResult(), auth_btn.setVisibility(View.VISIBLE); does not make the button reappear.
Code (from pastebin in the comments):
private Button auth_btn = null;
private Button newAcc_btn = null;
private EditText mEdit = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up the window layout
setContentView(R.layout.main);
//instance of database adapter
db = new DBAdapter(this);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
auth_btn = (Button) findViewById(R.id.btn_auth);
mEdit = (EditText)findViewById(R.id.text_username);
newAcc_btn = (Button) findViewById(R.id.btn_newAcc);
//read every entry from database
db.load();
}
#Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the session
} else {
setupSession();
}
}
private void setupSession () {
//Authenticate
auth_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
out.write(AUTHENTICATE);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
authenticate();
}
});
//Create new account
newAcc_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try{
out.write(NEWACCOUNT);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
newAccount();
}
});
//Scan QR Code
Button scan = (Button) findViewById(R.id.btn_scan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, SCAN_QR_CODE);
}
});
auth_btn.setVisibility(View.INVISIBLE);
newAcc_btn.setVisibility(View.INVISIBLE);
mEdit.setVisibility(View.INVISIBLE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == SCAN_QR_CODE) {
if (resultCode == RESULT_OK) {
//Successful scan
processQR(intent.getStringExtra("SCAN_RESULT"));
//String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); //format of the code
//Toast.makeText(this, contents, Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Scan failed!", Toast.LENGTH_SHORT).show();
}
}
if (requestCode == REQUEST_ENABLE_BT) {
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupSession();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(this, "Bluetooth cannot be enabled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
public void processQR (String content) {
String[] contents = content.split(" ");
if (contents.length != 3) {
Log.e(TAG, "Not well formed QR Code");
}
else {
appKey = contents[APPKEY];
macAdd = contents[MACADR];
my_uuid = UUID.fromString(contents[UUID_STR]);
Log.d(TAG, macAdd);
String appName = db.getAppName(appKey);
Log.d(TAG, appName);
if (appName == null)
return;
Toast.makeText(this, appName, Toast.LENGTH_SHORT).show();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAdd);
try {
bt = device.createInsecureRfcommSocketToServiceRecord(my_uuid);
bt.connect();
in = bt.getInputStream();
out = bt.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
Log.d(TAG, "Set new acc visible");
mEdit = (EditText)findViewById(R.id.text_username);
mEdit.setVisibility(View.VISIBLE);
newAcc_btn.setVisibility(View.VISIBLE);
if (db.appAccounts(appKey).getCount() > 0)
auth_btn.setVisibility(View.VISIBLE);
}
}
onStart() is called each time the activity is visible. After pressing the scan button, the intent is executed, then the buttons are set to VISIBLE at onActivityResult().
After which, the activity is visible again, causing onStart() to be executed, therefore making the buttons INVISIBLE again.
Related
Scenario: App Scans a QR code using Zxing library. When scanning usecase is initiated, app’s main activity launches activity A which initializes the UI , checks the basic permissions (like camera access,) , it then launches activity B for scanning the image. Scanning is done two ways, one is through camera and another is by picking an image from gallery.
What works: Scanning through camera and scanning valid QR code files from the gallery works
Issue: After scanning an invalid QR code from gallery. On pressing back button on the toolbar of activity A, app hangs. On the run window, this message is displayed “SQLiteConnectionPool: The connection pool for database '+appname_dbV8' has been unable to grant a connection to thread 2 (main) with flags 0x5 for 16.006 seconds
Activity A:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
Toolbar toolbar = getActionBarToolbar();
toolbar.setTitle("Scan");
toolbar.setNavigationIcon(R.drawable.ic_up);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View view) {
navigateUpToFromChild(ActivityA.this,
Intent.makeMainActivity(new ComponentName(ActivityA.this,
mymainactivity.class)));
}
});
setEventListeners();
}
private void initiateScan () {
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setCaptureActivity(ActivityB.class);
integrator.setOrientationLocked(false);
integrator.initiateScan();
}
private void setEventListeners () {
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "Scan cancelled!", Toast.LENGTH_LONG).show();
finish();
} else {
String decoderesult = "";
try {
decoderesult = URLDecoder.decode(result.getContents(), "UTF-8");
} catch (UnsupportedEncodingException e) {
//Log error message
} catch (IllegalArgumentException i) {
//log error message
Toast.makeText(this, "Unsupported scan Code!", Toast.LENGTH_LONG).show();
finish();
}
if (decoderresult is a valid scan code) {
//parse and handle the scan code
} else { //handle invalid QR code
Toast.makeText(this, "Invalid QR Code!", Toast.LENGTH_LONG).show();
finish();
}
}
} else
{
super.onActivityResult(requestCode, resultCode, data);
}
}
Activity B:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
toolbar.setTitle("Scan");
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
barcodeScannerView = (DecoratedBarcodeView) findViewById(R.id.zxing_barcode_scanner);
barcodeScannerView.setTorchListener(this);
switchFlashlightButton = (ImageView) findViewById(R.id.switch_flashlight);
// if the device does not have flashlight in its camera,
// then remove the switch flashlight button...
if (!hasFlash()) {
switchFlashlightButton.setVisibility(View.GONE);
}
capture = new CaptureManager(this, barcodeScannerView);
capture.initializeFromIntent(getIntent(), savedInstanceState);
capture.decode();
}
//XML file has the corresponding onclick for gallery_browse
public void gallery_browse(View view){
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, PICK_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (data == null || data.getData() == null) {
Log.e("TAG", "The uri is null, probably the user cancelled the image selection process using the back button.");
return;
}
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
if (bitmap == null) {
Toast.makeText(this, "Not a valid QR code", Toast.LENGTH_LONG).show();
return;
}
int width = bitmap.getWidth(), height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
bitmap.recycle();
bitmap = null;
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
BinaryBitmap bBitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader reader = new MultiFormatReader();
String data = "";
Result result;
Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
try {
result = reader.decode(bBitmap, hints);
resultdata = result.getText();
} catch (IllegalArgumentException i) {
} catch (NotFoundException e) {
ULog.e("Not found exception in class " + getClass().getName(), e.getMessage());
RemoteLogger.b(e.getMessage());
}
if (resultdata is valid) {
// Parse and process the data
}else {
Toast.makeText(this, "Seems to be an Invalid QR Code. Try another QR code!!", Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
Log.e("TAG", "can not open file" + uri.toString(), e);
}
}
else{
super.onActivityResult(requestCode, resultCode, data);
}
}
Found the issue. In the code which I have provided here, in activity B, after decode, in Notfoundexception block there was a remote logger code which was causing the app to hang and later crash.
This was the part of code that was causing the issue:
ULog.e("Not found exception in class " + getClass().getName(), e.getMessage());
RemoteLogger.b(e.getMessage());
I want to make an application in the way that when I speak, can answer me without the necessity of press any button. I want that my recordings guard on a string, and then depending of the record, the TTS can answer diferent things. This is my source code.
protected static final int RESULT_SPEACH =1;
private Button record, speak;
TextToSpeech t1;
String SpokedText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mai);
record = (Button) findViewById(R.id.record);
speak = (Button) findViewById(R.id.speak);
speak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reconize = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
try {
startActivityForResult(reconize, RESULT_SPEACH);
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(), "Your divece cannot execute this kind of operation", Toast.LENGTH_LONG);
t.show();
}
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode,resultCode,Data);
switch (requestCode) {
case RESULT_SPEACH: {
if (resultCode == RESULT_OK && null != Data) {
final String spoked = (RecognizerIntent.EXTRA_RESULTS);
if (spoked == "Good Morning") {
String SpokedText= "Good Morning";
t1.speak(SpokedText, TextToSpeech.QUEUE_FLUSH, null);
} else {
if (spoked== "I need your help") {
String SpokedText= "Alright sir";
t1.speak(SpokedText, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.getDefault());
}
}
});
}}
This is a strange problem that only started yesterday, and I can't think of anything in my code that would have changed anything. I'm setting up a User on Parse, which includes profile information. Now, for some reason (and I can't find ANYTHING about this particular issue online) when I submit the user profile information, while all of the related fields in the app are correctly retrieving the data from Parse (which means it's out there)... when I look at the User on Parse.com all of the fields are marked as (undefined). This is most likely a JSON error, but I can't figure out where it is coming from? Here's my code for the user to submit their profile... see anything? I will add... The user has already signed up in another activity preceding this one.
public class CreateProfileActivity extends AppCompatActivity {
private ParseUser mCurrentUser;
private ParseFile mUserProfilePic;
private EditText mFirstName;
private EditText mLastName;
private EditText mBusinessName;
private EditText mBusinessCategory;
private EditText mBusinessDescription;
private ImageView mProfilePicImageView;
private Button mSubmitInfoButton;
private Uri mProfilePicUri;
private Bitmap mProfilePicBitmap;
private byte[] mProfilePicByteArray;
private boolean mProfilePic = false;
private ProgressBar mProgressBar;
private CirclePhotoTransform mCirclePhotoTransform = new CirclePhotoTransform();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
//INITIALIZE ALL UI ELEMENTS...
mFirstName = (EditText) findViewById(R.id.firstNameField);
mLastName = (EditText) findViewById(R.id.lastNameField);
mBusinessName = (EditText) findViewById(R.id.businessNameField);
mBusinessCategory = (EditText) findViewById(R.id.businessCategoryField);
mBusinessDescription = (EditText) findViewById(R.id.businessDescriptionField);
mProfilePicImageView = (ImageView) findViewById(R.id.profilePicImageView);
mSubmitInfoButton = (Button) findViewById(R.id.submitProfileButton);
mProgressBar = (ProgressBar) findViewById(R.id.createProfileProgress);
mProgressBar.setVisibility(View.INVISIBLE);
//INITIALIZE PARSE USER
mCurrentUser = ParseUser.getCurrentUser();
mProfilePicImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectProfilePicture();
}
});
mSubmitInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProgressBar.setVisibility(View.VISIBLE);
if (mProfilePic) {
mUserProfilePic = new ParseFile(mCurrentUser.getUsername() + "ProfilePicture.png", mProfilePicByteArray);
mUserProfilePic.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
submitUserProfile();
} else {
Toast.makeText(CreateProfileActivity.this, "There was an error. " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
} else {
mProfilePicBitmap = ((BitmapDrawable) mProfilePicImageView.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mProfilePicBitmap.compress(Bitmap.CompressFormat.PNG, 70, stream);
mProfilePicByteArray = stream.toByteArray();
mUserProfilePic = new ParseFile(mCurrentUser.getUsername() + "ProfilePicture.png", mProfilePicByteArray);
mUserProfilePic.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
submitUserProfile();
} else {
Toast.makeText(CreateProfileActivity.this, "There was an error. " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
});
}
private void submitUserProfile() {
DateFormat formattedDate = new SimpleDateFormat("MMM d, yyyy");
Date date = Calendar.getInstance().getTime();
String creationDate = formattedDate.format(date);
mCurrentUser.put("firstName", mFirstName.getText().toString());
mCurrentUser.put("lastName", mLastName.getText().toString());
mCurrentUser.put("businessName", mBusinessName.getText().toString());
mCurrentUser.put("businessCategory", mBusinessCategory.getText().toString());
mCurrentUser.put("businessDescription", mBusinessDescription.getText().toString());
mCurrentUser.put("itemsSoldCount", 0);
mCurrentUser.put("creationDate", creationDate);
mCurrentUser.put("totalRevenue", "0.00");
mCurrentUser.put("userProfilePic", mUserProfilePic);
mCurrentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
goToHomeScreen();
}
});
}
private void goToHomeScreen() {
Intent intent = new Intent(CreateProfileActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
private void selectProfilePicture() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 5);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 5:
getProfilePic(data);
break;
default:
break;
}
}
}
private void getProfilePic(Intent data) {
mProfilePicUri = data.getData();
try {
mProfilePicBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mProfilePicUri);
mProfilePicBitmap = mCirclePhotoTransform.transform(mProfilePicBitmap);
} catch (IOException e) {
e.printStackTrace();
}
if (mProfilePicBitmap != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mProfilePicBitmap.compress(Bitmap.CompressFormat.PNG, 80, stream);
mProfilePicByteArray = stream.toByteArray();
}
mProfilePicImageView.setImageBitmap(mProfilePicBitmap);
mProfilePic = true;
}
Ok. So I haven't figured out why, so if anyone knows why please tell me why. When I switched the value being stored in mCurrentUser.put("totalRevenue", "0.00"); to mCurrentUser.put("totalRevenue", 0.00); which stores as a Number on Parse.com. I'm not sure why storing the value as a String was nullifying everything else that was being stored but it was. After the change, all the data appears and is saved to Parse.com.
Check exactly what's the error .... ur getting
public void done(ParseException e) {
if (e != null) {
goToHomeScreen();
}
else {
Log.d("Error", "Error: " + e.getMessage());
Toast.makeText(getApplicationContext(), " Error: "+e.getMessage() , Toast.LENGTH_SHORT).show();
}
}
Whenever I start/resume my android phone app, it will prompt me to enable my bluetooth twice, regardless what I choose on the first prompt message. What is wrong with my code?
public class MainActivity extends AppCompatActivity {
// BLE management
private static BluetoothManager btManager;
private static BluetoothAdapter btAdapter;
// Set the enable bluetooth code
private final static int REQUEST_ENABLE_BT = 0;
// String for LogCat documentation
private final static String DEBUG_TAG= "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = btManager.getAdapter();
if (btAdapter != null) {
if (!btAdapter.isEnabled()) {
// Request Bluetooth Adapter to be turned on
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
}
else
{
Log.i(DEBUG_TAG, "No bluetooth available");
}
Button launchReminderButton = (Button) findViewById(R.id.button);
launchReminderButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Launch Reminder
// Used Context's startActivity() method
// Create an intent stating which Activity you would like to
// start
Intent reminder = new Intent(MainActivity.this, Reminder.class);
// Launch the Activity using the intent
startActivity(reminder);
}
}
);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
// check for Bluetooth enabled on each resume
if(btAdapter != null && !btAdapter.isEnabled()){
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onRestart() {
super.onRestart();
}
#Override
public void onDestroy() {
super.onDestroy();
btAdapter = null;
}
#Override
protected void onActivityResult(int request_enable_bt, int result_enable_bt, Intent data)
{
super.onActivityResult(request_enable_bt, result_enable_bt, data);
if(result_enable_bt == RESULT_OK) {
Toast.makeText(this, "Turned On", Toast.LENGTH_SHORT).show();
}
else if (result_enable_bt == RESULT_CANCELED)
{
Toast.makeText(this, "Didn't Turn On", Toast.LENGTH_SHORT).show();
finish();
}
}
Thanks.
Pay attention to the following code,the key is finish() you used here:
#Override
protected void onActivityResult(int request_enable_bt,
int result_enable_bt, Intent data)
{
super.onActivityResult(request_enable_bt, result_enable_bt, data);
if (result_enable_bt == RESULT_OK)
{
Toast.makeText(this, "Turned On", Toast.LENGTH_SHORT).show();
}
else if (result_enable_bt == RESULT_CANCELED)
{
Toast.makeText(this, "Didn't Turn On", Toast.LENGTH_SHORT).show();
finish();
}
}
When you start your app,the system will remind you to turn on your Bluetooth,because your request Bluetooth on in onCreate method.When you deny the request, and the method onActivityResult call back,you will run the following code:
else if (result_enable_bt == RESULT_CANCELED)
{
Toast.makeText(this, "Didn't Turn On", Toast.LENGTH_SHORT).show();
finish();
}
The finish() will finish your Activity,every time when you click your app,when you click deny first time,and then you click deny second time.Every time you got this: onCreate -> onResume.So you get the request to enable your Bluetooth twice!
I know there is like a ton topic and question regarding Voice Recognition and my question might be a stupid one too. but please bear with me guys.
I need to get the result of the speech recognition into an (Editable Text Box) instead of (Array List), the editable text box to allow the user to edit the result , just like a memo.
I found some questions like mine but I could not understand ,I am still a beginner comparing to you guys .
This is the code :
public class AVRScreen extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private ListView mlvTextMatches;
private Button mbtSpeak;
private Button reButton;
private EditText result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vr_screen);
Toast.makeText(this, "Press Speak! to Start Speeking",
Toast.LENGTH_LONG).show();
result = (EditText) findViewById(R.id.out_text);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
reButton = (Button)findViewById(R.id.Replay1);
reButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startActivity(new Intent(v.getContext(),KeyBoard.class));
}
});
checkVoiceRecognition();
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
mbtSpeak.setText("Voice recognizer not present");
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//Start the Voice recognizer activity for the result.
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
mlvTextMatches .setAdapter(new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,textMatchList));
}
}
//Result code for various error.
{
} if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Helper method to show the toast message
**/
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
This is the code after editing :
public class AVRScreen extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private Button mbtSpeak;
private Button reButton;
private EditText myEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vr_screen);
Toast.makeText(this, "Press Speak! to Start Speeking",
Toast.LENGTH_LONG).show();
myEditText = (EditText) findViewById(R.id.out_text);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
reButton = (Button)findViewById(R.id.Replay1);
reButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startActivity(new Intent(v.getContext(),KeyBoard.class));
}
});
checkVoiceRecognition();
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
mbtSpeak.setText("Voice recognizer not present");
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//Start the Voice recognizer activity for the result.
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
myEditText.setText(textMatchList.toString());
// if the above does not look good
// for (String match : textMatchList) {
// myEditText.append(match + "\n"); // or whatever separator you want
// }
}
}
the second try is :
} else {
// populate the Matches
//myEditText.setText(textMatchList.toString());
// if the above does not look good
for (String match : textMatchList) {
myEditText.append(match + "\n"); // or whatever separator you want
}
}
}
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
result.setText(textMatchList.toString());
// if the above does not look good
// for (String match : textMatchList) {
// result.append(match + "\n"); // or whatever separator you want
// }
}