Need help debugging: Failure delivering result - java.lang.NullPointerException - java

I have looked around through the other questions with the same problem, but because this error is specific to everyone's personal code, they didn't help much. I'm getting the following error:
(I can't upload images yet, and Eclipse won't let me copy+paste the error, so because I'm lazy, here's a Gyazo: CLICK ME)
Here's my code:
Mikey.java (ignore the stupid names)
package com.jamco.apps.mikey;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class Mikey extends Activity implements RecognitionListener, OnClickListener, TextToSpeech.OnInitListener {
protected static final int REQUEST_OK = 1;
private ImageButton btn;
private TextToSpeech tts;
private TextView txt;
private String thoughts;
private ArrayList<String> thingsYouSaid;
private Integer numberOfThingsSaid = 0;
#Override
public void onDestroy() {
//Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mikey);
btn = (ImageButton) findViewById(R.id.imageButton1);
txt = (TextView) findViewById(R.id.textView1);
tts = new TextToSpeech(this, this);
btn.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) {
numberOfThingsSaid += 1;
ArrayList<String> youJustSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
((TextView)findViewById(R.id.textView1)).setText("You said: " + youJustSaid);
thingsYouSaid.add(youJustSaid.get(0).toString());
think();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
btn.setEnabled(true);
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
#Override
public void onBeginningOfSpeech() {
//TODO Auto-generated method stub
}
#Override
public void onBufferReceived(byte[] buffer) {
//TODO Auto-generated method stub
}
#Override
public void onEndOfSpeech() {
//TODO Auto-generated method stub
}
#Override
public void onError(int error) {
//TODO Auto-generated method stub
}
#Override
public void onEvent(int eventType, Bundle params) {
//TODO Auto-generated method stub
}
#Override
public void onPartialResults(Bundle partialResults) {
//TODO Auto-generated method stub
}
#Override
public void onReadyForSpeech(Bundle params) {
//TODO Auto-generated method stub
}
#Override
public void onResults(Bundle results) {
//TODO Auto-generated method stub
}
#Override
public void onRmsChanged(float rmsdB) {
//TODO Auto-generated method stub
}
private void speak(String speech) {
tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(this, speech, Toast.LENGTH_LONG).show();
}
private void think() {
if (thingsYouSaid.get(numberOfThingsSaid) == "Hello" || thingsYouSaid.get(numberOfThingsSaid) == "Hi") {
switch (randInt(0, 2)) {
case 0:
speak("Hello");
case 1:
speak("Hello");
case 2:
speak(thingsYouSaid.get(numberOfThingsSaid));
}
}
}
public static int randInt(int min, int max) {
//Usually this can be a field rather than a method variable
Random rand = new Random();
//nextInt is normally exclusive of the top value,
//so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
(Sorry if the formatting is bad, I'm new to this site).
Here is my activity xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Mikey" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="42dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="119dp"
android:text="Click the Microphone and ask a question!" />
</RelativeLayout>
The Stack-trace tells me to go to this line:
thingsYouSaid.add(youJustSaid.get(0).toString());
However, after lots of trial and error I can't work out what's wrong with it. I tried adding .toString() just to see if it magically fixed something, but no.
Hopefully someone will be able to help me solve this :)
Merry Christmas!

I don't see anywhere that you are initializing thingsYouSaid;. You declare it like this
private ArrayList<String> thingsYouSaid;
but you don't initialize it. Try changing that to
private ArrayList<String> thingsYouSaid = new ArrayList<String>();
Edit
I haven't worked with TextToSpeech but I can tell you that you are comparing Strings incorrectly here
thingsYouSaid.get(numberOfThingsSaid) == "Hello" || thingsYouSaid.get(numberOfThingsSaid) == "Hi")
inside think(). You should use equals() to compare Strings.
if ((("Hello".equals(thingsYouSaid.get(numberOfThingsSaid))
|| ("Hi".equals(thingsYouSaid.get(numberOfThingsSaid))))
also, you should add break; statements at the end of each case or the logic will fall through even if it matches one of the first case statements.

thingsYouSaid is not instantiated anywhere in your code. You should instantiate it (you can do that while declaring):
ArrayList<String> thingsYouSaid = new ArrayList<String>();

Related

Android to Arduino via Bluetooth. App won't send string

I found some code in the Internet and changed it. I try to send a short string via Bluetooth. I use the HC-05 Bluetooth module.
I can connect my android device with the module but I can't send a string to my Arduino.
I have:
1 EditText to enter my string.
2 Buttons:
-1 to send
-2 to connect
Could you look over my code? Thank you:)
Android Code...
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
String command;//string variable that will store value to be transmitted to the bluetooth module
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button BtSend = findViewById(R.id.BtSend);
Button BtVerbinden = findViewById(R.id.BtVerbinden);
final EditText EtEingabe = findViewById(R.id.EtEingabe);
BtSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
command = EtEingabe.getText().toString();
try {
outputStream.write(command.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
});
//Button that connects the device to the bluetooth module when pressed
BtVerbinden.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (BTinit()) {
BTconnect();
}
}
});
}
public boolean BTinit() {
boolean found = false;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) //Checks if the device supports bluetooth
{
Toast.makeText(getApplicationContext(), "Device doesn't support bluetooth", Toast.LENGTH_SHORT).show();
}
if (!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if (bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(), "Please pair the device first", Toast.LENGTH_SHORT).show();
} else {
for (BluetoothDevice iterator : bondedDevices) {
if (iterator.getAddress().equals(DEVICE_ADDRESS)) {
device = iterator;
found = true;
break;
}
}
}
return found;
}
public boolean BTconnect() {
boolean connected = true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID); //Creates a socket to handle the outgoing connection
socket.connect();
Toast.makeText(getApplicationContext(),
"Connection to bluetooth device successful", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
connected = false;
}
if (connected) {
try {
outputStream = socket.getOutputStream(); //gets the output stream of the socket
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream == null) {
try {
outputStream = socket.getOutputStream();
} catch (IOException e) {
}
}
return connected;
}
#Override
protected void onStart() {
super.onStart();
}
}
Android XML...
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.swini.gimbalarduino.MainActivity">
<Button
android:id="#+id/BtSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="184dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Send"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/EtEingabe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="220dp"
android:ems="10"
android:hint="Hoi"
android:inputType="textPersonName"
android:text="Text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/BtVerbinden"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Connect"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Try to use this code but this code run in Fragment so carefully change the Code according to your activity.
package com.example.rishabhrawat.tablayoutapp;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import static android.app.Activity.RESULT_OK;
/**
* Created by Rishabh Rawat on 6/18/2017.
*/
public class OfflineVideo extends android.support.v4.app.Fragment {
Button f,r,l,b,s,dis;
ListView listView;
ImageView mic;
BluetoothAdapter adapter;
private Set<BluetoothDevice> paireddevices;
private String address;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
private ProgressDialog progress;
private final int REQ_CODE_SPEECH_INPUT = 100;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.offlinevideo,container,false);
f=(Button)view.findViewById(R.id.forward);
r=(Button)view.findViewById(R.id.right);
l=(Button)view.findViewById(R.id.left);
b=(Button)view.findViewById(R.id.backward);
s=(Button)view.findViewById(R.id.stop);
dis=(Button)view.findViewById(R.id.discover);
mic=(ImageView)view.findViewById(R.id.mic);
listView=(ListView)view.findViewById(R.id.listview);
f.setEnabled(false);
r.setEnabled(false);
l.setEnabled(false);
b.setEnabled(false);
s.setEnabled(false);
mic.setEnabled(false);
adapter=BluetoothAdapter.getDefaultAdapter();
dis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShowPairedDevices();
}
});
f.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forward();
}
});
r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
right();
}
});
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
left();
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
backward();
}
});
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stop();
}
});
mic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VoiceInput();
}
});
return view;
}
public void ShowPairedDevices()
{
paireddevices=adapter.getBondedDevices();
ArrayList list = new ArrayList();
if (paireddevices.size()>0)
{
for(BluetoothDevice bt : paireddevices)
{
list.add(bt.getName() + "\n" + bt.getAddress());
}
}
else
{
Toast.makeText(getContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter=new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(myclicklistner);
}
private AdapterView.OnItemClickListener myclicklistner= new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
String info = ((TextView) v).getText().toString();
address = info.substring(info.length() - 17);
new connectbt().execute();
}
};
private class connectbt extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(getActivity(), "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
adapter = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = adapter.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
Toast.makeText(getActivity().getApplicationContext(),"Connection Failed Please Try again later",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Successfully Connected ", Toast.LENGTH_SHORT).show();
f.setEnabled(true);
r.setEnabled(true);
l.setEnabled(true);
b.setEnabled(true);
s.setEnabled(true);
mic.setEnabled(true);
isBtConnected = true;
}
progress.dismiss();
}
}
public void toast(String message)
{
Toast.makeText(getActivity().getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void forward()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("F".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void left()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("L".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void right()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("R".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void backward()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("B".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void stop()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("S".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
public void VoiceInput()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speak Command for Robot");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQ_CODE_SPEECH_INPUT)
{
if(resultCode==RESULT_OK)
{
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(result.get(0).equals("forward"))
{
forward();
}
else if(result.get(0).equals("backward"))
{
backward();
}
else if(result.get(0).equals("stop"))
{
stop();
}
else if(result.get(0).equals("left"))
{
left();
}
else if(result.get(0).equals("right"))
{
right();
}
else
{
Toast.makeText(getActivity(), result.get(0), Toast.LENGTH_SHORT).show();
}
}
}
}
}
Layout File
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/forward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forward"
android:background="#00bfff"
android:textColor="#fff"
android:layout_above="#+id/stop"
android:layout_alignStart="#+id/stop"
android:layout_marginBottom="27dp" />
<Button
android:id="#+id/backward"
android:background="#00bfff"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/forward"
android:layout_centerVertical="true"
android:text="Backward"
/>
<Button
android:id="#+id/left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginEnd="14dp"
android:text="Left"
android:background="#00bfff"
android:textColor="#fff"
android:layout_above="#+id/backward"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:background="#00bfff"
android:textColor="#fff"
android:layout_alignTop="#+id/left"
android:layout_marginStart="17dp"
android:text="Right" />
<Button
android:id="#+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:background="#d22d2d"
android:textColor="#fff"
android:layout_alignBaseline="#+id/right"
android:layout_alignBottom="#+id/right"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/backward"
android:divider="#52f202"
android:dividerHeight="1dp"
android:id="#+id/listview"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<Button
android:id="#+id/discover"
android:background="#80ff00"
android:textSize="25dp"
android:textColor="#000099"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:fontFamily="sans-serif-smallcaps"
android:text="Discovery"
android:textAppearance="#style/TextAppearance.AppCompat.Light.Widget.PopupMenu.Large" />
<ImageView
android:id="#+id/mic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/discover"
app:srcCompat="#drawable/microphone" />
</RelativeLayout>
Arduino Code
char myserial;
void setup()
{
pinMode(11,OUTPUT);
pinMode(10,OUTPUT);
pinMode(9,OUTPUT);
pinMode(8,OUTPUT);
Serial.begin(9600);
}
void loop()
{
myserial=Serial.read();
switch(myserial)
{
case 'S':
digitalWrite(11,LOW);
digitalWrite(10,LOW);
digitalWrite(9,LOW);
digitalWrite(8,LOW);
break;
case 'B':
digitalWrite(11,HIGH);
digitalWrite(10,LOW);
digitalWrite(9,HIGH);
digitalWrite(8,LOW);
break;
case 'F':
digitalWrite(11,LOW);
digitalWrite(10,HIGH);
digitalWrite(9,LOW);
digitalWrite(8,HIGH);
break;
case 'L':
digitalWrite(11,HIGH);
digitalWrite(10,LOW);
digitalWrite(9,LOW);
digitalWrite(8,HIGH);
break;
case 'R':
digitalWrite(11,LOW);
digitalWrite(10,HIGH);
digitalWrite(9,HIGH);
digitalWrite(8,LOW);
break;
}
}
btSocket.getOutputStream().write(sendText.getText().toString().getBytes());
.

The app crashes when trying to login(using parse object)

I am creating an app having login activity and used parse.com as the network service. I used the default loginactivity.java file in android studio. Inside my class UserLoginTask, I used the parse login methods. But I am not sure what is wrong. The app takes the email id and password. The progress bar works for a flip second and then the app shuts down.Then I get and error after sometime.
This is the loginactivty.java.
package com.redux.kumardivyarajat.attendance;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentResolver;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.List;
/**
* A login screen that offers login via email/password.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class LoginActivity extends ActionBarActivity implements LoaderCallbacks<Cursor> {
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
Button mSignUpButton = (Button)findViewById(R.id.SignUpButtonInsideLogin);
mSignUpButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
//mSignUpTextView = (TextView) findViewById(R.id.SignupText);
}
private void populateAutoComplete() {
if (VERSION.SDK_INT >= 14) {
// Use ContactsContract.Profile (API 14+)
getLoaderManager().initLoader(0, null, this);
} else if (VERSION.SDK_INT >= 8) {
// Use AccountManager (API 8+)
new SetupEmailAutoCompleteTask().execute(null, null);
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
email = email.trim();
password = password.trim();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute();
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("#");
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Use an AsyncTask to fetch the user's email addresses on a background thread, and update
* the email text field with results on the main UI thread.
*/
class SetupEmailAutoCompleteTask extends AsyncTask<Void, Void, List<String>> {
#Override
protected List<String> doInBackground(Void... voids) {
ArrayList<String> emailAddressCollection = new ArrayList<String>();
// Get all emails from the user's contacts and copy them to a list.
ContentResolver cr = getContentResolver();
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
null, null, null);
while (emailCur.moveToNext()) {
String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract
.CommonDataKinds.Email.DATA));
emailAddressCollection.add(email);
}
emailCur.close();
return emailAddressCollection;
}
#Override
protected void onPostExecute(List<String> emailAddressCollection) {
addEmailsToAutoComplete(emailAddressCollection);
}
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
/*try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;*/
ParseUser.logInInBackground(mEmail,mPassword, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null)
{
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage());
builder.setTitle(R.string.loginup_error_title);
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
And this is the error I get after a while. I think this error is because of the fact that the app closes down but the background task of fetching data from parse is still in progress. I am not sure.
com.redux.kumardivyarajat.attendance E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.redux.kumardivyarajat.attendance, PID: 22430
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#43010550 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:559)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.redux.kumardivyarajat.attendance.LoginActivity$UserLoginTask$1.done(LoginActivity.java:362)
at com.redux.kumardivyarajat.attendance.LoginActivity$UserLoginTask$1.done(LoginActivity.java:345)
at com.parse.Parse$6$1.run(Parse.java:945)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5047)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:806)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
at dalvik.system.NativeStart.main(Native Method)
Please suggest what chages should I make in the UserLoginTask(asynctask) to make it work.
Edit: Adding the mainactivity.java and the activity_login2.xml.
activity_login2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.redux.kumardivyarajat.attendance.LoginActivity"
android:weightSum="1"
android:id="#+id/activity_login2">
<!-- Login progress -->
<ProgressBar android:id="#+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1"
android:touchscreenBlocksFocus="false">
<AutoCompleteTextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true"
android:layout_weight="10.63">
<requestFocus/>
</AutoCompleteTextView>
<EditText android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"
android:textSize="20dp"/>
<Button android:id="#+id/email_sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/action_sign_in_short"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id ="#+id/SignupText"
android:text="#string/sign_up_from_login"
android:textColor="#ffff0500"
android:layout_marginTop="50dp"
android:layout_weight="0.18" />
<Button
style="?android:textAppearanceSmall"
android:id="#+id/SignUpButtonInsideLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Sign Up"
android:textStyle="bold"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Now the on create method of mainactivity.java.
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
setContentView(R.layout.activity_main);
}
ParseAnalytics.trackAppOpened(getIntent());
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser == null) {
navigateToLogin();
} else {
Log.i(TAG,currentUser.getUsername());
}
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
According to your scenario, BadToken error may occurs when you try to show the particular view or a dialog once you finish the current activity. Whatever happens, your doinBackground return true, but when it get execute, you may have finish the activity. So i suggest you to proceed within the onpostExecute.
Try this,
Update your Async task as follows and return the status values from doInBackground. Then perform whatever the task based on return value with on onPostExecute.
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
private boolean status = false;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
ParseUser.logInInBackground(mEmail,mPassword, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null)
{
status = true;
} else {
status = false;
}
}
});
return status;
}
#Override
protected void onPostExecute(final Boolean success) {
if (success) {
// success code
} else {
// failure code
}
}

How to toggle flashlight mode?

I want to add a button (which I have included in my activity_main) to my app that will launch a strobe effect when pressed and will stop when pressed again. I do not care about the speed, just that it toggles flash_mode_torch and flash_mode_off repeatedly until the button is pressed again.
I have tried:
Using a handler
Creating a separate class
The separate class containing the handler did not work because there was no intent in the main activity to launch or in the manifest because the code for it is not finished because I want to ask here how its done in the most simplest manner possible.
StrobeLightConfig.java
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class StrobeLightConfig extends Activity {
boolean check = false;
Camera sandy;
StrobeRunner runner;
Thread bw;
ImageButton btnClick;
public final Handler mHandler = new Handler();
public final Runnable mShowToastRunnable = new Runnable() {
public void run() {
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnClick = (ImageButton) findViewById(R.id.btnSwitch);
runner = StrobeRunner.getInstance();
runner.controller = this;
if (runner.isRunning) {
} else {
try {
sandy = Camera.open();
if (sandy == null) {
return;
}
sandy.release();
} catch (RuntimeException ex) {
return;
}
}
bw = new Thread(runner);
bw.start();
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (check) {
bw = new Thread(runner);
bw.start();
check = false;
} else {
check = true;
runner.requestStop = true;
}
}
});
final SeekBar skbar = (SeekBar) findViewById(R.id.SeekBar01);
skbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
runner.delay = 101 - progress;
runner.delayoff = 101 - progress;
}
});
}
#Override
protected void onStop() {
// runner.requestStop = true;
super.onStop();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
// super.onBackPressed();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startActivity(startMain);
}
}
StrobeRunner.java
import android.hardware.Camera;
public class StrobeRunner implements Runnable {
protected StrobeRunner()
{
}
public static StrobeRunner getInstance()
{
return ( instance == null ? instance = new StrobeRunner() : instance );
}
private static StrobeRunner instance;
public volatile boolean requestStop = false;
public volatile boolean isRunning = false;
public volatile int delay = 10;
public volatile int delayoff = 500;
public volatile StrobeLightConfig controller;
public volatile String errorMessage = "";
#Override
public void run() {
if(isRunning)
return;
requestStop=false;
isRunning = true;
Camera cam = Camera.open();
Camera.Parameters pon = cam.getParameters(), poff = cam.getParameters();
pon.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
poff.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
while(!requestStop)
{
try{
cam.setParameters(pon);
Thread.sleep(delay);
cam.setParameters(poff);
Thread.sleep(delayoff);
}
catch(InterruptedException ex)
{
}
catch(RuntimeException ex)
{
requestStop = true;
errorMessage = "Error setting camera flash status. Your device may be unsupported.";
}
}
cam.release();
isRunning = false;
requestStop=false;
controller.mHandler.post(controller.mShowToastRunnable);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/TableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<SeekBar
android:id="#+id/SeekBar01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:progress="0"
android:layout_alignParentTop="true"
>
</SeekBar>
<ImageButton
android:id="#+id/btnSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/w_led_on"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"/>
</RelativeLayout>

Text to Speak for Android not working

I'm trying to implement Text to Speech onto my app. I've followed the following guide but my app keeps crashing after the splash screen.
link: http://www.androidhive.info/2012/01/android-text-to-speech-tutorial/
Main Activity Class I have this
String alertMessage = AppResources.ALERT_MSG;
SpeakDemo speak = new SpeakDemo(null, alertMessage);
speak.speakOut();
If I remove the speak.speakOut(); line the app works fine.
App Resources is another class with the following message box
public static String ALERT_MSG = "Welcome!";
The SpeakDemo Class is:
import java.util.Locale;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;
public class SpeakDemo implements TextToSpeech.OnInitListener{
private TextToSpeech tts;
private Context context;
private String message;
public SpeakDemo(Context context, String message){
this.context = context;
this.message = message;
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
public void speakOut(){
tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
}
}
Any Ideas?
Thanks
You need to instantiate the TextToSpeech.
Change
public SpeakDemo(Context context, String message){
this.context = context;
this.message = message;
tts = new TextToSpeech(context, this);
}
//FOR TEXT TO SPEECH
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
String msg=text.getText().toString();
if(status==TextToSpeech.SUCCESS)
{
tts.setLanguage(Locale.US);
tts.speak(msg,TextToSpeech.QUEUE_FLUSH,null);
}
else
Log.e("TTS","INITILIZATION FAILED");
}
public void onDestroy()
{
if (tts!=null)
{
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
Xml:
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Speak"
android:onClick="TTS"/>
Mainactivity:
TextToSpeech textToSpeech;
textToSpeech=new TextToSpeech(TTSpeech.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS)
{
result=textToSpeech.setLanguage(Locale.ENGLISH);
}
else
{
Toast.makeText(TTSpeech.this, "speech not work", Toast.LENGTH_SHORT).show();
}
}
});
}
public void TTS(View view) {
switch (view.getId())
{
case R.id.button:
if(result== TextToSpeech.LANG_NOT_SUPPORTED || result==TextToSpeech.LANG_MISSING_DATA)
{
Toast.makeText(TTSpeech.this, "speech not nt work", Toast.LENGTH_SHORT).show();
}
else
{
text=ed.getText().toString();
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null);
}
break;
}
if you get problem you can comment me.

Modify speech recognition without popup

I'm totally new to Android and I decided to create a Siri look-a-like app, which is working fine, I searched before asking but I can't get it to work: Android speech Recognition App Without Pop Up
So I want to hide the pop-up inside my Android app, but I really don't now how to do it properly. I'll be very glad if someone could help me doing this. I have already added the correct permissions in Android Manifest...
Here is my full source:
/**
* Giovanni Terlingen
* PWS Project
* 3 november 2014
* Original file from http://github.com/gi097/PWS
*/
package nl.giovanniterlingen.pws;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity implements OnInitListener {
private static final String TAG = "PWS";
private TextView result;
private TextToSpeech tts;
private Button speak;
private int SPEECH_REQUEST_CODE = 1234;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
speak = (Button) findViewById(R.id.bt_speak);
speak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRecognizeIntent();
}
});
speak.setEnabled(false);
result = (TextView) findViewById(R.id.tv_result);
tts = new TextToSpeech(this, this);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
speak.setEnabled(true);
} else {
// failed to init
finish();
}
}
private void sendRecognizeIntent() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Aan het luisteren...");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 100);
startActivityForResult(intent, SPEECH_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SPEECH_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (matches.size() == 0) {
tts.speak("Ik heb niks gehoord, probeer het nog eens",
TextToSpeech.QUEUE_FLUSH, null);
} else {
String mostLikelyThingHeard = matches.get(0);
result.setText("Dit heeft u gezegd: "
+ mostLikelyThingHeard + ".");
mostLikelyThingHeard = mostLikelyThingHeard.toLowerCase();
boolean found = false;
String[] groeten = { "hallo", "heey", "hoi", "hey", "he",
"hee", "hay" };
for (String strings : groeten) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Hey leuk dat je er bent!",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] okay = { "oké, oke, ok, okay, okee" };
for (String strings : okay) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Okiedokie!",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] vragen = { "hoe gaat het", "hoe gaat het met je", "hoe gaat het met jou", "hoe gaat het met u", "hoe is het"};
for (String strings : vragen) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Met mij gaat het altijd goed, met jou?",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] wie = { "wie ben", "hoe heet je", "hoe heet jij", "wat is je naam", "wat is uw naam"};
for (String strings : wie) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Ik ben PWS, ik ben gemaakt als profielwerkstuk door Giovanni Terlingen.",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] leeftijd = { "hoe oud ben" };
for (String strings : leeftijd) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Ik ben op 3 november 2014 van start gegaan dus dat mag je zelf uitrekenen",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] lachen = { "haha", "hah", "ha" };
for (String strings : okay) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Haha leuk grapje",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
if (!found) {
String doei = "doei";
if (mostLikelyThingHeard.equals(doei)) {
tts.speak("Okay tot de volgende keer!",
TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak("Ik begrijp niet wat je bedoeld met "
+ mostLikelyThingHeard
+ " probeer het anders te verwoorden.",
TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
} else {
Log.d(TAG, "result NOT ok");
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onDestroy() {
if (tts != null) {
tts.shutdown();
}
super.onDestroy();
}
}
Step 1
In Android Manifest.xml, add the permission.
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Step 2
In the Layout screen, i am using a Toggle Button to start/stop voice listening.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
.......
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:text="ToggleButton" />
......
</RelativeLayout>
Step 3 - Activity Class
package com.example.voice;
import java.util.ArrayList;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;
public class VoiceRecognitionActivity extends Activity implements
RecognitionListener {
private TextView returnedText;
private ToggleButton toggleButton;
private SpeechRecognizer speech = null;
private Intent recognizerIntent;
private String LOG_TAG = "VoiceRecognitionActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
returnedText = (TextView) findViewById(R.id.textView1);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,
"en");
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
speech.startListening(recognizerIntent);
} else {
speech.stopListening();
}
}
});
}
#Override
public void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
if (speech != null) {
speech.destroy();
Log.i(LOG_TAG, "destroy");
}
}
#Override
public void onBeginningOfSpeech() {
Log.i(LOG_TAG, "onBeginningOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer) {
Log.i(LOG_TAG, "onBufferReceived: " + buffer);
}
#Override
public void onEndOfSpeech() {
Log.i(LOG_TAG, "onEndOfSpeech");
toggleButton.setChecked(false);
}
#Override
public void onError(int errorCode) {
String errorMessage = getErrorText(errorCode);
Log.d(LOG_TAG, "FAILED " + errorMessage);
returnedText.setText(errorMessage);
toggleButton.setChecked(false);
}
#Override
public void onEvent(int arg0, Bundle arg1) {
Log.i(LOG_TAG, "onEvent");
}
#Override
public void onPartialResults(Bundle arg0) {
Log.i(LOG_TAG, "onPartialResults");
}
#Override
public void onReadyForSpeech(Bundle arg0) {
Log.i(LOG_TAG, "onReadyForSpeech");
}
#Override
public void onResults(Bundle results) {
Log.i(LOG_TAG, "onResults");
ArrayList<String> matches = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String text = "";
for (String result : matches)
text += result + "\n";
returnedText.setText(text);
}
#Override
public void onRmsChanged(float rmsdB) {
Log.i(LOG_TAG, "onRmsChanged: " + rmsdB);
}
public static String getErrorText(int errorCode) {
String message;
switch (errorCode) {
case SpeechRecognizer.ERROR_AUDIO:
message = "Audio recording error";
break;
case SpeechRecognizer.ERROR_CLIENT:
message = "Client side error";
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
message = "Insufficient permissions";
break;
case SpeechRecognizer.ERROR_NETWORK:
message = "Network error";
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
message = "Network timeout";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
message = "No match";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
message = "RecognitionService busy";
break;
case SpeechRecognizer.ERROR_SERVER:
message = "error from server";
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
message = "No speech input";
break;
default:
message = "Didn't understand, please try again.";
break;
}
return message;
}
}

Categories