I have a problem with my android app with speech recognition.My problem is that I want to show the same speech recognition input screen as is shown from the jellybean keyboard. If I invoke the Speech recognition intent from code, it does not keep listening and stops prematurely.
There must be a simple way to do this, but I can't find it.
here is my code
package com.bsdcservices.recognitiontest;
import java.util.ArrayList;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private final String TAG = "RecognitionTest";
private final int SPEECHRECOGNITION_RESULTCODE = 0;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.textbox);
Button recognize = (Button) findViewById(R.id.recognize);
recognize.setOnClickListener(buttonClickListener);
}
public OnClickListener buttonClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
startSpeechRecognitionActivity();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
void startSpeechRecognitionActivity(){
// MyApplication.speechRecognitionActive = true;
// main.startSpeechRecognizer(TABSPEAK);
try{
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);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault().toString());
startActivityForResult(intent, SPEECHRECOGNITION_RESULTCODE);
} catch (ActivityNotFoundException error) {
Toast.makeText(getBaseContext(), "Speech recognition is not supported by your device" , Toast.LENGTH_LONG).show();
} catch( RuntimeException error ) {
Toast.makeText(getBaseContext(), error.getMessage() , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try
{
if (requestCode == SPEECHRECOGNITION_RESULTCODE) {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
editText.append(text.get(0));
}
}
} catch( RuntimeException error ) {
Toast.makeText(getBaseContext(), error.getMessage() , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}
}
Related
I'm trying to implement the facebook login. I have followed everything from here.
https://developers.facebook.com/docs/facebook-login/android/v2.3
And I am trying to make a Graph API call to retrieve user data; however, when I do so I get this.
Warning: Request without access token missing application ID or client token.
I believe I have implemented this login correctly and followed all the steps.
I have done some research on this and since sessions are deprecated in this current Facebook API version it has been of no help.
Is there anything blatantly wrong with my implementation that would cause Facebook Login not to be validated for the user?
package com.ro.hitup1_0;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class LoginActivity extends Activity {
//Give your SharedPreferences file a name and save it to a static variable
public static final String PREFS_NAME = "MyPrefsFile";
//Facebook button
LoginButton loginButton;
Button email_button;
Button google_button;
CallbackManager callbackManager;
AccessTokenTracker accessTokenTracker;
ProfileTracker profileTracker;
JSONArray userInformation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.e("loginResult: ", loginResult.getAccessToken().getToken());
//LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile", "email", "user_friends"));
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
response.getError();
Log.e("JSON: ", object.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
//Log.e(" About to Graph Call", " ");
request.executeAsync();
//Log.e(" Finished Graph Call", " ");
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
Log.e("Facebook exception: ", exception.getMessage());
}
});
// Callback registration
//make sure to redirect to main page
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
// App code
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(
Profile oldProfile,
Profile currentProfile) {
// App code
}
};
google_button=(Button)findViewById(R.id.google_button);
google_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
email_button= (Button)findViewById(R.id.email_button);
email_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.ro.hitup1_0",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
super.onDestroy();
profileTracker.stopTracking();
}
}
I implemented this in a FragmentActivity is there anything wrong with doing so?
What am I missing and why is this occuring?
For additional context (no android pun intended),
https://github.com/rrtigga/Hitup1.0/tree/master/app/src/main
Thanks.
I need help, I am making a simple application, and I donĀ“t know how to return to the MainActivity the string from the spinner and the name of the person when i click in the "Aceptar" button.
MainActivity.java
package com.example.holaamigos;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_SALUDO = "com.example.holaamigos.SALUDO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtNombre = (EditText)findViewById(R.id.TxtNombre);
final Button btnHola = (Button)findViewById(R.id.BtnHola);
final CheckBox checkbox1 =(CheckBox)findViewById(R.id.checkBox1);
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean checked) {
if (checked)
{
Toast.makeText(checkbox1.getContext(), "Activo", Toast.LENGTH_LONG).show();
btnHola.setVisibility(0);
btnHola.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ActivitySaludo.class);
String saludo = txtNombre.getText().toString();
intent.putExtra(EXTRA_SALUDO, saludo);
startActivity(intent);
}
});
}
else
{
Toast.makeText(checkbox1.getContext(), "Inactivo", Toast.LENGTH_SHORT).show();
btnHola.setVisibility(View.INVISIBLE);
}
}
});
}
public void HobbyReturn(int requestcode, int resultadocode, Intent data) {
if (resultadocode == ActivitySaludo.ACEPTAR_OK); {
String string = data.getStringExtra(ActivitySaludo.ACEPTAR_OK);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
ActivitySaludo
package com.example.holaamigos;
import com.example.holaamigos.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class ActivitySaludo extends Activity {
public static final String ACEPTAR_OK = "com.example.holaamigos.ACEPTAR_OK";
String myspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saludo);
Intent intent = getIntent();
String saludo = intent.getStringExtra(MainActivity.EXTRA_SALUDO);
TextView txtCambiado = (TextView) findViewById(R.id.TxtSaludo);
txtCambiado.setText(getString(R.string.hola_saludo) + " " + saludo);
final Spinner spinner = (Spinner)findViewById(R.id.SpinnerSaludo);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.hobby, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
myspinner = spinner.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
final Button BtnAceptar=(Button) findViewById(R.id.buttonAceptar);
BtnAceptar.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View v) {
Intent iboton = new Intent();
iboton.putExtra("HOBBY", myspinner);
setResult(ACEPTAR_OK, iboton);
finish();
}
});
}
}
You need to start your second activity with the flag that you are waiting for a result, so instead of startActivity you need to make use of startActivityForResult.
If you need a little bit more information take a look at this tutorial it should cover all you need to get things working.
I'm new in Java and my English isn't the best too.
I want to write an app which meassures the Amplitude of a record. The app works except for the fact, that the amplitude is always 0. I have now read several websites, but didn't found an answer. I would be realy glad if somebody helps me.
package com.example.volumeswitcher;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnInfoListener {
WindowManager.LayoutParams lp;
Button messe;
MediaRecorder micro;
int ampli;
TextView tv1;
TextView tv2;
String amplitext;
Vibrator vibr;
Environment e;
String mFileName;
int i;
Boolean recording;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
setContentView(R.layout.activity_main);
micro = null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onBtnClicked(View v) {
startRecording();
}
protected void startRecording() {
if (micro == null){
i ++;
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecord"+ i +".3gp";
micro = new MediaRecorder();
micro.setAudioSource(MediaRecorder.AudioSource.MIC);
micro.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
micro.setOutputFile(mFileName);
micro.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
micro.setMaxDuration(2000);
try {
micro.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "IllegalStateException called", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "prepare() failed", Toast.LENGTH_LONG).show();
}
micro.start();
micro.getMaxAmplitude();
ampli = micro.getMaxAmplitude();
tv1 = (TextView) findViewById(R.id.textView1);
tv1.setText(Integer.toString(ampli));
}
micro.setOnInfoListener(new OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
micro.stop();
recording = false;
micro.release();
micro = null;
}
}
});
}
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
// TODO Auto-generated method stub
}
}
Thank you for your help!
I have the same issue, and oddly enough if you change the time interval when your trying to get the max amplitude, to greater then one second, it works normally, but i don't know what's causing it ...
I'm recieving an error when running on my galaxy s3 called ": Can't open file for reading" twice in my LogCat.
Here is my code:
package com.example.speechrecognizertest;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
public static final String TAG = null;
private ListView wordList;
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private boolean mIslistening;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speechBtn = (Button) findViewById(R.id.speech_btn);
wordList = (ListView) findViewById(R.id.word_list);
PackageManager packManager = getPackageManager();
List<ResolveInfo> intActivities = packManager.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
if (!mIslistening)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
} else {
speechBtn.setEnabled(false);
Toast.makeText(this, "Oops - Speech Recognition Not Supported!",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onDestroy() {
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
protected class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "OnReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
ArrayList<String> suggestedWords = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// matches are the return values of speech recognition engine
// Use these values for whatever you wish to do
wordList.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.word, suggestedWords));
}
#Override
public void onRmsChanged(float rmsdB){}}
}
My LogCat is displaying idsactly what I described. Would really appreciate a fix guys!
I've seen this for a number of months on my S3 and it's never appeared to cause any problems. The answer here sounds probable to me.
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button abButton = (Button) findViewById(R.id.button1);
final TextView changelingtext = (TextView) findViewById(R.id.changeling);
abButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Buttons are working baby", Toast.LENGTH_LONG).show();
count++;
String a = Integer.toString(count);
changelingtext.setText(a);
gotonextpage(v);
}
});
}
public void gotonextpage(View view){
Intent intent = new Intent(this, SecondpageActivity.class);
startActivity(intent);
intent.putExtra("count", count);
//finish(); if you want to end this page
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
First class is above, second class is below
package com.example.collegematch;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class SecondpageActivity extends Activity {
int values;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondpage);
Intent intent = getIntent();
values = intent.getExtras().getInt("count");
Button exitButton = (Button) findViewById(R.id.exit);
Button textbutton = (Button) findViewById(R.id.coolbutton);
TextView texty = (TextView) findViewById(R.id.cooltext);
textbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), Integer.toString(values), Toast.LENGTH_LONG).show();
System.out.println(values);
}
});
exitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Seeya", Toast.LENGTH_LONG).show();
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.secondpage, menu);
return true;
}
}
In the mainActivity, everytime button abButton is pressed, it increases the count variable by 1. It also creates a new intent and sends that variable via extra to that intent.
In the second activity, the "values" variable getting the data from the intent is giving me a null pointer exception. Why?
Intent intent = new Intent(this, SecondpageActivity.class);
startActivity(intent);
intent.putExtra("count", count);
Change to
Intent intent = new Intent(this, SecondpageActivity.class);
intent.putExtra("count", count);
startActivity(intent);
You are setting the extra after you've already started the 2nd activity
just alter these two code lines,
Intent intent = new Intent(this, SecondpageActivity.class);
intent.putExtra("count", count);
startActivity(intent);
Your SecondActivity Intent start before setting the extra count to it.