user1502224
user1502224

Reputation: 105

My application stops responding

So whenever I launch my app on my devices it runs fine but when I push a button it does nothing excepted stay highlited and then pops up saying its not responding here is the code. I think its the way I have the code in the OnClickListerner. package com.dicamillo.alarm;

import java.util.Calendar;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.TimePicker;

public class AlarmlockActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    TimePicker tp;
    Button set;
    int hour;
    int minuet;
    DigitalClock dc;
    Calendar calendar = Calendar.getInstance();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tp = (TimePicker) findViewById(R.id.tpAlarmTime);
    set = (Button) findViewById(R.id.bSet);
    dc = (DigitalClock) findViewById(R.id.digitalClock1);
    hour = calendar.get(Calendar.HOUR);
    minuet = calendar.get(Calendar.MINUTE);
    set.setOnClickListener(this);

}

public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bSet:
        while (tp.getCurrentHour().intValue() != hour
                && tp.getCurrentMinute().intValue() != minuet) {
            tp.getCurrentHour().intValue();
            tp.getCurrentMinute().intValue();
            if (tp.getCurrentHour().intValue() == hour
                    && tp.getCurrentMinute().intValue() == minuet) {
                MediaPlayer mp = MediaPlayer.create(AlarmlockActivity.this,
                        R.raw.alarm);
            } 
        }
        break;
    }
}

}

Upvotes: 0

Views: 161

Answers (3)

louis1204
louis1204

Reputation: 411

Did you try checking the logcat?!

Upvotes: 0

wnafee
wnafee

Reputation: 2136

Your while will basically loop forever on the main UI thread until the hour/minute from your TimePicker matches the current time. That's what's causing the ANR message from the OS.

You shouldn't be running long operations on the UI thread. Either use Threads or Handlers or AsyncTasks to achieve the result you want.

Upvotes: 0

Krylez
Krylez

Reputation: 17800

Anything in the onClick method runs on the UI thread. Your while loop is hanging the app and the OS is (rightfully) forcing it to stop.

Look into using an AsyncTask to get your code off the UI thread. You should also pause after each loop iteration to avoid unnecessary CPU usage.

Upvotes: 2

Related Questions