Android Java:Stopping a thread without crashing - java

I created an android app that tests your reflects speed.
at first the app is still
when you press(State 0) the app starts a thread that waits a couple of seconds before showing a green screen.
When the green screen is shown(State 1) you have to press as fast as you can.
if you press the green(state 2) you are shown the reflect time
the problem I'm having that when a person clicks too soon, i have to stop the thread which causes the app to crash(thread.stop()).
Any suggestions?
public class MainActivity extends Activity implements OnClickListener{
TextView tvs,tvas;
RelativeLayout rl;
int state; //0=red 1=green 2=tapped-green
long end,start,result;
Thread th;
Boolean dont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rl = (RelativeLayout) findViewById(R.id.rl);
tvs = (TextView) findViewById(R.id.tvs);
tvas = (TextView) findViewById(R.id.tvas);
dont=true;
state=0;
Typeface myTypeface = Typeface.createFromAsset(this.getAssets(),"RobotoCondensed-Bold.ttf");
tvs.setTypeface(myTypeface);
tvas.setTypeface(myTypeface);
rl.setOnClickListener(this);
tvs.setOnClickListener(this);
tvas.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (state) {
case 0:
tvs.setText("Any Min Now");
rl.setBackgroundColor(Color.rgb(255, 68, 68));
final Handler mHandler = new Handler();
state=1;
dont=true;
th = new Thread((new Runnable() {public void run() {while (true){try {Thread.sleep(randInt());mHandler.post(new Runnable() {public void run() {
if(dont){ //not helping
rl.setBackgroundColor(Color.GREEN);
start = SystemClock.uptimeMillis();
state=2;
}
}});} catch (Exception e) {}}}}));
th.start();
break;
case 1:
tvs.setText("Too Soon!");
tvas.setText("Tap AnyWhere To restart");
dont=false;
rl.setBackgroundColor(Color.rgb(255, 68, 68));
state=0;
break;
case 2:
end = SystemClock.uptimeMillis();
result=end-start;
tvs.setText("UR Reaction Time= "+result+"ms");
tvas.setText("Tap AnyWhere To restart");
state=0;
dont=false;
th.interrupt(); //giving me wrong numbers
break;
}
}
public static int randInt() { //creates a random number
Random rand = new Random();
int randomNum = rand.nextInt((6000 - 2000) + 1) + 2000;
return randomNum;
}
}
LogCat:
03-07 22:16:05.575: I/WindowState(840): WIN DEATH: Window{45b08280 u0 com.afm.reflects/com.afm.reflects.MainActivity}
03-07 22:16:05.575: I/ActivityManager(840): Process com.afm.reflects (pid 32055) (adj 11) has died.
03-07 22:16:52.391: V/SmartFaceService - 3rd party pause(840): onReceive
[android.intent.action.ACTIVITY_STATE/com.afm.reflects/create]
03-07 22:17:03.471: E/AndroidRuntime(864): Process: com.afm.reflects, PID: 864
03-07 22:17:03.471: E/AndroidRuntime(864): at com.afm.reflects.MainActivity.onClick(MainActivity.java:73)
03-07 22:17:03.482: W/ActivityManager(840): Force finishing activity com.afm.reflects/.MainActivity
03-07 22:17:03.522: V/SmartFaceService - 3rd party pause(840): onReceive
[android.intent.action.ACTIVITY_STATE/com.afm.reflects/pause]
03-07 22:17:03.562: D/CrashAnrDetector(840): processName: com.afm.reflects
03-07 22:17:03.562: D/CrashAnrDetector(840): broadcastEvent : com.afm.reflects data_app_crash
03-07 22:17:05.634: I/ActivityManager(840): Process com.afm.reflects (pid 864) (adj 9) has died.
03-07 22:17:05.644: I/WindowState(840): WIN DEATH: Window{45514be0 u0 com.afm.reflects/com.afm.reflects.MainActivity}
03-07 22:18:53.869: V/SmartFaceService - 3rd party pause(840): onReceive
[android.intent.action.ACTIVITY_STATE/com.afm.reflects/create]
03-07 22:19:11.867: E/AndroidRuntime(1649): Process: com.afm.reflects, PID: 1649
03-07 22:19:11.867: E/AndroidRuntime(1649): at com.afm.reflects.MainActivity.onClick(MainActivity.java:73)
03-07 22:19:11.877: W/ActivityManager(840): Force finishing activity com.afm.reflects/.MainActivity
03-07 22:19:11.917: D/CrashAnrDetector(840): processName: com.afm.reflects
03-07 22:19:11.917: V/SmartFaceService - 3rd party pause(840): onReceive
[android.intent.action.ACTIVITY_STATE/com.afm.reflects/pause]
03-07 22:19:11.927: D/CrashAnrDetector(840): broadcastEvent : com.afm.reflects data_app_crash

Related

App works on emulator but not real device

I just uploaded my app to google play and then installed it on my android phone which is running android 2.3.5. Anyways everything worked perfect on the emulator but crashes right on start up on the real device. Any ideas? here's the code.
public class StopWatch extends Activity implements OnClickListener {
//PROPERTIES USED THROUGHOUT CLASS
private Random rand = new Random();
private TextView stopWatchC;
private Button startButton,stopButton,resetButton;
private RelativeLayout mainLayout;
private Handler handle;
private Handler backHand = new Handler();
private boolean timerIsRunning;
private boolean previouslyStarted;
private long startTime;
private long endTime;
private long runTime;
private long UPDATE_EVERY = 200;
private int backgrounds[] = {
R.drawable.woman_1,
R.drawable.woman_2,
R.drawable.woman_3,
R.drawable.woman_4,
R.drawable.woman_5,
R.drawable.woman_6,
R.drawable.woman_7,
R.drawable.woman_8,
R.drawable.woman_9
};
//END PROPERTY DECLARATIONS
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stopwatch);
//Start our service
startService(new Intent(this,StopwatchService.class));
//SETUP BUTTON AND TEXTVIEWS
stopWatchC = (TextView) findViewById(R.id.counter);
startButton = (Button) findViewById(R.id.start_button);
stopButton = (Button) findViewById(R.id.stop_button);
resetButton = (Button) findViewById(R.id.reset);
mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
//Handles listening for clicks on our start,stop and reset buttons
startButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
resetButton.setOnClickListener(this);
//Calls run method for changing backgrounds
backHand.postDelayed(backgroundUpdate, 300);
}
/**
* Handles displaying the counter
*/
public void SWCounterDisplay()
{
String display;
long now;
long difference;
long secs;
long mins;
long hours;
if(timerIsRunning == true)
{
now = System.currentTimeMillis();
}else{
now = endTime;
}
if(previouslyStarted == true){
difference = runTime + (now - startTime);
}else{
difference = now-startTime;
}
//No negative numbers
if(difference < 0)
{
difference = 0;
}
secs = difference/1000;
mins = secs/60;
hours = mins/60;
secs = secs%60;
mins = mins%60;
display = String.format("%d", hours) + ":" +
String.format("%02d",mins) + ":" +
String.format("%02d", secs);
stopWatchC.setText(display);
}
/**
* Reset the timer
*/
public void resetTimer()
{
timerIsRunning = false;
previouslyStarted = false;
stopButton.setEnabled(false);
startButton.setEnabled(true);
runTime = 0;
SWCounterDisplay();
handle.removeCallbacks(timerUpdate);
handle = null;
}
/**
* Starts the stop watch
*/
public void startTimer()
{
timerIsRunning = true;
stopButton.setEnabled(timerIsRunning);
startButton.setEnabled(false);
if(!previouslyStarted){
previouslyStarted = true;
runTime = 0;
}
startTime = System.currentTimeMillis();
//Create new handler
handle = new Handler();
handle.postDelayed(timerUpdate, UPDATE_EVERY);
}
/**
* Stops the timer
*/
public void stopTimer()
{
timerIsRunning = false;
stopButton.setEnabled(timerIsRunning);
startButton.setEnabled(true);
endTime = System.currentTimeMillis();
runTime += endTime-startTime;
handle.removeCallbacks(timerUpdate);
handle = null;
}
/**
* Handles any onClick events
*/
#Override
public void onClick(View v) {
if(v == startButton)
{
startTimer();
}else if(v == stopButton)
{
stopTimer();
}else if(v == resetButton)
{
resetTimer();
}
}
/**
* Changes the background every 20 Seconds
*/
private Runnable backgroundUpdate = new Runnable(){
#Override
public void run() {
mainLayout.setBackgroundResource(backgrounds[rand.nextInt(backgrounds.length)]);
backHand.postDelayed(this, 60000);
}
};
/**
* Handles updating the timer
*/
private Runnable timerUpdate = new Runnable(){
#Override
public void run() {
SWCounterDisplay();
if(handle != null){
handle.postDelayed(this, UPDATE_EVERY);
}
}
};
/**
* Call run method if timer is still running
*/
public void onStart()
{
super.onStart();
if(timerIsRunning == true)
{
handle = new Handler();
handle.postDelayed(timerUpdate, UPDATE_EVERY);
}
}
/**
* Stop the timer if timer is still running
*/
public void onStop()
{
super.onStop();
if(timerIsRunning == true)
{
handle.removeCallbacks(timerUpdate);
handle = null;
}
}
/**
* Resume when the onResume method is called
*/
public void onResume()
{
super.onResume();
if(timerIsRunning == true){
stopButton.setEnabled(true);
startButton.setEnabled(false);
}else{
stopButton.setEnabled(false);
startButton.setEnabled(true);
}
SWCounterDisplay();
}
package com.webdeveloper93.stopwatch;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class StopwatchService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public int onStartCommand(Intent intent,int flags,int startId)
{
Log.d("StopwatchService:","SERVICE STARTED");
super.onStartCommand(intent, flags, startId);
return START_NOT_STICKY;
}
public void onDestroy()
{
Log.d("StopwatchService:","SERVICE DESTROYED");
super.onDestroy();
}
}
Thanks in advance
EDIT
I/ActivityManager( 132): No longer want com.google.android.gsf.login (pid 1140): hidden #16
D/WifiService( 132): ACTION_BATTERY_CHANGED pluggedType: 0
I/ActivityManager( 132): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.webdeveloper93.stopwatch/.StopWatch } from pid 231
E/AndroidRuntime( 1186): FATAL EXCEPTION: main
E/AndroidRuntime( 1186): java.lang.NoSuchMethodError: android.os.StrictMode$VmPolicy$Builder.detectLeakedClosableObjects
E/AndroidRuntime( 1186): at com.webdeveloper93.stopwatch.StopWatch.onCreate(StopWatch.java:59)
E/AndroidRuntime( 1186): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime( 1186): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
E/AndroidRuntime( 1186): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
E/AndroidRuntime( 1186): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
E/AndroidRuntime( 1186): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
E/AndroidRuntime( 1186): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 1186): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime( 1186): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime( 1186): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 1186): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 1186): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
E/AndroidRuntime( 1186): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
E/AndroidRuntime( 1186): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 132): Force finishing activity com.webdeveloper93.stopwatch/.StopWatch
W/ActivityManager( 132): Activity pause timeout for HistoryRecord{408ff850 com.webdeveloper93.stopwatch/.StopWatch}
W/InputMethodManagerService( 132): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#405ca178
I/ActivityManager( 132): Process com.webdeveloper93.stopwatch (pid 1186) has died.
W/ActivityManager( 132): Service crashed 2 times, stopping: ServiceRecord{4078c080 com.webdeveloper93.stopwatch/.StopwatchService}
W/ActivityManager( 132): Activity destroy timeout for HistoryRecord{408ff850 com.webdeveloper93.stopwatch/.StopWatch}
I/ActivityManager( 132): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=org.jtb.alogcat/.LogActivity } from pid 231
It looks like you use a method which is not implemented in android <=2.3.5. If you remove #SuppressLint("NewApi"), you will see which one it is.
I think it works in your emulator because you use a higher sdk-version there.

BadTokenException even after referring to Activity and not the application context

android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406a6678 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:528)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.Activity.showDialog(Activity.java:2569)
at android.app.Activity.showDialog(Activity.java:2527)
at MyCode$8$4.run(MyCode.java:557)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
at dalvik.system.NativeStart.main(Native Method)
I am getting above exception when following code is executed. This file dialog will shown once the processing is done and progressbar reaches 100%. FileSaveDialog extends Dialog and implements OnCompletionListener
runOnUiThread(new Runnable() {
#Override
public void run() {
showDialog(error.Code());//Line 557
}
});
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
final ScrollView scrollView = new ScrollView(this);
final TextView textView = new TextView(this);
switch (id) {
// Other cases are here
case 4:
File playFile = new File(mediaPath, TEMP_WAV_FILE_NAME);
dialog = new FileSaveDialog(this, getResources(),
playFile.getAbsolutePath(), saveDiscardHandler);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do whatever you want the back key to do
cleanUp();
}
});
break;
// Other cases are here
default:
dialog = null;
}
return dialog;
}
You must check activity isFinishing() If the activity is finishing, returns true; else returns false.

restarting CountDownTimer from another activity

i have this code to create a CountdownTimer:
CountDownTimer CountdownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
txttime.setText(millisUntilFinished / 1000 );
}
public void onFinish(){
timeout_stage();
}
}.start();
it works fine and i can cancel and start it perfectly, but i want to restart it from another activity. in main form i cancell it, the an activity opens like a dialogbox that has a "AGAIN" button. when i click on that, i want to CountDownTimer.start(); called and my counter restarts again...
how i can do this?
i do this in second activity:
MainActivity main = new MainActivity();
main.CountdownTimer.start();
but i get this error:
04-28 11:42:40.495: E/AndroidRuntime(17039): FATAL EXCEPTION: main
04-28 11:42:40.495: E/AndroidRuntime(17039): java.lang.NullPointerException
04-28 11:42:40.495: E/AndroidRuntime(17039): at com.english.game.MainActivity$1.onTick(MainActivity.java:70)
04-28 11:42:40.495: E/AndroidRuntime(17039): at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:124)
04-28 11:42:40.495: E/AndroidRuntime(17039): at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 11:42:40.495: E/AndroidRuntime(17039): at android.os.Looper.loop(Looper.java:137)
04-28 11:42:40.495: E/AndroidRuntime(17039): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-28 11:42:40.495: E/AndroidRuntime(17039): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 11:42:40.495: E/AndroidRuntime(17039): at java.lang.reflect.Method.invoke(Method.java:511)
04-28 11:42:40.495: E/AndroidRuntime(17039): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-28 11:42:40.495: E/AndroidRuntime(17039): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-28 11:42:40.495: E/AndroidRuntime(17039): at dalvik.system.NativeStart.main(Native Method)
I am not sure, because there is not enough code to do a proper analysis, but to me these lines look wrong:
MainActivity main = new MainActivity();
main.CountdownTimer.start();
When you initialize the main activity this way, no activity life cycle methods (onCreate(), onStart(), etc.) are called. My guess is, that the txttime (label?) is initialized in onCreate().
Additionally (and imho even worse), you would not restart the timer used in the actual main activity.
To ensure you have the correct main activity in your second activity I woud suggest you use the code from this answer.
You can create static handler in Activity1 and start your countDownTimer from there.
In second Activity you can access the static handler instance by Activity1.hander and you can send message from here to start or cancel the countDownTimer.
Don't create the instance of Activity1 by using new operator, instead this use Handler.
Activity1.java
public class Activity1 extends Activity {
public static Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initHandler();
mHandler.sendEmptyMessage(1);
startActivity(new Intent(Activity1.this, Activity2.class));
}
private void initHandler(){
mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch (msg.arg1) {
case 1:
mCountDownTimer.start();
break;
}
}
};
}
private CountDownTimer mCountDownTimer = new CountDownTimer(10000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Toast.makeText(Activity1.this, "Count is: "+ millisUntilFinished/1000, Toast.LENGTH_SHORT).show();
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
}
Activity2.java
public class Activity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity1.mHandler.sendEmptyMessage(1);
}
}
This sample code is only idea to do, please use this logic and let me know if any problem is coming...

button sound and reset button not functioning Android java

I am creating a simple Click Counter Android App using Java. I am new to Java. Here is my code below, the gui has different buttons with different functions, for example the count button itself, a reset count button, and a mute sound button.
public class wazeefa extends Activity {
//Count Button
TextView txtCount;
ImageView image;
Button btnCount;
Button wmute;
Button wreset;
public static int count=0;
SharedPreferences app_preferences;
MediaPlayer mpButtonClick;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
setContentView(R.layout.wazeefa);
//SAVE COUNT
app_preferences = this.getSharedPreferences("myPrefscount", MODE_WORLD_READABLE);
count = app_preferences.getInt("count", 0);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
//Button SOUND AND COUNT
mpButtonClick = MediaPlayer.create(this, R.raw.bubble);
//RESET Button
wreset = (Button)findViewById(R.id.wreset);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText(String.valueOf(count));
btnCount = (Button)findViewById(R.id.wclick);
btnCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
image = (ImageView) findViewById(R.id.imageview);
count++;
if (count > 50) count = 0; image.setImageResource(R.drawable.duroodimage);
if (count > 0) image.setImageResource(R.drawable.duroodimage);
if (count > 9) image.setImageResource(R.drawable.zikrimage);
if (count > 39) image.setImageResource(R.drawable.duroodimage);
txtCount.setText(String.valueOf(count));
}
});
wreset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count = 0;
image.setImageResource(R.drawable.duroodimage);;
txtCount.setText("0");
}
});
}
#Override
protected void onPause() {
super.onPause();
// save count value here
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
//MUTE button
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.wmute:
AudioManager.setMode(AudioManager.MODE_IN_CALL);
AudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
default:
AudioManager.setMode(AudioManager.MODE_NORMAL );
AudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
break;
}
}
I have 1 issue:
When I go back into the app and the count shows as '5' just for example, the Reset button no longer functions - it does nothing, I get an error message on AVD saying 'unfortunately 'App' has stopped'. But when I continue the count and then hit the Reset button it works changes the count to zero again
Any suggestions on the above issue, have I missed anything or placed code in the wrong areas? The button sound was working before I edited the code, to save the 'count' data.
Let me know if I'm being vague...
The Crash Log:
12-24 18:07:42.661: W/Trace(3633): Unexpected value from nativeGetEnabledTags: 0
12-24 18:07:42.741: D/AndroidRuntime(3633): Shutting down VM
12-24 18:07:42.741: W/dalvikvm(3633): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
12-24 18:07:42.811: E/AndroidRuntime(3633): FATAL EXCEPTION: main
12-24 18:07:42.811: E/AndroidRuntime(3633): java.lang.NullPointerException
12-24 18:07:42.811: E/AndroidRuntime(3633): at com.shaadcorp.wazaifapp.wazeefa$2.onClick(wazeefa.java:81)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.view.View.performClick(View.java:4202)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.view.View$PerformClick.run(View.java:17340)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.os.Handler.handleCallback(Handler.java:725)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.os.Handler.dispatchMessage(Handler.java:92)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.os.Looper.loop(Looper.java:137)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-24 18:07:42.811: E/AndroidRuntime(3633): at java.lang.reflect.Method.invokeNative(Native Method)
12-24 18:07:42.811: E/AndroidRuntime(3633): at java.lang.reflect.Method.invoke(Method.java:511)
12-24 18:07:42.811: E/AndroidRuntime(3633): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-24 18:07:42.811: E/AndroidRuntime(3633): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-24 18:07:42.811: E/AndroidRuntime(3633): at dalvik.system.NativeStart.main(Native Method)
12-24 18:07:48.842: I/Process(3633): Sending signal. PID: 3633 SIG: 9
12-24 18:07:51.572: E/Trace(3808): error opening trace file: No such file or directory (2)
I guess I didn't see mpButtonClick.start() anywhere in your code. That's why sound is not playing. Add mpButtonClick.start(). to your ClickListener.
fixed issue, thanks for your help Passionate Androiden.
public class wazeefa extends Activity {
//Count Button
TextView txtCount;
ImageView image;
Button btnCount;
Button wmute;
Button wreset;
public static int count=0;
SharedPreferences app_preferences;
MediaPlayer mpButtonClick;
AudioManager audioManager;
public static boolean mutestatus=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
setContentView(R.layout.wazeefa);
audioManager =
(AudioManager)getSystemService(Context.AUDIO_SERVICE);
//SAVE COUNT
app_preferences = this.getSharedPreferences("myPrefscount", MODE_WORLD_READABLE);
count = app_preferences.getInt("count", 0);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
image = (ImageView) findViewById(R.id.imageview);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
//Button SOUND AND COUNT
mpButtonClick = MediaPlayer.create(this, R.raw.bubble);
//RESET Button
wreset = (Button)findViewById(R.id.wreset);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText(String.valueOf(count));
btnCount = (Button)findViewById(R.id.wclick);
wmute=(Button)findViewById(R.id.wmute);
btnCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count++;
if (count > 50) count = 0; image.setImageResource(R.drawable.duroodimage);
if (count > 0) image.setImageResource(R.drawable.duroodimage);
if (count > 9) image.setImageResource(R.drawable.zikrimage);
if (count > 39) image.setImageResource(R.drawable.duroodimage);
txtCount.setText(String.valueOf(count));
mpButtonClick.start();
}
});
wreset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count = 0;
image.setImageResource(R.drawable.duroodimage);;
txtCount.setText("0");
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
});
wmute.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!mutestatus){
mutestatus=true;
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
Log.v("'test....",""+mutestatus);
}
else{
mutestatus=false;
audioManager.setMode(AudioManager.MODE_NORMAL );
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
Log.v("'test....",""+mutestatus);
}
}});
}
#Override
protected void onPause() {
super.onPause();
// save count value here
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
}

How to start activity from a popup window?

I have a custom popup window with it's own layout in my activity (code that responsible for the work of the popup window is in a separate class PopupWindowActivity). I want to appoint a button in this popup window opening activity. I tried some methods but app crashed with NullPointerException.
The code of this activity is following:
public class FirstActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView popupButton = (ImageView) this.findViewById(R.id.popup_btn);
likemenuButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupWindow dw = new PopupWindow(v);
dw.showLikePopDownMenu();
}
});
}
// my stuff
//popup window
private class PopupWindow extends PopupWindowActivity implements OnClickListener {
public PopupWindow(View anchor) {
super(anchor);
}
#Override
protected void onCreate() {
// inflate layout
LayoutInflater inflater =
(LayoutInflater) this.anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.popup, null);
// setup button events
ImageView aboutButton = (ImageView) findViewById(R.id.btn_about);
aboutButton.setOnClickListener(this);
this.setContentView(root);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_about: {
Intent activity = new Intent(FistActivity.this, About.class);
startActivity(activity);
break;
}
}
}}
}
In another way:
private static class PopupWindow extends PopupWindowActivity implements OnClickListener {
public PopupWindow(View anchor) {
super(anchor);
}
#Override
protected void onCreate() {
// inflate layout
LayoutInflater inflater =
(LayoutInflater) this.anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.popup, null);
// setup button events
ImageView searchButton = (ImageView) findViewById(R.id.btn_about);
algebraButton.setOnClickListener(this);
this.setContentView(root);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_about: {
Intent intent = new Intent();
intent.setClass(this, About.class);
startActivity(intent);
break;
}
default:
break;
}
}}
eclipse says that at first I should delete static from private static class PopupWindow extends PopupWindowActivity implements, then I have following for intent.setClass(this, About.class);:
The method setClass(Context, Class<?>) in the type Intent is not applicable for the arguments
(FirstActivity.PopupWindow, Class<About>)
Please, help.
Added log for first crash:
03-07 00:28:07.750: D/AndroidRuntime(12472): Shutting down VM
03-07 00:28:07.750: W/dalvikvm(12472): threadid=1: thread exiting with uncaught exception (group=0x40018578)
03-07 00:28:07.759: E/AndroidRuntime(12472): FATAL EXCEPTION: main
03-07 00:28:07.759: E/AndroidRuntime(12472): java.lang.NullPointerException
03-07 00:28:07.759: E/AndroidRuntime(12472): at com.example.FirstActivity$PopupWindow.onCreate(FirstActivity.java:110)
03-07 00:28:07.759: E/AndroidRuntime(12472): at com.quickaction.PopupWindowActivity.<init>(PopupWindowActivity.java:52)
03-07 00:28:07.759: E/AndroidRuntime(12472): at com.example.FirstActivity$PopupWindow.<init>(FirstActivity.java:97)
03-07 00:28:07.759: E/AndroidRuntime(12472): at com.example.FirstActivity$1.onClick(FirstActivity.java:30)
03-07 00:28:07.759: E/AndroidRuntime(12472): at android.view.View.performClick(View.java:2485)
03-07 00:28:07.759: E/AndroidRuntime(12472): at android.view.View$PerformClick.run(View.java:9080)
03-07 00:28:07.759: E/AndroidRuntime(12472): at android.os.Handler.handleCallback(Handler.java:587)
03-07 00:28:07.759: E/AndroidRuntime(12472): at android.os.Handler.dispatchMessage(Handler.java:92)
03-07 00:28:07.759: E/AndroidRuntime(12472): at android.os.Looper.loop(Looper.java:130)
03-07 00:28:07.759: E/AndroidRuntime(12472): at android.app.ActivityThread.main(ActivityThread.java:3687)
03-07 00:28:07.759: E/AndroidRuntime(12472): at java.lang.reflect.Method.invokeNative(Native Method)
03-07 00:28:07.759: E/AndroidRuntime(12472): at java.lang.reflect.Method.invoke(Method.java:507)
03-07 00:28:07.759: E/AndroidRuntime(12472): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
03-07 00:28:07.759: E/AndroidRuntime(12472): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
03-07 00:28:07.759: E/AndroidRuntime(12472): at dalvik.system.NativeStart.main(Native Method)
On button press:
Intent intent = new Intent("<your-intent-goes-here");
<context>.startActivity(intent);
There are a lot of ways to solve this. One would be to pass a reference to your Context via the constructor of the Dialog.

Categories