Sending tweets using Android - android

I want to send a tweet from Android.I have executed the following code.But I am not bale to send any tweets.Avtually the button I created is not working.Can anybody tel me wats the prob?
This is my code..
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.os.Bundle;
public class TwidgitPublicIntent extends Activity implements OnClickListener {
private static final int TWIDGIT_REQUEST_CODE = 2564;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button)findViewById(R.id.tweet_button)).setOnClickListener(this);
((Button)findViewById(R.id.mention_button)).setOnClickListener(this);
((Button)findViewById(R.id.retweet_button)).setOnClickListener(this);
((Button)findViewById(R.id.message_button)).setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.tweet_button:
// Standard tweet
Intent tIntent = new Intent("com.disretrospect.twidgit.TWEET");
tIntent.putExtra("com.disretrospect.twidgit.extras.MESSAGE", "_message_in_here_");
try {
this.startActivityForResult(tIntent, TWIDGIT_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// If Twidgit is not installed
}
break;
case R.id.mention_button:
// Mention
Intent mIntent = new Intent("com.disretrospect.twidgit.MENTION");
mIntent.putExtra("com.disretrospect.twidgit.extras.TO", "_username_to_xmention_");
mIntent.putExtra("com.disretrospect.twidgit.extras.MESSAGE", "_message_in_here_");
try {
this.startActivityForResult(mIntent, TWIDGIT_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// If Twidgit is not installed
}
break;
case R.id.retweet_button:
// Retweet a tweet
Intent rtIntent = new Intent("com.disretrospect.twidgit.RETWEET");
rtIntent.putExtra("com.disretrospect.twidgit.extras.MESSAGE", "_message_in_here_");
rtIntent.putExtra("com.disretrospect.twidgit.extras.VIA", "_original_author_of_tweet_name_");
try {
this.startActivityForResult(rtIntent, TWIDGIT_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// If Twidgit is not installed
}
break;
case R.id.message_button:
// Send DM
Intent dmIntent = new Intent("com.disretrospect.twidgit.DIRECT_MESSAGE");
dmIntent.putExtra("com.disretrospect.twidgit.extras.TO", "_username_to_send_dm_to_");
dmIntent.putExtra("com.disretrospect.twidgit.extras.MESSAGE", "_message_in_here_");
try {
this.startActivityForResult(dmIntent, TWIDGIT_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// If Twidgit is not installed
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check result code
if(resultCode == Activity.RESULT_OK) {
// Check requestCode
switch(requestCode) {
case TWIDGIT_REQUEST_CODE:
// Handle successful return
break;
}
} else if(resultCode == Activity.RESULT_CANCELED){
// Handle canceled activity
}
}
}

I'm not able to edit your post so i have to put this in an answer: could you provide more details about the problem? More precisely, what do you mean by "the button is not working?" Is anything happening when you click the button, or not? If nothing happens, might be that you run into the ActivityNotFoundException. Since it is catched, but no action is taken, it's transparent. Have you tried debugging, with a break point on the onClick method?

Related

How to solve this Android request keyword error?

MainActivity.java :
package com.example.dell.capcrop;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
final int CAMERA_CAPTURE=1;
private Uri picUri;
final int PIC_CROP=2;
Bundle bundle;
Bitmap bitmap;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureBtn=(Button)findViewById(R.id.capture_btn);
captureBtn.setOnClickListener(this);
}
#Override
public void onClick(View v){
if (v.getId()==R.id.capture_btn){
try {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent,CAMERA_CAPTURE);
}
catch (ActivityNotFoundException anfe){
String errorMessage ="Whoops - your device doesn't support capturing image";
Toast toast=Toast.makeText(this,errorMessage,Toast.LENGTH_SHORT);
toast.show();
}
}
}
private void performCrop() {
try{
Intent cropIntent=new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri,"image/*");
cropIntent.putExtra("crop","true");
cropIntent.putExtra("aspectX",1);
cropIntent.putExtra("aspectY",1);
cropIntent.putExtra("outputX",256);
cropIntent.putExtra("outputY",256);
cropIntent.putExtra("return_data",true);
startActivityForResult(cropIntent,PIC_CROP);
}
catch (ActivityNotFoundException anfe)
{
String errorMessage="Whoops - your device doesn't support capturing image";
Toast toast=Toast.makeText(this,errorMessage,Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request&&resultCode==RESULT_OK)
{
bundle=data.getExtras();
bitmap=(Bitmap)bundle.get("data");
img.setImageBitmap(bitmap);
Thread thread=new Thread()
{
#Override
public void run() {
try {
sleep(2000);
Intent intent=new Intent(getApplicationContext(),result.class);
bundle.putParcelable("bmp",bitmap);
intent.putExtras(bundle);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
picUri = data.getData();
performCrop();
} else if (requestCode == PIC_CROP) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView) findViewById(R.id.picture);
picView.setImageBitmap(thePic);
}
}
}
}
My app is basically a sign language interpreter and I need to remove an error. Here is the code in which there is multiple onactivityresult() definition which is causing error. I do some changes but all in vain. In this code the mobile camera capture image and show a frame in which the user crop the required part of image and show in the next activity.

How can i get the output as just the city name instead of whole address in my App when using Google API?

Even when the user search for any locality in a city, the output should be name of the city.
package com.example.rajat.location;
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.TextView;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.ui.PlaceAutocomplete;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/*
* In this method, Start PlaceAutocomplete activity
* PlaceAutocomplete activity provides--
* a search box to search Google places
*/
public void findPlace(View view) {
try {
Intent intent =
new PlaceAutocomplete
.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.build(this);
startActivityForResult(intent, 1);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
// A place has been received; use requestCode to track the request.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// retrive the data by using getPlace() method.
Place place = PlaceAutocomplete().getPlace(this, data);
Log.e("Tag", "Place: " + place.getAddress() + place.getPhoneNumber());
((TextView) findViewById(R.id.searched_address))
.setText(place.getName()+",\n"+
place.getAddress() +"\n" + place.getPhoneNumber());
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
Log.e("Tag", status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
} }
You need to use a key specific to the Google Places API to retrieve the city name from your JSON response object.
This link shows the JSON response you are getting back (the key value pairs)
https://developers.google.com/places/web-service/details
Inspect your JSON response object (which i believe is your "Place" object).
Run a debug statement on this line of code. Place place = PlaceAutocomplete().getPlace(this, data);
Once you know the key for City, grab the City value and only populate your UI with the City value.

calling another class functions from one class on button click in android

I am making an app with various activities and each activity uses the camera function which is defined in another class. I want that in each activity when the camera button is clicked the camera class is called.
This is my main class:-
package com.example.ishan.complainbox;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.lang.String;
public class Crime extends MainActivity implements View.OnClickListener
{
camera cam=new camera();
EditText str,city,pn,det;
Button save,pic;
crimeDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
// Get References of Views
str = (EditText) findViewById(R.id.str);
city = (EditText) findViewById(R.id.city);
pn = (EditText) findViewById(R.id.pin);
det = (EditText) findViewById(R.id.detail);
save = (Button) findViewById(R.id.save);
pic=(Button) findViewById(R.id.uploadpic);
dbHandler = new crimeDBHandler(this, null, null, 1);
}
public void onClick(View view) {
String street = str.getText().toString();
String cty = city.getText().toString();
String pin = pn.getText().toString();
String detail = det.getText().toString();
// check if any of the fields are vaccant
if(str.equals("")||city.equals("")||pn.equals("")||det.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vacant",
Toast.LENGTH_LONG).show();
return;
}
// check if both passwords match
else
{
// Save the Data in Database
dbHandler.insertEntry(street,cty,pin,detail);
Toast.makeText(getApplicationContext(), "Complaint Successfully
Filed ", Toast.LENGTH_LONG).show();
}
}
};
.....and this is the camera class..:-
package com.example.ishan.complainbox;
/**
* Created by ishan on 13/04/2017.
*/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class camera extends MainActivity{
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView ivImage;
private String userChosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
btnSelect = (Button) findViewById(R.id.uploadpic);
btnSelect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ivImage = (ImageView) findViewById(R.id.imgView);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[]
permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED)
{
if(userChosenTask.equals("Take Photo"))
cameraIntent();
else if(userChosenTask.equals("Choose from Library"))
galleryIntent();
} else {
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(camera.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(camera.this);
if (items[item].equals("Take Photo")) {
userChosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChosenTask ="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new
File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() +
".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm =
MediaStore.Images.Media.getBitmap(getApplicationContext().
getContentResolver(),
data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
}
}
This can be achieved through regular inter-activity communication mechanisms like passing intents or using broadcast receivers. I would suggest using intents - Refer this basic example from Android doc: https://developer.android.com/training/basics/firstapp/starting-activity.html
EDIT
Response to OP's question in comment-
You have to save the image file to FS in your Camera Class and pass the file name as an Extra with the intent to your Crime class. Since you are dealing with storage your Apps's manifest now would need additional permissions. I would recommend you go through this thread: Camera is not saving after taking picture

PayPal Android SDK keeps on "checking my device"

I am trying to use the PayPal Android SDK (https://github.com/paypal/PayPal-Android-SDK) in my App. I used the same methods like their example. All parameters like ClientID are the correct ones from my PayPal sandbox. When I press the button that calls the PayPal activity, a screen captioned "Checking this device...", a spinning ProgressBar and a PayPal Logo appears on the screen. I let this screen like this for hours, but nothing happend.
Thanks for help and excuse me for my bad english, it's my first question here and I am from Germany...
There is now output in LogCat From PayPal or its Activity. Here is my code:
package de.jimpachnet.xaver;
import java.math.BigDecimal;
import org.json.JSONException;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class Premium extends Activity {
private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_NO_NETWORK;
// note that these credentials will differ between live & sandbox environments.
private static final String CONFIG_CLIENT_ID = "XXXXXXXXXXXX";
// when testing in sandbox, this is likely the -facilitator email address.
private static final String CONFIG_RECEIVER_EMAIL = "XXXXXXXXX-facilitator#t-online.de";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_premium);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
startService(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.premium, menu);
return true;
}
public void onButtonPayPal (View view) {
onBuyPressed();
}
public void onBuyPressed() {
PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal("2.11"), "USD", "StXaverAppPremiumAccount");
Intent intent = new Intent(this, PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, "test");
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i("paymentExample", confirm.toJSONObject().toString(4));
} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("paymentExample", "Nope");
}
else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
Log.i("paymentExample", "An invalid payment was submitted. Please see the docs.");
}
}
#Override
public void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
}

Would someone please straighten me out with this Android voice recognition class?

I'm analyzing this Voice Recognizer class and need help understanding this line in the code. What is the role of the following line? Does it create a list of all of the activities on the android platform loaded on the device? I especially find the resolve info bit confusing...
List activities = pm.queryIntentActivities(new Intent(
Here is the code used in context
package com.example.voicerecognitionactivity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class VoiceRecognitionActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private EditText metTextHint;
private ListView mlvTextMatches;
private Spinner msTextMatches;
private Button mbtSpeak;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
metTextHint = (EditText) findViewById(R.id.etTextHint);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
}
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);
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Specify the calling package to identify your application
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
// Display an hint to the user about what he should say.
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText()
.toString());
// Given an hint to the recognizer about what the user is going to say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
// If number of Matches is not selected then return show toast message
if (msTextMatches.getSelectedItemPosition() == AdapterView.INVALID_POSITION) {
Toast.makeText(this, "Please select No. of Matches from spinner",
Toast.LENGTH_SHORT).show();
return;
}
int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()
.toString());
// Specify how many results you want to receive. The results will be
// sorted where the first result is the one with higher confidence.
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);
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.isEmpty()) {
// If first Match contains the 'search' word
// Then start web search.
if (textMatchList.get(0).contains("search")) {
String searchQuery = textMatchList.get(0).replace("search",
" ");
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
search.putExtra(SearchManager.QUERY, searchQuery);
startActivity(search);
} else {
// populate the Matches
mlvTextMatches
.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
textMatchList));
}
}
//Result code for various error.
}else 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);
}
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
This, i think, is the simplest way of checking if voice recognition is present or not:
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_LONG);
t.show();
}
ANd after that:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
et_task_notes.setText(text.get(0));
}
break;
}
}
}

Categories

Resources