I've made a simple accelerometer app and I want to make a companion widget. But every time I add a sensor to my widgetprovider I get the following error:
07-25 10:31:01.337: E/AndroidRuntime(8908): FATAL EXCEPTION: main
07-25 10:31:01.337: E/AndroidRuntime(8908):
java.lang.RuntimeException: Unable to start receiver
com.example.axelo.AxeloAppWidgetProvider:
java.lang.NullPointerException 07-25 10:31:01.337:
E/AndroidRuntime(8908): at
android.app.ActivityThread.handleReceiver(ActivityThread.java:2153)
07-25 10:31:01.337: E/AndroidRuntime(8908): at
android.app.ActivityThread.access$1500(ActivityThread.java:127) 07-25
10:31:01.337: E/AndroidRuntime(8908): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
07-25 10:31:01.337: E/AndroidRuntime(8908): at
android.os.Handler.dispatchMessage(Handler.java:99) 07-25
10:31:01.337: E/AndroidRuntime(8908): at
android.os.Looper.loop(Looper.java:137) 07-25 10:31:01.337:
E/AndroidRuntime(8908): at
android.app.ActivityThread.main(ActivityThread.java:4448) 07-25
10:31:01.337: E/AndroidRuntime(8908): at
java.lang.reflect.Method.invokeNative(Native Method) 07-25
10:31:01.337: E/AndroidRuntime(8908): at
java.lang.reflect.Method.invoke(Method.java:511) 07-25 10:31:01.337:
E/AndroidRuntime(8908): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
07-25 10:31:01.337: E/AndroidRuntime(8908): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590) 07-25
10:31:01.337: E/AndroidRuntime(8908): at
dalvik.system.NativeStart.main(Native Method) 07-25 10:31:01.337:
E/AndroidRuntime(8908): Caused by: java.lang.NullPointerException
07-25 10:31:01.337: E/AndroidRuntime(8908): at
com.example.axelo.AxeloAppWidgetProvider.onUpdate(AxeloAppWidgetProvider.java:29)
07-25 10:31:01.337: E/AndroidRuntime(8908): at
android.appwidget.AppWidgetProvider.onReceive(AppWidgetProvider.java:66)
07-25 10:31:01.337: E/AndroidRuntime(8908): at
android.app.ActivityThread.handleReceiver(ActivityThread.java:2146)
07-25 10:31:01.337: E/AndroidRuntime(8908): ... 10 more
This is what my widget class looks like
package com.example.axelo;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.TextView;
public class AxeloAppWidgetProvider extends AppWidgetProvider implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mSensor;
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this provider
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null){
Log.v("SENSOR_SERVICE","accelerometer found!");
}
else {
Log.v("SENSOR_SERVICE","Not found!");
}
// Create an Intent to launch MainActivity
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.axelo_widget);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
// // Show changes on screen.
views.setTextViewText(R.id.coord_X, Float.toString(linear_acceleration[0]));
views.setTextViewText(R.id.coord_Y, Float.toString(linear_acceleration[1]));
views.setTextViewText(R.id.coord_Z, Float.toString(linear_acceleration[2]));
// Tell the AppWidgetManager to perform an update on the current app widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
float[] gravity={(float) 9.81,(float) 9.81,(float) 9.81};
float[] linear_acceleration=new float[3];
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
final float alpha = (float) 0.8;
Log.v("SENSOR_SERVICE", "on sensor change");
// Isolate the force of gravity with the low-pass filter.
gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
// Remove the gravity contribution with the high-pass filter.
linear_acceleration[0] = event.values[0] - gravity[0];
linear_acceleration[1] = event.values[1] - gravity[1];
linear_acceleration[2] = event.values[2] - gravity[2];
}
}
Please tell me where I'm going wrong or is there no way to add a sensor to the widget?
I think that sensor widget will not be applicable this way, you should extends Activity instead of AppWidgetProvider and do not forget registerListener/unregisterListener, you can do something more you can add activity class to the widget manifest and put your code within this class as normal, from widget you can setOnClickPendingIntent a button to this Activity.
Related
I want to show the floating layout on top of the screen when service Alarm or Call happened. Normally, when the app opens or it is in the background (before swiping it out) it shows and works well. even if I kill the app it still shows (kill = swipe the app)and it is still working. but, if the app is killed and not opened it tries to show (from service of alarm for example) it crashes and I cant even see the crash log in the android studio after terminating the app.
how can I fix that or find the issue?
my code Alarm BroadCast where it called: (the alarm broadcast called as needed)
public class BroadcastManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent = new Intent(context,FloatingWindow.class);
startService(intent);
}
my floating view code :
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.greenbook.greenlids.MainActivity;
import com.example.greenbook.greenlids.R;
public class FloatingWindow extends Service {
private WindowManager windowManager;
private LinearLayout layout;
private TextView txt;
private Button bttn1 , exitBttn;
private Context context;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
layout = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setBackgroundColor(Color.argb(255,0,0,255));
layout.setLayoutParams(layoutParams);
final WindowManager.LayoutParams windowParams;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
windowParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
windowParams.x = 0;
windowParams.y = 0;
windowParams.gravity = Gravity.CENTER;
}else{
windowParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
windowParams.x = 0;
windowParams.y = 0;
windowParams.gravity = Gravity.CENTER;
}
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
if (layoutInflater != null) {
layout = (LinearLayout) layoutInflater.inflate(R.layout.linear_layout_floating_window, null);
}
layout.setBackgroundColor(Color.argb(255,240,240,255));
bttn1 = layout.findViewById(R.id.LLbutton);
exitBttn = layout.findViewById(R.id.exitBttn);
txt = layout.findViewById(R.id.noteTxt);
txt.setTextSize(18);
txt.setText("Natan");
exitBttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
windowManager.removeView(layout);
stopSelf();
}
});
bttn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean handler = new Handler().postDelayed(new Runnable() {
#Override
public void run() {
txt.setText("Natan The King");
}
}, 1000*5);
}
});
windowManager.addView(layout,windowParams);
layout.setOnTouchListener(new View.OnTouchListener() {
private WindowManager.LayoutParams updateParam = windowParams;
int x , y;
float touchedX , touchedY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
x = updateParam.x;
y = updateParam.y;
touchedX = event.getRawX();
touchedY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
updateParam.x = (int) (x+event.getRawX() - touchedX);
updateParam.y = (int) (y+event.getRawY() - touchedY);
windowManager.updateViewLayout(layout,updateParam);
break;
}
return false;
}
});
}
}
logcat updated:
06-18 11:59:00.263 6722-6722/? E/Zygote: isWhitelistProcess - Process is Whitelisted
06-18 11:59:00.264 6722-6722/? E/libpersona: scanKnoxPersonas
Couldn't open the File - /data/system/users/0/personalist.xml - No such file or directory
06-18 11:59:00.268 6722-6722/? W/SELinux: SELinux selinux_android_compute_policy_index : Policy Index[2], Con:u:r:zygote:s0 RAM:SEPF_SM-G935F_8.0.0_0007, [-1 -1 -1 -1 0 1]
06-18 11:59:00.269 6722-6722/? I/SELinux: SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=com.example.greenbook.greenlids
06-18 11:59:00.275 6722-6722/? I/zygote64: Late-enabling -Xcheck:jni
06-18 11:59:00.341 6722-6722/? D/TimaKeyStoreProvider: TimaKeyStore is not enabled: cannot add TimaSignature Service and generateKeyPair Service
06-18 11:59:00.341 6722-6722/? D/ActivityThread: Added TimaKeyStore provider
06-18 11:59:00.422 6722-6722/com.example.greenbook.greenlids I/zygote64: no shared libraies, dex_files: 1
06-18 11:59:00.723 6722-6722/com.example.greenbook.greenlids I/InstantRun: starting instant run server: is main process
06-18 11:59:00.750 6722-6722/com.example.greenbook.greenlids D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-18 11:59:00.755 6722-6722/com.example.greenbook.greenlids E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.greenbook.greenlids, PID: 6722
java.lang.RuntimeException: Unable to start receiver com.example.greenbook.greenlids.models.BroadcastManager: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.example.greenbook.greenlids/.floating_window.FloatingWindow }: app is in background uid UidRecord{1651455 u0a451 RCVR idle procs:1 seq(0,0,0)}
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3399)
at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1780)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.example.greenbook.greenlids/.floating_window.FloatingWindow }: app is in background uid UidRecord{1651455 u0a451 RCVR idle procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1538)
at android.app.ContextImpl.startService(ContextImpl.java:1484)
at android.content.ContextWrapper.startService(ContextWrapper.java:663)
at android.content.ContextWrapper.startService(ContextWrapper.java:663)
at com.example.greenbook.greenlids.models.BroadcastManager.onReceive(BroadcastManager.java:40)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3392)
at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1780)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Under certain circumstances, a background app is placed on a temporary whitelist for several minutes. While an app is on the whitelist, it can launch services without limitation, and its background services are permitted to run. An app is placed on the whitelist when it handles a task that's visible to the user, such as:
Handling a high-priority Firebase Cloud Messaging (FCM) message.
Receiving a broadcast, such as an SMS/MMS message.
Executing a PendingIntent from a notification.
Starting a VpnService before the VPN app promotes itself to the foreground.
taked from the link below
i found the answer here:
https://stackoverflow.com/a/46445436/8675712
https://stackoverflow.com/a/47654126/8675712
I tried to import an SQLite sample code into my Android application to save and manage my data through SQLite, using a ListView.
In this SQLite sample that implements an AddressBook when I fill in the text fields of a new contact and I press "Save" button to save them to my SQLite, then my Android app crashes, displaying that unfortunately my application has terminated.I believe that my problem is focused on the button Save(button1) and especially line: android:onClick="run" but I don't understand the exact problem.For your convenience method "run" is implemented in DisplayContact.java archive.
The code of my button1 in my activity_display_contact.xml layout is:
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="#string/save" />
The code of my DisplayContact.java which is responsible for tha layout of ListView is :
package com.qualcomm.QCARSamples.ImageTargets;
import com.qualcomm.QCARSamples.ImageTargets1.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayContact extends Activity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;
TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));
if (!rs.isClosed())
{
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence)phon);
phone.setFocusable(false);
phone.setClickable(false);
email.setText((CharSequence)emai);
email.setFocusable(false);
email.setClickable(false);
street.setText((CharSequence)stree);
street.setFocusable(false);
street.setClickable(false);
place.setText((CharSequence)plac);
place.setFocusable(false);
place.setClickable(false);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
}
else{
getMenuInflater().inflate(R.menu.mainmenu, menu);
}
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);
street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);
place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),com.qualcomm.QCARSamples.ImageTargets.MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view)
{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),com.qualcomm.QCARSamples.ImageTargets.MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else{
if(mydb.insertContact(name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),com.qualcomm.QCARSamples.ImageTargets.MainActivity.class);
startActivity(intent);
}
}
}
}
and the code of my Logcat is the following:
04-07 04:09:25.113: E/AndroidRuntime(7943): FATAL EXCEPTION: main
04-07 04:09:25.113: E/AndroidRuntime(7943): java.lang.IllegalStateException: Could not find a method run(View) in the activity class com.qualcomm.QCARSamples.ImageTargets.ImageTargets for onClick handler on view class android.widget.Button with id 'button1'
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.view.View$1.onClick(View.java:3050)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.view.View.performClick(View.java:3534)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.view.View$PerformClick.run(View.java:14263)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.os.Handler.handleCallback(Handler.java:605)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.os.Handler.dispatchMessage(Handler.java:92)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.os.Looper.loop(Looper.java:137)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.app.ActivityThread.main(ActivityThread.java:4441)
04-07 04:09:25.113: E/AndroidRuntime(7943): at java.lang.reflect.Method.invokeNative(Native Method)
04-07 04:09:25.113: E/AndroidRuntime(7943): at java.lang.reflect.Method.invoke(Method.java:511)
04-07 04:09:25.113: E/AndroidRuntime(7943): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-07 04:09:25.113: E/AndroidRuntime(7943): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-07 04:09:25.113: E/AndroidRuntime(7943): at dalvik.system.NativeStart.main(Native Method)
04-07 04:09:25.113: E/AndroidRuntime(7943): Caused by: java.lang.NoSuchMethodException: run [class android.view.View]
04-07 04:09:25.113: E/AndroidRuntime(7943): at java.lang.Class.getConstructorOrMethod(Class.java:460)
04-07 04:09:25.113: E/AndroidRuntime(7943): at java.lang.Class.getMethod(Class.java:915)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.view.View$1.onClick(View.java:3043)
04-07 04:09:25.113: E/AndroidRuntime(7943): ... 11 more
This is weird: Your Java code creates an Activity called "DisplayContact" but the stacktrace says it cannot find an onClick handler called "run" in an Activity called "ImageTargets". I would check the way your development project has been set up.
I am trying to have an alert appear on a certain time. I was able to do that, but when I press the snooze button it works, I get another alert but I also get some errors.
Find the errors below:
11-19 12:50:26.755: E/AndroidRuntime(452): FATAL EXCEPTION: main
11-19 12:50:26.755: E/AndroidRuntime(452): java.lang.NullPointerException
11-19 12:50:26.755: E/AndroidRuntime(452): at android.app.PendingIntent.getActivity(PendingIntent.java:191)
11-19 12:50:26.755: E/AndroidRuntime(452): at com.example.servicealarmdemo2.MainActivity.repeat(MainActivity.java:124)
11-19 12:50:26.755: E/AndroidRuntime(452): at com.example.servicealarmdemo2.AlertDemo$2.onClick(AlertDemo.java:58)
11-19 12:50:26.755: E/AndroidRuntime(452): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:159)
11-19 12:50:26.755: E/AndroidRuntime(452): at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 12:50:26.755: E/AndroidRuntime(452): at android.os.Looper.loop(Looper.java:123)
11-19 12:50:26.755: E/AndroidRuntime(452): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-19 12:50:26.755: E/AndroidRuntime(452): at java.lang.reflect.Method.invokeNative(Native Method)
11-19 12:50:26.755: E/AndroidRuntime(452): at java.lang.reflect.Method.invoke(Method.java:507)
11-19 12:50:26.755: E/AndroidRuntime(452): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-19 12:50:26.755: E/AndroidRuntime(452): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-19 12:50:26.755: E/AndroidRuntime(452): at dalvik.system.NativeStart.main(Native Method)
the function that repeats the alert is in MainActivity.java
public void repeat() {
Intent i = new Intent("com.example.servicealarmdemo2.demoactivity");
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
long time= System.currentTimeMillis();
EditText text=(EditText)findViewById(R.id.editText1);
String str = text.getText().toString();
long t=Long.parseLong(str);
alarmManager.set(AlarmManager.RTC_WAKEUP, time+( t*60*1000), operation);
}
and the following two classes are for the alerts:
AlertDemo.java
package com.example.servicealarmdemo2;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;
public class AlertDemo extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
/** Turn Screen On and Unlock the keypad when this alert dialog is displayed */
getActivity().getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD);
/** Creating a alert dialog builder */
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
/** Setting title for the alert dialog */
builder.setTitle("Alarm");
/** Setting the content for the alert dialog */
builder.setMessage("An Alarm by AlarmManager");
/** Defining an OK button event listener */
builder.setPositiveButton("Take", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/** Exit application on click OK */
getActivity().finish();
}
});
builder.setNegativeButton("Snooze", new OnClickListener() {
// #Override
public void onClick(DialogInterface dialog, int which) {
/** Exit application on click OK */
//getActivity().finish();
// repeat();
System.out.println("REPEAT");
new MainActivity().repeat();
//System.out.println("Activities: "+m);
}
});
/** Creating the alert dialog window */
return builder.create();
}
/** The application should be exit, if the user presses the back button */
#Override
public void onDestroy() {
super.onDestroy();
getActivity().finish();
}
// public void repeat() {
// MainActivity.repeat();
// }
// public void repeat() {
// Intent i = new Intent("com.example.servicealarmdemo2.demoactivity");
//// PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
// PendingIntent operation = PendingIntent.getActivity(getActivity().getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
// AlarmManager alarmManager = (AlarmManager) getActivity().getBaseContext().getSystemService(getActivity().ALARM_SERVICE);
// long time= System.currentTimeMillis();
// EditText text=(EditText)getActivity().findViewById(R.id.editText1);
// String str = text.getText().toString();
// long t=Long.parseLong(str);
// alarmManager.set(AlarmManager.RTC_WAKEUP, time+( t*60*1000), operation);
//
// }
}
and DemoActivity.java
package com.example.servicealarmdemo2;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;
public class DemoActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Creating an Alert Dialog Window */
AlertDemo alert = new AlertDemo();
/** Opening the Alert Dialog Window */
alert.show(getSupportFragmentManager(), "AlertDemo");
}
}
new MainActivity().repeat();
Never instantiate activities using new, only via Intent.
Reason for NPE is that the code is trying to use the activity as a Context but it has not been properly initialized for such use.
Technically, getBaseContext() returns null and getActivity() unconditionally calls a method on the passed-in context.
The way you did code its not look good, and Null-pointer is because of wrong Context.
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
Try to pass activity context while calling repeat() function.
new MainActivity().repeat(Activity context); //pass here activity context.
public void repeat(Activity ctx) {
Intent i = new Intent("com.example.servicealarmdemo2.demoactivity");
PendingIntent operation = PendingIntent.getActivity(ctx, 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
.
.
.
.
}
But not a good way to achieve!
Pretty new on this android stuff and gets a NullPointException that I can't seem to figure out. I am trying to implement an onResume() method in my CameraActivity and have moved almost all of the orginal code in onCreate() to onResume() and then call onResume() in onCreate(). The activity worked fine when the code was in onCreate(), but when placed in onResume() the exception arsises. What is causing it?
package com.example.tensioncamapp_project;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "PreviewAactivity";
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
this.mHolder = getHolder();
this.mHolder.addCallback(this);
}
/**Displays the picture on the camera */
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
this.mCamera.setPreviewDisplay(holder);
this.mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
this.mCamera.release();
this.mCamera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
//add things here
}
}
and my CameraActivityClass
package com.example.tensioncamapp_project;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.content.Intent;
import android.app.Activity;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
public class CameraActivity extends Activity {
private ImageButton captureButton;
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture;
private ImageView imageView;
private static final int STD_DELAY = 400;
private static final int MEDIA_TYPE_IMAGE = 1;
protected static final String TAG = "CameraActivity";
/**Starts up the camera */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
onResume();
}
/**Connects the capture button on the view to a listener
* and redirects the client to a preview of the captures image*/
private void addListenerOnButton() {
this.captureButton = (ImageButton) findViewById(R.id.button_capture_symbol);
this.captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View capturebutton) {
mCamera.takePicture(null, null, mPicture);
delay();
Intent viewPic = new Intent(CameraActivity.this, ViewPicActivity.class);
startActivity(viewPic);
}
});
}
/** A safe way to get an instance of the Camera object. Code collected from elsewhere */
public static Camera getCameraInstance(){
Camera c = null;
try {
// attempt to get a Camera instance
c = Camera.open();
//getting current parameters
Camera.Parameters params = c.getParameters();
//setting new parameters with flash
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
c.setParameters(params);
}
catch (Exception e){
// camera is not available (in use or does not exist)
}
// returns null if camera is unavailable
return c;
}
/**Generates a delay needed for application to save new pictures */
private void delay(){
try {
//Makes the program inactive for a specific amout of time
Thread.sleep(STD_DELAY);
} catch (Exception e) {
e.getStackTrace();
}
}
/**Method for releasing the camera immediately on pause event*/
#Override
protected void onPause() {
super.onPause();
//Shuts down the preview shown on the screen
mCamera.stopPreview();
//Calls an internal help method to restore the camera
releaseCamera();
}
/**Help method to release the camera */
private void releaseCamera(){
//Checks if there is a camera object active
if (this.mCamera != null){
//Releases the camera
this.mCamera.release();
//Restore the camera object to its initial state
this.mCamera = null;
}
}
/**Activates the camera and makes it appear on the screen */
protected void onResume() {
// TODO Auto-generated method stub
// deleting image from external storage
FileHandler.deleteFromExternalStorage();
// Create an instance of Camera.
this.mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
this.mPreview = new CameraPreview(this, this.mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(this.mPreview);
//add the capture button
addListenerOnButton();
// In order to receive data in JPEG format
this.mPicture = new PictureCallback() {
/**Creates a file when a image is taken, if the file doesn't already exists*/
#Override
public void onPictureTaken(byte[] data, Camera mCamera) {
File pictureFile = FileHandler.getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions");
return;
}
try {
//Writes the image to the disc
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
super.onResume();
}
}
Log cat:
05-21 14:32:05.424: D/OpenGLRenderer(1030): Enabling debug mode 0
05-21 14:32:10.986: E/CameraActivity(1030): camera not availableFail to connect to camera service
05-21 14:32:11.033: I/Choreographer(1030): Skipped 66 frames! The application may be doing too much work on its main thread.
05-21 14:32:11.203: W/EGL_emulation(1030): eglSurfaceAttrib not implemented
05-21 14:32:13.013: D/AndroidRuntime(1030): Shutting down VM
05-21 14:32:13.013: W/dalvikvm(1030): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-21 14:32:13.083: E/AndroidRuntime(1030): FATAL EXCEPTION: main
05-21 14:32:13.083: E/AndroidRuntime(1030): java.lang.NullPointerException
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.example.tensioncamapp_project.CameraPreview.surfaceCreated(CameraPreview.java:33)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView.updateWindow(SurfaceView.java:569)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView.access$000(SurfaceView.java:86)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:174)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:680)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1842)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer.doFrame(Choreographer.java:532)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Handler.handleCallback(Handler.java:725)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Handler.dispatchMessage(Handler.java:92)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Looper.loop(Looper.java:137)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-21 14:32:13.083: E/AndroidRuntime(1030): at java.lang.reflect.Method.invokeNative(Native Method)
05-21 14:32:13.083: E/AndroidRuntime(1030): at java.lang.reflect.Method.invoke(Method.java:511)
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-21 14:32:13.083: E/AndroidRuntime(1030): at dalvik.system.NativeStart.main(Native Method)
The solution was to call the getCameraInstancemethod() in onResume() in an if-statement
protected void onResume() {
// TODO Auto-generated method stub
// deleting image from external storage
FileHandler.deleteFromExternalStorage();
// Create an instance of Camera.
if (this.mCamera == null){
this.mCamera = getCameraInstance();}
I think your problem is here
this.mPreview = new CameraPreview(this, this.mCamera);
this.mCamera seems to be null, it's not be set a new instance of the class, this needs to be done in the getCameraInstance() method.
getCameraInstance() returns null if an exception was thrown.
This cause the NPE as this.mCamera is null.
You should check if an exception was thrown in getCameraInstance and handle it correctly. The most basic thing is to log it and try to understand the reason.
I am working on an app and I want the app to use text to speech to tell the user what button they have just pressed. I am having problems getting my button to work properly with the two conflicting activities. I am able to make it work either doing only text to speech or only when pressing it goes to a different page, but I can't get it to do both at the same time. Currently it sends the user to the new menu without playing the text to speech but I am finally getting an error from my LogCat so I figured it is fixable. I have included my LogCat and the java. I have commented above and below where the problem code is.
07-25 12:52:35.031: E/ActivityThread(328): Activity com.example.com.proto1.menu has leaked ServiceConnection android.speech.tts.TextToSpeech$1#4051eb10 that was originally bound here
07-25 12:52:35.031: E/ActivityThread(328): android.app.ServiceConnectionLeaked: Activity com.example.com.proto1.menu has leaked ServiceConnection android.speech.tts.TextToSpeech$1#4051eb10 that was originally bound here
07-25 12:52:35.031: E/ActivityThread(328): at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:938)
07-25 12:52:35.031: E/ActivityThread(328): at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:833)
07-25 12:52:35.031: E/ActivityThread(328): at android.app.ContextImpl.bindService(ContextImpl.java:867)
07-25 12:52:35.031: E/ActivityThread(328): at android.content.ContextWrapper.bindService(ContextWrapper.java:347)
07-25 12:52:35.031: E/ActivityThread(328): at android.speech.tts.TextToSpeech.initTts(TextToSpeech.java:467)
07-25 12:52:35.031: E/ActivityThread(328): at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:433)
07-25 12:52:35.031: E/ActivityThread(328): at com.example.com.proto1.menu.onActivityResult(menu.java:122)
07-25 12:52:35.031: E/ActivityThread(328): at android.app.Activity.dispatchActivityResult(Activity.java:3908)
07-25 12:52:35.031: E/ActivityThread(328): at android.app.ActivityThread.deliverResults(ActivityThread.java:2528)
07-25 12:52:35.031: E/ActivityThread(328): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574)
07-25 12:52:35.031: E/ActivityThread(328): at android.app.ActivityThread.access$2000(ActivityThread.java:117)
07-25 12:52:35.031: E/ActivityThread(328): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961)
07-25 12:52:35.031: E/ActivityThread(328): at android.os.Handler.dispatchMessage(Handler.java:99)
07-25 12:52:35.031: E/ActivityThread(328): at android.os.Looper.loop(Looper.java:123)
07-25 12:52:35.031: E/ActivityThread(328): at android.app.ActivityThread.main(ActivityThread.java:3683)
07-25 12:52:35.031: E/ActivityThread(328): at java.lang.reflect.Method.invokeNative(Native Method)
07-25 12:52:35.031: E/ActivityThread(328): at java.lang.reflect.Method.invoke(Method.java:507)
07-25 12:52:35.031: E/ActivityThread(328): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-25 12:52:35.031: E/ActivityThread(328): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-25 12:52:35.031: E/ActivityThread(328): at dalvik.system.NativeStart.main(Native Method)
menu.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.speech.tts.TextToSpeech;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
#SuppressWarnings("unused")
public class menu extends Activity implements TextToSpeech.OnInitListener,
OnClickListener {
TextToSpeech mTts;
Button speakButton;
// TTS object
public TextToSpeech myTTS;
// status check code
public int MY_DATA_CHECK_CODE = 0;
#Override
protected void onCreate(Bundle aboutmenu) {
// TODO Auto-generated method stub
super.onCreate(aboutmenu);
setContentView(R.layout.mainx);
SpeakingAndroid speak = new SpeakingAndroid();
// get a reference to the button element listed in the XML layout
speakButton = (Button) findViewById(R.id.btn_speak);
// listen for clicks
speakButton.setOnClickListener(this);
// check for TTS data
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
// Setting up the button references
Button info = (Button) findViewById(R.id.aboutbutton);
Button voice = (Button) findViewById(R.id.voicebutton);
info.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("android.intent.action.INFOSCREEN"));
}
});
voice.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
} catch (Exception e) {
}
}
});
// This is the start of the problem area
starteyephone();
{
speakButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent voiceIntent = new Intent(
"android.intent.action.RECOGNITIONMENU");
startActivity(voiceIntent);
}
});
}
}
private void starteyephone() {
// TODO Auto-generated method stub
}
// respond to button clicks
public void onClick(View v) {
// get the text entered
speakButton = (Button) findViewById(R.id.btn_speak);
String words = speakButton.getText().toString();
speakWords(words);
}
//this is the end of the problem area
// speak the user text
public void speakWords(String speech) {
// speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
// act on result of TTS data check
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
} else {
// no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
// setup TTS
public void onInit(int initStatus) {
// check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
}
I see a number of problems here:
You initialize the TextToSpeech using the Context of the menu activity. That means that when the menu activity is destroyed, the TextToSpeech instance will be leaked because it is never properly shutdown (this is probably why you see that error in your logcat). You need to either call myTTS.shutdown() in menu.onDestroy() or you need to pass getApplicationContext() as the context parameter when initializing TextToSpeech here:
myTTS = new TextToSpeech(getApplicationContext(), this);
Note: If you use the application context, then you need to determine when you don't need the TTS anymore and call shutdown() on it at that time.
You are using android.intent.action.RECOGNITIONMENU but this Intent is used for speech recognition (ie: Speech to text), not Text to Speech. I don't understand what you are trying to do here.
I still don't understand your exact problem. It seems to me that the code you have posted should speak the text of the button. What else do you expect to happen here?
EDIT: Add observation
I see now that you are calling setOnClickListener() on the speakButton twice. Once at the beginning of onCreate() and then again in your "problem section". You can't set more than one onClickListener, so the first one is overwritten. You should just move this code:
Intent voiceIntent = new Intent("android.intent.action.RECOGNITIONMENU");
startActivity(voiceIntent);
into your existing onClick() method.