Нажатие кнопки заморозить приложение

1

Когда я нажимаю кнопку (метки в этом коде как mbutton), мое приложение зависает, по-видимому, без причины. logcat не дает информации о причине этого замораживания. код для всего класса ниже вместе с XML для класса ниже него

Код

public class WorkoutChoice extends Activity
{
 private TextView mDateDisplay,cDateDisplay;
 private Button mPickDate;
 private int mYear,mMonth,mDay;
 private int cYear,cMonth,cDay;
 static final int DATE_DIALOG_ID = 0;
 Button   mButton;
 EditText cweight,nweight;
 TextView t,c;
 String s,s2,cDate,mDate;
 int current,target;
 DataBaseHelper db = new DataBaseHelper(this);
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.choice);
    final Context context = getApplicationContext();
    final int duration = Toast.LENGTH_SHORT;

    mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
    cDateDisplay = (TextView) findViewById(R.id.Current);
    mPickDate = (Button) findViewById(R.id.pickDate);
    mPickDate.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            showDialog(DATE_DIALOG_ID);
        }
    });
    final Calendar c = Calendar.getInstance();
    cYear = c.get(Calendar.YEAR);
    cMonth = c.get(Calendar.MONTH);
    cDay = c.get(Calendar.DAY_OF_MONTH);
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);
    cDate = (cDay+"-"+cMonth+"-"+cYear);
    mDate = (mDay+"-"+mMonth+"-"+mYear); 
    Date past = new Date(112, cMonth, cDay); // current Date
    Date today = new Date(112, 11, 18); // date Choosen by the user
    final int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays()+1;
     cDateDisplay.setText(cDate);

     //display the current date (this method is below)
     updateDisplay();

    mButton = (Button)findViewById(R.id.get);
    cweight   = (EditText)findViewById(R.id.cweight);
    nweight   = (EditText)findViewById(R.id.nweight);
    t = (TextView)findViewById(R.id.out);

    mButton.setOnClickListener(
        new View.OnClickListener()
        {
            public void onClick(View view)
            {
                db.open();
                while(cweight != null && nweight  != null);
                {
                    s = WorkoutChoice.this.cweight.getText().toString();
                    current =  Integer.parseInt(s);
                    s2 = WorkoutChoice.this.nweight.getText().toString();
                    target =  Integer.parseInt(s2);
                    db.deleteFirst();
                    db.insertTitle(mDate, current, target);
                    CharSequence text = "Goal Set\n"+"Target Date"+mDate+"\n"+"Current Weight "+current+"\n"+"Target Weight "+target;
                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                    /*Intent i = new Intent();
                    i.setClassName("com.b00348312.workout","com.b00348312.workout.WorkoutMenu");
                    startActivity(i);*/
                }
               db.close(); 
            }
        });

}
public void convert(View view) 
{
    Intent i = new Intent();
    i.setClassName("com.b00348312.workout","com.b00348312.workout.convert");
    startActivity(i); 
}
 private void updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mDay).append("-")
                    .append(mMonth + 1).append("-")
                    .append(mYear).append(" "));
        /*cDateDisplay.setText(
                new StringBuilder()
                        // Month is 0 based so add 1
                        .append(cDay).append("-")
                        .append(cMonth + 1).append("-")
                        .append(cYear).append(" "));*/
    } 
 private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };
           @Override
           protected Dialog onCreateDialog(int id) {
                switch (id) {
                case DATE_DIALOG_ID:
                    return new DatePickerDialog(this,
                                mDateSetListener,
                                mYear, mMonth, mDay);
                }
                return null;
            }
}
<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/Cdate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Current Date"
    android:textAppearance="?android:attr/textAppearanceSmall" android:textColor="#000000"/>

<TextView
    android:id="@+id/Current"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#000000"/>

<TextView
    android:id="@+id/blank"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Target"
    android:textColor="#000000" />
<TextView
    android:id="@+id/dateDisplay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#000000"/>
<Button
    android:id="@+id/pickDate"
    android:layout_width="324dp"
    android:layout_height="wrap_content"
    android:text="Change the date"/>
<TextView
     android:text="Enter Enter Current Weight (Kg)" 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="#00000F">
</TextView>
<EditText
    android:id="@+id/cweight"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal" >
        <requestFocus></requestFocus>
</EditText>
<TextView android:text="Enter Desired Weight(kg)" 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" android:textStyle="bold" android:textColor="#00000F"></TextView>

<EditText
    android:id="@+id/nweight"
    android:layout_width="320dp"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal" >

Теги:
freeze

2 ответа

2

Ваш код находится в бесконечном цикле.

Изменение: while(cweight != null && nweight != null);

To: if(cweight != null && nweight != null);

Еще одна вещь: вы уверены, что хотите проверить здесь null. Я хотел бы проверить, что значения будут соответствовать здесь перед запросом базы данных. Я сомневаюсь, что они когда-нибудь будут пустыми. (были бы и другие ошибки)

  • 0
    спасибо cstrutton .......... Я не могу поверить, что упустил такой основной момент при ответе ...
1

Делайте onclick работу в не-UI-потоке, например, используя задачу Asycn или создайте другой поток и используйте обработчик, так как здесь он работает db и может занять много времени...

  • 0
    ashwinrayaprolu.wordpress.com/2011/03/15/...
  • 0
    stackoverflow.com/questions/5924270/...
Показать ещё 8 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню