android - 打开“编辑”对话框并旋转设备时,应用崩溃

标签 android crash rotation android-activity screen-rotation

我有个问题。当我单击“添加锻炼”并打开“添加”对话框以输入一些信息时,即使我旋转设备也可以正常工作。但是,当我使用“编辑对话框”旋转设备时,APP崩溃了
请帮我。
需要一些预防措施。 (我不是程序员,所以对我来说并不容易)

public class ShowExercisesListActivity extends ListActivity {

private static final String TAG = "Exercises";

private List<Exercise> mExercises;
private LayoutInflater mInflater;
private ArrayAdapter<Exercise> mArrayAdapter;
private View mAddExerciseDialogLayout;
private Context mContext;
private EditText exerciseName;

private static final int DIALOG_ADD_EXERCISE = 0;

 // package scope, since it is accessed in inner classes
WorkoutTrackerApp mApp;

/** 
 * Called when the activity is first created. 
 * 
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.type_list);

    mApp = (WorkoutTrackerApp) getApplication();
    mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    mExercises = DBUtil.fetchAllExercises(this);

    mArrayAdapter = new ArrayAdapter<Exercise>(this, R.layout.type_list_item, mExercises) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row;

            if (null == convertView) {
                row = mInflater.inflate(R.layout.type_list_item, null);
            } else {
                row = convertView;
            }

            Exercise type = (Exercise) mExercises.get(position);
            TextView tv = (TextView) row.findViewById(android.R.id.text1);
            tv.setText(type.getName());

            return row;
        }

    };
    setListAdapter(mArrayAdapter);

    //dialog box layout
    mContext = this;
    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    mAddExerciseDialogLayout = inflater.inflate(R.layout.add_type_dialog, (ViewGroup) findViewById(R.id.type_layout_root));



    exerciseName = (EditText) mAddExerciseDialogLayout.findViewById(R.id.type_name);
    //register for context menu
    registerForContextMenu(getListView());      

    if (mExercises.size() == 0) {
        // if there are no exercises initially, then show the add type dialog
        showDialog(DIALOG_ADD_EXERCISE);            
    }



    //Начало:Активация кнопки "Добавить упражнение"
    Button addExerciseButton = (Button) findViewById(R.id.menu_add_exercise);
    addExerciseButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            mApp.setCurrrentDialogStatus(DialogStatus.ADD);
            showDialog(DIALOG_ADD_EXERCISE);
        }
    });
    //Конец: Активация кнопки "Добавить упражнение"


    //Начало:Активация иконки Верхней плашки
    ImageButton GoHomeButton = (ImageButton) findViewById(R.id.imageButton1);
    GoHomeButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent myIntent5 = new Intent(ShowExercisesListActivity.this, AndroidApp.class);
            ShowExercisesListActivity.this.startActivity(myIntent5);
        }
    });
    //Конец:Активация иконки Верхней плашки
}






@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Exercise type = mExercises.get(position);
    Log.v(TAG, "Clicked " + type.getName() + "Id: " + type.getId());

    Intent intent = new Intent(this.getApplicationContext(),
            TabWidget.class);
    intent.putExtra("typeId", type.getId());
    startActivity(intent);
}

/**
 * When the context menu is created
 * 
 * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
 */
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.exercise_context_menu, menu);
}



/**
 * When a context menu item is selected
 *  
 * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
 */
@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    switch (item.getItemId()) {

    case R.id.edit_exercise:
        //Edit Exercise name
        mApp.setCurrentExerciseDialogStatus(DialogStatus.EDIT);         
        editExercise((int) info.id);
        return true;
    case R.id.delete_exercise:
        //Delete Exercise and all its entries
        deleteExercise((int) info.id);
        return true;
    default:
        return super.onContextItemSelected(item);
    }
}

/*
 * (non-Javadoc)
 * 
 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.types_menu, menu);
    return true;
}

/*
 * (non-Javadoc)
 * 
 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.add_exercise:
        mApp.setCurrentExerciseDialogStatus(DialogStatus.ADD);
        showDialog(DIALOG_ADD_EXERCISE);
        break;

    case R.id.home: // Go Back to local website
        Intent myIntent3 = new Intent(ShowExercisesListActivity.this, AndroidApp.class);
        ShowExercisesListActivity.this.startActivity(myIntent3);
        return true;

    case R.id.close: // Close WebView
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent); 
        return true;
    case R.id.google: // Open new WebView with the e.g. Google Url
        startActivity(new Intent(Intent.ACTION_VIEW, 
                Uri.parse("http://vk.com/gymtraining")));

        return true;

    default:
        break;
    }
    return super.onOptionsItemSelected(item);
}

/* (non-Javadoc)
 * @see android.app.Activity#onCreateDialog(int)
 */
@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog;
    switch (id) {
    case DIALOG_ADD_EXERCISE:
        AlertDialog.Builder builder;

        //build the dialog
        builder = new AlertDialog.Builder(mContext);
        builder.setView(mAddExerciseDialogLayout);
        builder.setMessage(this.getString(R.string.add_exercise_title))
           .setCancelable(false)
           .setPositiveButton(this.getString(R.string.add, this.getString(R.string.exercise)), null)
           .setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });

        dialog = builder.create();

        break;

    default:
        dialog = null;
        break;
    }
    return dialog;
}

/* (non-Javadoc)
 * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
 */
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    AlertDialog alertDialog = (AlertDialog) dialog;
    Button positiveButton = null;

    switch (id) {
    case DIALOG_ADD_EXERCISE:

        switch (mApp.getCurrentExerciseDialogStatus()) {
        case DEFAULT:
        case ADD:

            alertDialog.setMessage(this.getString(R.string.add_exercise_title));
            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, this.getString(R.string.add, this.getString(R.string.exercise)), new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       //Insert the new data into db
                       String typeName = exerciseName.getText().toString();
                       Exercise newExercise = DBUtil.insertExercise(mContext, typeName);

                       Toast.makeText(mContext, mContext.getResources().getString(R.string.exercise_saved), Toast.LENGTH_SHORT).show();

                       mArrayAdapter.add(newExercise);
                       mArrayAdapter.notifyDataSetChanged();
                   }
               });

            positiveButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
            positiveButton.setText(this.getString(R.string.add, this.getString(R.string.exercise)));
            positiveButton.invalidate();

            exerciseName.setText("");

            break;

        case EDIT:
            alertDialog.setMessage(this.getString(R.string.edit, this.getString(R.string.exercise)));
            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, this.getString(R.string.edit_button), new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       //Update the data into db
                        Exercise exerciseToEdit = (Exercise) exerciseName.getTag(); 
                        exerciseToEdit.setName(exerciseName.getText().toString());

                        DBUtil.updateExercise(mContext, exerciseToEdit);
                        Toast.makeText(mContext, mContext.getResources().getString(R.string.exercise_saved), Toast.LENGTH_SHORT).show();        
                        mArrayAdapter.notifyDataSetChanged();
                   }

               });

            Exercise exerciseToEdit = (Exercise) exerciseName.getTag();
            exerciseName.setText(exerciseToEdit.getName());

            positiveButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
            positiveButton.setText(this.getString(R.string.edit_button));
            positiveButton.invalidate();

            break;
            }
    default:
        break;
    }
}

/**
 * Edit Exercise name
 * 
 * @param id
 */
private void editExercise(int position) {
    exerciseName.setTag(mExercises.get(position));
    showDialog(DIALOG_ADD_EXERCISE);
}

/**
 * Delete an Exercise
 * 
 * @param position
 */
private void deleteExercise(int position) {
    Exercise exercise = mExercises.get(position);
    DBUtil.deleteExercise(mContext, exercise.getId());

    Toast.makeText(mContext, mContext.getResources().getString(R.string.exercise_deleted), Toast.LENGTH_SHORT).show();      

    mArrayAdapter.remove(exercise);
    mArrayAdapter.notifyDataSetChanged();

}

}

最佳答案

我现在不能遍历整个代码,但是如果您的问题仅在于旋转手机并且不必激活旋转功能,那么为什么不将以下两行添加到 Activity 定义中呢?在您的AndroidManifest.xml中

android:screenOrientation="portrait"

要么
android:screenOrientation="landscape"

关于android - 打开“编辑”对话框并旋转设备时,应用崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13915557/

相关文章:

excel - 任何 Office 365 应用程序中的 VBA 编辑器不再打开

jquery - 使 div 在每个浏览器中都可旋转

java - 如何检查字符串中的逻辑运算符或将字符串转换为Java中的代码

javascript - phonegap javascript 警报不起作用?

android - 尝试创建自定义 View.onFocusChangeListener 时出错

java - Android proguard,保留内部类的内部类

visual-studio-2015 - C++/CLI 应用程序启动时崩溃 (_register_onexit_function)

xamarin.ios - Xamarin随机崩溃/iOS7/StoreKit

ios - 从 CGAffineTransform 获取比例和旋转角度?

ios - 在倒置肖像模式下关闭 VC 后,主 VC 显示为正常肖像