I am integrating the zxing scanner into my android application and I am coming across a weird situation where the onActivityResult (in the activity initiating the scan) is being called before the scanning intent opens. I have looked at several examples and my code seems to match what I am seeing in many of the tutorials. Here is the code for the activity.
package com.honeydewit;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.honeydewit.adapters.ListItemAdapter;
import com.honeydewit.listeners.OneOffClickListener;
import com.honeydewit.pojos.BasicList;
import com.honeydewit.pojos.ListItem;
public class ListHomeActivity extends BasicActivity{
private ImageButton addItemBtn;
private ImageButton addByScanBtn;
private ArrayList<ListItem> lists = new ArrayList<ListItem>();
public static ListItemAdapter listAdapter;
private TextView headerTxt;
private BasicList basicList;
private ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listshome);
listView =(ListView) findViewById(R.id.list);
basicList = getApplicationContext().getCurrentList();
headerTxt = (TextView)findViewById(R.id.headerTxt);
headerTxt.setText(basicList.getName());
headerTxt.setTypeface(getApplicationContext().getTypeface());
//add button
addItemBtn = (ImageButton)findViewById(R.id.add);
addItemBtn.setOnClickListener(new OneOffClickListener() {
#Override
public void onClick(View v) {
addToList(v, basicList);
}
});
addByScanBtn = (ImageButton)findViewById(R.id.addByScan);
addByScanBtn.setVisibility(View.VISIBLE);
addByScanBtn.setOnClickListener(new OneOffClickListener() {
#Override
public void onClick(View v) {
addToListByScan(v, basicList);
}
});
setupListAdapter(basicList.get_id());
}
private void setupListAdapter(int listId) {
populateListItems(listId);
listAdapter = new ListItemAdapter(this, R.layout.listrow, lists);
listView.setAdapter(listAdapter);
}
private void populateListItems(int listId) {
ArrayList<ListItem> items = (ArrayList<ListItem>)getApplicationContext().getShoppingListDbHelper().getShoppingListItems(listId);
for(ListItem item : items ) {
lists.add(item);
}
}
private void addToList(View view, BasicList list) {
if(basicList.getListTypeId() == Constants.TODO_LIST_TYPE_CDE) {
Intent newListIntent = new Intent(getBaseContext(), ToDoItemActivity.class);
startActivityForResult(newListIntent, 1);
}
else {
Intent newListIntent = new Intent(getBaseContext(), ItemActivity.class);
startActivityForResult(newListIntent, 1);
}
}
private void addToListByScan(View view, BasicList list) {
try {
IntentIntegrator zxingIntegrator = new IntentIntegrator(this);
zxingIntegrator.initiateScan();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "ERROR:" + e, 1).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
Log.d(getClass().getName(), scanResult.getContents());
Log.d(getClass().getName(), scanResult.getFormatName());
Log.d(getClass().getName(),data.getStringExtra("SCAN_RESULT_FORMAT"));
Log.d(getClass().getName(),data.getStringExtra("SCAN_RESULT"));
}
}
}
}
onActivityResult is called by Android whenever your app needs to be told about an Intent. That could be from lots of places. You know by looking at the request code and comparing it to the one in IntentIntegrator. Or let that class do all this for you.
My guess is your intent-filter is too broad and you're hearing things you don't expect.
Related
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class ReaderActivity extends AppCompatActivity {
private Button scan_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader);
scan_btn = (Button) findViewById(R.id.scan_btn);
final Activity activity = this;
scan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result.getContents() != null) {
if(result.getContents().equals("Electronics A1")){
Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, result.getContents(),Toast.LENGTH_LONG).show();
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
Hi all, currently doing a project for my school.
now im having problems with the program.
if(result.getContents() != null) {
if(result.getContents().equals("Electronics A1")){
Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_LONG).show();
curently this if stament is being ignored by the app.
the purpose of the statement is when i scan a specific qr code it will move to a new activity or do something.
yesterday the statement was working but suddenly today it wont work......
can you guys help me?
currently new to android studio
i want use toggle switch by voice commands like switch on and switch off so i got a code for voice recognition from a site but dont know how to trigger my toggle button thru it
The code of voice recognition i used -
package com.authorwjf.talk2me;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
protected static final int REQUEST_OK = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(i, REQUEST_OK);
} catch (Exception e) {
Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_OK && resultCode==RESULT_OK) {
ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
((TextView)findViewById(R.id.text1)).setText(thingsYouSaid.get(0));
}
}
}
your array thingsYouSaid have all possible string array you have . for example if I say hello it will have like [hello,aloe,hallo,no] so what you have to do is you can match your string switch off to result string array and if it is match with like "switch off" than change value of your switch from on to off likewise;
if (requestCode==REQUEST_OK && resultCode==RESULT_OK) {
ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
for(String value : thingsYouSaid.get(0)){
if(value.equalsignorecase("switch off")){
// change value for switch to off
break;
}
else if(value.equalsignorecase("switch on")){
// change value for switch to on
break;
}
}
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class AttachFiles extends Activity {
Button btnAddFile;
ListView listViewFiles;
String[] str;
ArrayList<String> arrayList = new ArrayList<String>();
Adapter myFileListAdapter;
final int RQS_LOADIMAGE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAddFile = (Button) findViewById(R.id.addphoto);
btnAddFile.setOnClickListener(btnAddFileOnClickListener);
}
View.OnClickListener btnAddFileOnClickListener
= new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, RQS_LOADIMAGE);
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_LOADIMAGE:
Uri imageUri = data.getData();
String string = imageUri.toString();
Log.e("STRING", " "+string);
arrayList.add(string);
Log.e("Get arrayList :" , " "+arrayList);
myFileListAdapter = new Adapter(AttachFiles.this, arrayList);
listViewFiles = (ListView) findViewById(R.id.filelist);
listViewFiles.setAdapter(myFileListAdapter);
myFileListAdapter.notifyDataSetChanged();
break;
}
}
}
}
In the above code I can see the files but couldn't load it into ListView.
In case you getting the result inside onactivityresult().I haven't see other than any chance to an error.
Change Adapter to ArrayAdapter
ArrayAdapter< String > myFileListAdapter = new
ArrayAdapter< String >(AttachFiles.this,
android.R.layout.simple_list_item_1, arrayList);
And declaring listview inside oncreate is better.
And give a try :)
I used method Intent and SpeechRecognizer but it very slow translate from speech to text, it took than 30s but something it faster about 3s. How to make it faster same same voice search of google? thanks you reading!
This is example code:
Method Intent
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
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.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Sample code that invokes the speech recognition intent API.
*/
public class VoiceRecognition extends Activity implements OnClickListener {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private ListView mList;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate our UI from its XML layout description.
setContentView(R.layout.voice_recognition);
// Get display items for later interaction
Button speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
speakButton.setOnClickListener(this);
} else {
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
}
/**
* Handle the click on the start recognition button.
*/
public void onClick(View v) {
if (v.getId() == R.id.btn_speak) {
startVoiceRecognitionActivity();
}
}
/**
* Fire an intent to start the speech recognition activity.
*/
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
/**
* Handle the results from the recognition activity.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it could have heard
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Method SpeechRecognizer
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");
}
}
}
How can i open Android device contacts list at button click event.
Try this code..
yourButton.setOnClickListener(new YouButtonEvent());
class YouButtonEventimplements OnClickListener{
#Override
public void onClick(View v) {
Intent it= new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(it, PICK_CONTACT);
}
}
Declare Some variables. Create a method & handle the events.
private static final int CONTACT_PICKER_RESULT = 1001;
private static final String DEBUG_TAG = "Contact List";
private static final int RESULT_OK = -1;
// a method to open your contact list
private void openContactList() {
Intent it = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(it, CONTACT_PICKER_RESULT);
}
// handle after selecting a contact from the list
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
// handle contact results
Log.w(DEBUG_TAG, "Warning: activity result is ok!");
break;
}
} else {
// gracefully handle failure
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
You can use this source code as a reference:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test1Activity extends Activity {
private static final int PICK_CONTACT_REQUEST = 1;
private static final int PICK_CONTACT = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button pickContact = (Button) findViewById(R.id.button1);
pickContact.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT);
i.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
startActivity(i);
}
});
}
}
if u want to pick contact from your device then use this code.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContect();
dialog.dismiss();
}
and openContact() is:
private void openContect() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_SELECT_CONTACT);
}
}
and in your onActivityResult() use this:
if (requestCode==REQUEST_SELECT_CONTACT && resultCode == RESULT_OK && null != data){
Uri contactUri = data.getData();
//do what you want...
}