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;
}
}
}
Related
How can you redirect to another activity once the application that was launched by createChooser such as show below is complete?
My attempt below ends up with the second intent being triggered before the createChooser launches. I noticed that when I press the back button on the newly launched activity is when the createChooser appears on the activity I wanted to launch it from.
I also tried to wrap the createChooser in startActivityForResult and then launch the second intent using onActivityResult but the result was the same
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
Intent trackIntent = new Intent(InformContacts.this, TrackOffers.class);
startActivity(trackIntent);
Here's the entire code:
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class InformContacts extends Activity {
private static String ITEM_NAME = "Item name";
private static String ITEM_PRICE = "Item price";
private static String ITEM_PIC_URI = "Item pic uri";
public static final int REQUEST_SEND_EMAIL = 0;
ArrayList<Contact> listContacts;
ListView lvContacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inform_contacts);
listContacts = new ContactFetcher(this).fetchAll();
lvContacts = (ListView) findViewById(R.id.lvContacts);
final ContactsAdapter adapterContacts = new ContactsAdapter(this, listContacts);
lvContacts.setAdapter(adapterContacts);
final Button informButton = (Button) findViewById(R.id.button6);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final String uriSharedPref = preferences.getString(ITEM_PIC_URI, "item pic uri");
informButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList emailsList = adapterContacts.emailsSelected;
String item = preferences.getString(ITEM_NAME, "item name");
Float price = preferences.getFloat(ITEM_PRICE,0);
//May use the uriSharedPref string to embed actual url in email and show recipients like I did with publishing house
String sellingMessage = "Hello,\n\nI'm selling my "+ item +" for KES "+price+".\n\nGet back to me if you're interested in buying.\n\n" + uriSharedPref;
String subject = "Selling my "+item;
sendEmail(emailsList, sellingMessage, subject);
//Intent trackIntent = new Intent(InformContacts.this, TrackOffers.class);
//startActivity(trackIntent);
}
});
}
protected void sendEmail(ArrayList<String> arrayOfEmails, String message, String subject) {
Log.i("Send email", "");
Intent emailIntent = new Intent(Intent.ACTION_SEND);
//First Step: convert ArrayList to an Object array
Object[] objEmails = arrayOfEmails.toArray();
//Second Step: convert Object array to String array
String[] strEmails = Arrays.copyOf(objEmails, objEmails.length, String[].class);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, strEmails);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
PackageManager packageManager = getPackageManager();
List activities = packageManager.queryIntentActivities(emailIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean isIntentSafe = activities.size() > 0;
if(isIntentSafe){
startActivityForResult(Intent.createChooser(emailIntent, "Send mail..."), REQUEST_SEND_EMAIL);
//finish();
Log.i("Done sending email...", "");
}
else{
Toast.makeText(InformContacts.this, "No email app found. Email won't be sent.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
if(requestCode == REQUEST_SEND_EMAIL){
Intent intent = new Intent(this, TrackOffers.class);
startActivity(intent);
}
}
}
}
Try this
Change to:
if(requestCode == REQUEST_SEND_EMAIL){
Intent intent = new Intent(this, TrackOffers.class);
startActivity(intent);
}
Instead of:
if (resultCode == RESULT_OK){
if(requestCode == REQUEST_SEND_EMAIL){
Intent intent = new Intent(this, TrackOffers.class);
startActivity(intent);
}
}
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
I have an activity here. When the user touches the layout to the activity, I want the app to ask the user to give five pieces of information. In order to accomplish this, a series of five voice input prompts come up. Below, I have the code for this:
package com.example.shivamgandhi.gyrosafe;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.Locale;
public class Memory_Test1_Activity extends AppCompatActivity implements View.OnClickListener, View.OnTouchListener {
EditText ed23, ed24, ed25, ed26, ed27;
private final int REQ_CODE_SPEECH_INPUT_TOWN = 100;
private final int REQ_CODE_SPEECH_INPUT_WIN = 101;
private final int REQ_CODE_SPEECH_INPUT_MONTH = 102;
private final int REQ_CODE_SPEECH_INPUT_DAY = 103;
private final int REQ_CODE_SPEECH_INPUT_TEAM = 104;
int n = 1;
Button btnarray[] = new Button[n];
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
RelativeLayout RelativeLayout;
int count = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.memory_test1);
Intent STSintent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
btnarray[0] = (Button)findViewById(R.id.button8);
sharedpreferences = this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
ed23 = (EditText)findViewById(R.id.editText23);
ed24 = (EditText)findViewById(R.id.editText24);
ed25 = (EditText)findViewById(R.id.editText25);
ed26 = (EditText)findViewById(R.id.editText26);
ed27 = (EditText)findViewById(R.id.editText27);
RelativeLayout = (RelativeLayout)findViewById(R.id.RelativeLayout);
for(int i = 0; i <n; i++){
btnarray[i].setOnClickListener(this);
}
RelativeLayout.setOnTouchListener(this);
}
private void promptSpeechInput_town() {
Intent STSintent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
STSintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
STSintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
STSintent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(STSintent, REQ_CODE_SPEECH_INPUT_TOWN);
}
catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
private void promptSpeechInput_win() {
Intent STSintent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
STSintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
STSintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
STSintent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(STSintent, REQ_CODE_SPEECH_INPUT_WIN);
}
catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
private void promptSpeechInput_month() {
Intent STSintent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
STSintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
STSintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
STSintent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(STSintent, REQ_CODE_SPEECH_INPUT_MONTH);
}
catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
private void promptSpeechInput_day() {
Intent STSintent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
STSintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
STSintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
STSintent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(STSintent, REQ_CODE_SPEECH_INPUT_DAY);
}
catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
private void promptSpeechInput_team() {
Intent STSintent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
STSintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
STSintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
STSintent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(STSintent, REQ_CODE_SPEECH_INPUT_TEAM);
}
catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT_TOWN: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result_twn = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
ed23.setText(result_twn.get(0));
promptSpeechInput_win();
}
}
case REQ_CODE_SPEECH_INPUT_DAY:{
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result_day = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
ed26.setText(result_day.get(0));
promptSpeechInput_team();
}
}
case REQ_CODE_SPEECH_INPUT_WIN:{
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result_win = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
ed24.setText(result_win.get(0));
promptSpeechInput_month();
}
}
case REQ_CODE_SPEECH_INPUT_MONTH:{
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result_month = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
ed25.setText(result_month.get(0));
promptSpeechInput_day();
}
}
case REQ_CODE_SPEECH_INPUT_TEAM:{
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result_team = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
ed27.setText(result_team.get(0));
}
}
}
}
#Override
public boolean onTouch(View v, MotionEvent event){
if(v == RelativeLayout && count == 0 ){
promptSpeechInput_town();
count = 1;
return true;
}
else{
return false;
}
}
The problem I am facing is that when I touch the layout, only one of the speech prompts happen, promptSpeechInput_team. How can I make it so that each of the prompts is called?
Edit: I now have each function in OnActivityResult calling eachother. However, I still have the voice input keep going indefinitely.
You need to call promptSpeechInput_win()
in onActivityResult of promptSpeechInput_town
and so on.. Ideally only one voice input can be acquired from the user. Hence you should be initiating the next one onActivityResult of previous voice request.
Also you need be breaking the switch case to avoid all the cases being executed every time.
In my app I want to access contacts from the phone and fill the form with some data getting from the contact. When I am trying to run the Intent, I can see the list of contacts in my phone but it doesn't send any data back and onActivityResult is not being called. Can someone please help me as I am a beginner in android programming.
Here is part of my code :
On click event of a button called 'Contacts'
btn_contacts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
#SuppressWarnings("deprecation")
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
}
});
In onActivityResult in the same activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.e("REcAddress","in activity result");
super.onActivityResult(requestCode, resultCode, data);
if(data!=null){
Log.e("REcAddress","hey");
}
if(requestCode == PICK_CONTACT && resultCode == RESULT_OK){
Uri contactData = data.getData();
Log.e("REcAddress",contactData.toString());
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if(c.moveToFirst()){
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.e("REcAddress",name);
edt_rec_name.setText(name);
}
}
}
I have also attached an image to show the layout of the activity. I want to fill in as many details I can from contacts in the form. There is no error in Logcat too. Please, guide me.
Thanks.
first add permissions:
<uses-permission android:name="android.permission.READ_CONTACTS" />
then call intent on to pick contact on button click
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static int PICK_CONTACT = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button pick = (Button) findViewById(R.id.butpick);
pick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pickContact();
}
});
}
private void pickContact() {
//you have used CONTENT_TYPE and here should be CONTENT_URI
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(reqCode)
{
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.getCount() > 0) {
while (c.moveToNext()) {
String name=c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
edt_rec_name.setText(name);
}
}
}
}
You may not have the right permissions for accessing contacts on the phone. Are you using <uses-permission android:name="android.permission.READ_CONTACTS"/> in your Android Manifest?
Try the following code
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
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?