Android 将对象声明移动到函数之外会导致崩溃

Android 将对象声明移动到函数之外会导致崩溃,android,function,object,crash,Android,Function,Object,Crash,本规范适用于: public void saveRoutine() { datasource = new RoutinesDataSource(this); datasource.open(); EditText routineName = (EditText) findViewById(R.id.routine_add_name); String routineString = routineName.getText().toString(); if

本规范适用于:

public void saveRoutine() {
    datasource = new RoutinesDataSource(this);
    datasource.open();
    EditText routineName = (EditText) findViewById(R.id.routine_add_name);
    String routineString = routineName.getText().toString();

    if (routineString.length() == 0) {
        Toast toast_routine_name_empty = Toast.makeText(this, getString(R.string.toast_routine_name_empty), Toast.LENGTH_SHORT);
        toast_routine_name_empty.show();            
    }
    else {
        datasource.createRoutine(routineString);
        Toast toast_added = Toast.makeText(this, getString(R.string.toast_routine_added), Toast.LENGTH_SHORT);
        toast_added.show();
        this.finish();
    }
}
但是,当我移动行
EditText routineName=(EditText)findViewById(R.id.routine\u add\u name)位于
saveRoutine()
函数上方(外部),它会导致我的应用程序崩溃

如何使其能够在不仅仅是
saveRoutine()
函数中使用对象

例如,我想使用
saveRoutine()
函数下面的代码使其在按下ENTER键时调用
saveRoutine()


这是因为如果您将
EditText routineName=(EditText)findViewById(R.id.routine\u add\u name)中,整个语句将是全局的,
findViewById()
将在
setContentView()之前执行

这将导致一个空变量(没有布局,因此不会有视图分配给
routineName
),这将导致
NullPointerException
。你最好的选择是使
routineName
全球化,所以就这样做吧

EditText routineName; 
saveRoutine()方法之外。为了便于阅读和正确练习,请在所有方法之前在类声明的顶部声明它

那就做吧

routineName = (EditText) findViewById(R.id.routine_add_name);
在活动的
onCreate()
方法中的
setContentView()
之后

EditText routineName;
将方法外部作为全局变量并放置:

routineName = (EditText) findViewById(R.id.routine_add_name);
onCreate()
函数之后的任何方法中(或在调用
setContentView()
函数之后)


setContentView()
在“活动”中当前膨胀的可见布局中查找视图。如果将语句移到方法之外,则Android会尝试在当前为空的布局中查找视图,因为
setContentView()
通常在
onCreate()
中调用。这将导致EditText的值为null,当您尝试调用EditText的任何成员函数时,这将导致出现
NullPointerException

使用私有变量在onCreate()方法中编写声明EditText的代码,以在类中访问它

Public Class someclass extends Activity{

   private  editText;
   @override
   protected onCreate(Bundle b){
   editText = findViewById(R.id.edit);
  }
}

在类中使用变量editText anywhere/any函数。

很抱歉,我的格式不好,我正在从Mobile访问stackoverflow,它是一个Pita.id,而不是为这么简单的东西创建子类。
Public Class someclass extends Activity{

   private  editText;
   @override
   protected onCreate(Bundle b){
   editText = findViewById(R.id.edit);
  }
}