2

我为过滤器搜索栏创建了一个 onDestroy 方法,但遇到了一个小问题。

这是我的日志:

09-01 01:55:40.147: E/AndroidRuntime(1014): FATAL EXCEPTION: main
09-01 01:55:40.147: E/AndroidRuntime(1014): java.lang.RuntimeException: Unable to destroy activity {com.stts.sparetimetradingsystem/com.stts.sparetimetradingsystem.employer.HomepageEmployerActivity}: java.lang.NullPointerException
09-01 01:55:40.147: E/AndroidRuntime(1014):     at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3655)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3673)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at android.app.ActivityThread.access$2900(ActivityThread.java:125)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at android.os.Looper.loop(Looper.java:123)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at android.app.ActivityThread.main(ActivityThread.java:4627)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at java.lang.reflect.Method.invokeNative(Native Method)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at java.lang.reflect.Method.invoke(Method.java:521)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at dalvik.system.NativeStart.main(Native Method)
09-01 01:55:40.147: E/AndroidRuntime(1014): Caused by: java.lang.NullPointerException
09-01 01:55:40.147: E/AndroidRuntime(1014):     at com.stts.sparetimetradingsystem.employer.HomepageEmployerActivity.onDestroy(HomepageEmployerActivity.java:340)
09-01 01:55:40.147: E/AndroidRuntime(1014):     at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3642)
09-01 01:55:40.147: E/AndroidRuntime(1014):     ... 11 more

这是我的代码:

@Override
protected void onDestroy() {
    super.onDestroy();
    searchBarEmployer.removeTextChangedListener(filterTextWatcher); <--- LINE 340
}

* *编辑这是我的登录代码 在用户输入正确的凭据后将切换到主页。

public class LoginEmployerActivity extends Activity {
Button btnLoginEmployer;
Button btnLinkToEmployerRegisterScreen;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
TextView forgotPassword;

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_CNAME = "cname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private ProgressDialog pDialog;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_employer);

    // Importing all assets like buttons, text fields
    inputEmail = (EditText) findViewById(R.id.loginEmployerEmail);
    inputPassword = (EditText) findViewById(R.id.loginEmployerPassword);
    btnLoginEmployer = (Button) findViewById(R.id.btnLoginEmployer);
    btnLinkToEmployerRegisterScreen = (Button) findViewById(R.id.btnLinkToEmployerRegisterScreen);
    loginErrorMsg = (TextView) findViewById(R.id.login_error);
    forgotPassword = (TextView) findViewById(R.id.link_to_forgetPassword);

    // Login button Click Event
    btnLoginEmployer.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            // Checking for server respond
                new LoginEmployer().execute();
            }
        }
    });

    // Link to Register Screen
    btnLinkToEmployerRegisterScreen
            .setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    Intent i = new Intent(getApplicationContext(),
                            RegisterEmployerActivity.class);
                    startActivity(i);
                    finish();
                }
            });

    // Link to forgot password link
    forgotPassword.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            // Switching to forgot password screen
            Intent i = new Intent(getApplicationContext(),
                    ForgotPasswordEmployerActivity.class);
            startActivity(i);
        }
    });
}

// Background ASYNC Task to login by making HTTP Request
class LoginEmployer extends AsyncTask<String, String, String> {

    // Before starting background thread Show Progress Dialog
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginEmployerActivity.this);
        pDialog.setMessage("Authenticating...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    // Checking login in background
    protected String doInBackground(String... params) {
        runOnUiThread(new Runnable() {
            public void run() {

                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                EmployerFunctions employerFunctions = new EmployerFunctions();
                JSONObject json = employerFunctions.loginUser(email,
                        password);

                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        loginErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS);
                        if (Integer.parseInt(res) == 1) {
                            // user successfully logged in
                            // Store user details in SQLite Database
                            DatabaseHandlerEmployer dbe = new DatabaseHandlerEmployer(
                                    getApplicationContext());
                            JSONObject json_user = json
                                    .getJSONObject("user");

                            // Clear all previous data in database
                            employerFunctions
                                    .logoutUser(getApplicationContext());
                            dbe.addUser(
                                    json_user.getString(KEY_NAME),
                                    //json_user.getString(KEY_CNAME),
                                    json_user.getString(KEY_EMAIL),
                                    json.getString(KEY_UID),
                                    json_user.getString(KEY_CREATED_AT));
                            // Launch Employer homePage Screen
                            Intent homepage = new Intent(
                                    getApplicationContext(),
                                    HomepageEmployerActivity.class);

                            // Close all views before launching Employer
                            // homePage
                            homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(homepage);

                            // Close Login Screen
                            finish();
                        } else {
                            // Error in login
                            loginErrorMsg
                                    .setText("Invalid username/password");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        return null;
    }

    // After completing background task Dismiss the progress dialog
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }
}

}

4

4 回答 4

2

确保您searchBarEmployer已正确初始化和引用。

EditText searchBarEmployer ; // outside onCreate, global to class

在 onCreate() 内部,

searchBarEmployer = (EditText)findViewById(R.id.editTextIdInXML);

还,

@Override
protected void onDestroy() {
    searchBarEmployer.removeTextChangedListener(filterTextWatcher);
    super.onDestroy();

}
于 2012-08-31T18:05:19.340 回答
1

你做错了。如果你重写onCreate()(或者一般来说,构造函数类似的方法),那么经验法则是调用super.onCreate() FIRST(初始化所有 stull 超类可能需要等)然后做你的事情。但是,如果您覆盖onDestroy()(或一般的析构函数类似方法),那么经验法则是按照您在onCreate(). 首先清除自己的东西,然后super.onDestroy()作为最后一件事调用。否则(就像您所做的那样)可能会导致许多问题,因为超类可以简单地清理许多东西(如内部变量、引用等),并且您的代码将简单地崩溃。像这样重新排列你的onDestroy()

@Override
protected void onDestroy() {
    searchBarEmployer.removeTextChangedListener(filterTextWatcher);
    super.onDestroy();
}

还有一个选项你searchBarEmployer只是空,所以这可能更安全:

@Override
protected void onDestroy() {
    if( searchBarEmployer != null ) {
      searchBarEmployer.removeTextChangedListener(filterTextWatcher);
    }
    super.onDestroy();
}
于 2012-08-31T18:02:34.627 回答
0

请放置一个调试点并确保它searchBarEmployer不为空。

如果是null由于之前执行的某些步骤,请在此语句之前放置一个空检查。

if( searchBarEmployer != null ) {
// Place operation here...
}

你也应该搬家

super.onDestroy();

作为方法的最后一个语句。

编辑 我的意思是...

@Override
protected void onDestroy() {
    if( searchBarEmployer != null ) {    // <---- PLACE NULL CHECK
      searchBarEmployer.removeTextChangedListener(filterTextWatcher);
    }
    super.onDestroy();  // <--- LAST STATEMENT
}
于 2012-08-31T18:04:38.073 回答
0

如有必要,请初始化 searchBarEmployer。就像如果 searchBarEmployer 是一个文本视图,将其声明为顶部,然后执行 searchBarEmployer=(TextView)findViewById(R.id....); 等等然后使用它。

避免使用 TextView searchBarEmployer=null; 种方法。

于 2012-08-31T18:08:54.100 回答