Android NullPointerException错误。怎么解决?

时间:2013-01-31 00:16:38

标签: android nullpointerexception android-alertdialog

我已经创建了一个应用程序,其中程序中有一个警报对话框。在代码中,它不显示错误。但是当我运行它时,我看到这个Null指针异常错误。我试过解决它但仍然无法正常工作。我想要做的是,当用户点击“删除”按钮时,会出现一个警告对话框,上面写着“你确定要删除所选项吗?”当用户点击“是”时,它将被删除,如果“否”,则不会被删除。

这是我的代码:

主要活动档案:

protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.pass_list);
        hideKeyboard();
        initializing();
        show_list_layout();
        Button logout = (Button) findViewById(R.id.button1);
        String username = getIntent().getStringExtra("USERNAME");
        Toast.makeText(PasswordActivity.this,  "Welcome " + username, Toast.LENGTH_LONG).show();
        logout.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent i = new Intent(PasswordActivity.this, LogIn.class);
                startActivityForResult(i,0);
            }
        });

        btn_del.setOnClickListener(this);
    }

    public void btn_addnew_click(View v){
        this.selected_website = null;
        show_add_layout();
    }

    public void btn_back_click(View v){
        this.selected_website = null;
        show_list_layout();
    }

    public void btn_edit_click(View v){
        if(this.selected_website != null){
            show_add_layout();
        }else{
            show_mesg("Please select item to edit.");
        }
    }

    public void btn_add_update_click(View v){
        hideKeyboard();
        String username = getIntent().getStringExtra("USERNAME");
        String str_sitename = this.edt_sitename.getText().toString();
        String str_username = this.edt_username.getText().toString();
        String str_password = this.edt_password.getText().toString();
        if (str_sitename.equals("")){
            //edt_sitename.requestFocus();
            show_mesg("Please insert sitename.");
        }else if (str_username.equals("")){
            //edt_username.requestFocus();
            show_mesg("Please insert username.");
        }else if (str_password.equals("")){
            //edt_password.requestFocus();
            show_mesg("Please insert password.");
        }else{
            if (selected_website!=null){
                selected_website.setUser(username);
                selected_website.setSitename(str_sitename);
                selected_website.setUsername(str_username);
                selected_website.setPassword(str_password);
                datasource.updateWebsite(selected_website);
                show_mesg(str_sitename + " updated.");
                hideKeyboard();
                selected_website = null;
                show_list_layout();
            }else{
                datasource.addWebsite(username, str_sitename,str_username,str_password);
                hideKeyboard();
                show_mesg(str_sitename + " added.");
                selected_website = null;
                show_add_layout();
            }
        }
    }

    public void popUps(){
        if(this.selected_website != null){


            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                private WebsiteRecords selected_website;

                public void onClick(DialogInterface dialog, int which) {
                    switch (which){
                    case DialogInterface.BUTTON_POSITIVE:
                        datasource.deleteWebsite(this.selected_website);
                        hideKeyboard();
                        show_mesg(this.selected_website.getSitename() + " deleted.");
                        selected_website = null;
                        show_list_layout();

                    case DialogInterface.BUTTON_NEGATIVE:
                        show_mesg("NO");
                        break;
                    }
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Are you sure?")
                   .setPositiveButton("Yes", dialogClickListener)
                   .setNegativeButton("No", dialogClickListener)
                   .show();
        }
        else{
                show_mesg("Please select item to delete.");
        }
    }

    /*public void btn_del_click(View v){
         if(this.selected_website != null){
            datasource.deleteWebsite(this.selected_website);
            hideKeyboard();
            show_mesg(this.selected_website.getSitename() + " deleted.");
            selected_website = null;
            show_list_layout();
        }else{
            show_mesg("Please select item to delete.");
        }
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    show_mesg("YES");
                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    show_mesg("NO");
                    break;
                }
            }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener);
    }*/
    public class select_item_click implements OnClickListener{
        private RadioButton rdb_select_item;
        private WebsiteRecords website;
        select_item_click(RadioButton rdb_select_item,WebsiteRecords website){
            this.rdb_select_item = rdb_select_item;
            this.website = website;
        }

        @Override
        public void onClick(View v) {
            for (int i = 0 ; i< all_radiobutton.size();i++){
                RadioButton rdb_select_item = all_radiobutton.get(i);
                rdb_select_item.setChecked(false);
            }

            selected_website = this.website;
            this.rdb_select_item.setChecked(true);

        }

    }
    public void hideKeyboard(){
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    public void show_add_layout(){
        hideKeyboard();
        LinearLayout layout_list = (LinearLayout)findViewById(R.id.layout_list);
        LinearLayout layout_add = (LinearLayout)findViewById(R.id.layout_add_edit);
        layout_list.setVisibility(View.GONE);
        layout_add.setVisibility(View.VISIBLE);
        if (selected_website != null){
            this.edt_sitename.setText(selected_website.getSitename());
            this.edt_username.setText(selected_website.getUsername());
            this.edt_password.setText(selected_website.getPassword());
            this.btn_add.setText("Update");
        }else{
            this.edt_sitename.setText("");
            this.edt_username.setText("");
            this.edt_password.setText("");
            this.edt_sitename.requestFocus();
            this.btn_add.setText("Add");
        }
    }
    public void show_mesg(String msg){
        Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
    }

    public void show_list_layout(){
        hideKeyboard();
        LinearLayout layout_list = (LinearLayout)findViewById(R.id.layout_list);
        LinearLayout layout_add = (LinearLayout)findViewById(R.id.layout_add_edit);
        layout_list.setVisibility(View.VISIBLE);
        layout_add.setVisibility(View.GONE);

        this.tmp_websites = datasource.getAllWebsite(getIntent().getStringExtra("USERNAME"));
        Log.i("algo","Cantid ad de web sites "+this.tmp_websites.size());
        this.all_radiobutton.clear();
        ListView showlist = (ListView) findViewById(R.id.ListWebsite);
        showlist.removeAllViewsInLayout();
        showlist.setAdapter(new WebsiteItemAdapter(this, android.R.layout.simple_list_item_checked, this.tmp_websites));
    }

    public class WebsiteItemAdapter extends ArrayAdapter<WebsiteRecords> {
        private List<WebsiteRecords> websites;
        public WebsiteItemAdapter(Context context, int textViewResourceId, List<WebsiteRecords> websites) {
            super(context, textViewResourceId, websites);
            this.websites = websites;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            hideKeyboard();
            WebsiteRecords website = websites.get(position);
            if (website != null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = vi.inflate(R.layout.listview, null);
                hideKeyboard();
                RadioButton rdb_select_item =(RadioButton) view.findViewById(R.id.rdb_select_item);
                LinearLayout layout_item = (LinearLayout) view.findViewById(R.id.layout_item);
                TextView tv_sitename = (TextView) view.findViewById(R.id.website);
                TextView tv_username = (TextView) view.findViewById(R.id.username);
                TextView tv_password = (TextView) view.findViewById(R.id.password);
                tv_sitename.setText(website.getSitename());
                tv_username.setText("Username  : " + website.getUsername() );
                tv_password.setText("Password : " + website.getPassword());

                if(selected_website != null){
                    if (selected_website.getId() == website.getId()) rdb_select_item.setChecked(true);
                }

                all_radiobutton.add(rdb_select_item);
                rdb_select_item.setOnClickListener(new select_item_click(rdb_select_item,website));
                layout_item.setOnClickListener(new select_item_click(rdb_select_item,website));
            }
            return view;
        }
    }
    @Override
    protected void onResume() {
        datasource.open();
        super.onResume();
    }
    @Override
    protected void onPause() {
        datasource.close();
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        if(v == btn_del) {
            if(this.selected_website != null){
            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                private WebsiteRecords selected_website;
                public void onClick(DialogInterface dialog, int which) {
                    switch (which){
                    case DialogInterface.BUTTON_POSITIVE:
                        datasource.deleteWebsite(this.selected_website);
                        hideKeyboard();
                        show_mesg(this.selected_website.getSitename() + " deleted.");
                        selected_website = null;
                        show_list_layout();
                    case DialogInterface.BUTTON_NEGATIVE:
                        show_mesg("NO");
                        break;
                    }
                }
            };
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Are you sure?")
                   .setPositiveButton("Yes", dialogClickListener)
                   .setNegativeButton("NO", dialogClickListener)
                   .show();
            show_mesg("PASSED");
        }
        else{
                show_mesg("Please select item to delete.");
            }
        }
    }
}

我的数据源文件:

public class DataSource {

    private SQLiteDatabase database;
    private MySQLiteHelper dbHelper;
    private String[] allColumns = { 
                MySQLiteHelper.COLUMN_ID,
                MySQLiteHelper.COLUMN_USER,
                MySQLiteHelper.COLUMN_URL,
                MySQLiteHelper.COLUMN_USERNAME,
                MySQLiteHelper.COLUMN_PASSWORD
            };

    public DataSource(Context context) {
        dbHelper = new MySQLiteHelper(context);
    }

    public void open() throws SQLException {
        database = dbHelper.getWritableDatabase();
    }

    public void close() {
        dbHelper.close();
    }

    public void addWebsite(String user, String sitename, String username, String password) {

        ContentValues values = new ContentValues();
        values.put(MySQLiteHelper.COLUMN_USER,  user);
        values.put(MySQLiteHelper.COLUMN_URL, sitename);
        values.put(MySQLiteHelper.COLUMN_USERNAME, username);
        values.put(MySQLiteHelper.COLUMN_PASSWORD, password);
        database.insert(MySQLiteHelper.TABLE_URL, null,values);
    }

public void updateWebsite(WebsiteRecords website){

        ContentValues values = new ContentValues();
        values.put(MySQLiteHelper.COLUMN_URL, website.getSitename());
        values.put(MySQLiteHelper.COLUMN_USERNAME, website.getUsername());
        values.put(MySQLiteHelper.COLUMN_PASSWORD, website.getPassword());
        database.update(MySQLiteHelper.TABLE_URL, values, MySQLiteHelper.COLUMN_ID  + " = " + website.getId(), null);
    }

public void deleteWebsite(WebsiteRecords website) {
    database.delete(MySQLiteHelper.TABLE_URL, MySQLiteHelper.COLUMN_ID  + " = " + website.getId(), null);

}

public List<WebsiteRecords> getAllWebsite(String user){

    List<WebsiteRecords> websites = new ArrayList<WebsiteRecords>();
    Cursor cursor = database.rawQuery("SELECT * FROM " + MySQLiteHelper.TABLE_URL + " WHERE user='" + user+"'", null);
    cursor.moveToFirst();

    while (!cursor.isAfterLast()) {
        WebsiteRecords website = cursorToWebsite(cursor);
        websites.add(website);
        cursor.moveToNext();
    }

    cursor.close();

    return websites;
}

private WebsiteRecords cursorToWebsite(Cursor cursor) {
    WebsiteRecords website = new WebsiteRecords();
    website.setId(cursor.getInt(0));
    website.setUser(cursor.getString(1));
    website.setSitename(cursor.getString(2));
    website.setUsername(cursor.getString(3));
    website.setPassword(cursor.getString(4));
    return website;
}
你可以帮我解决这个问题吗?

修改 所以这里是LogCat:

01-31 08:11:07.649: E/AndroidRuntime(777): FATAL EXCEPTION: main
01-31 08:11:07.649: E/AndroidRuntime(777): java.lang.NullPointerException
01-31 08:11:07.649: E/AndroidRuntime(777):  at com.bernadette.remembermypassword.DataSource.deleteWebsite(DataSource.java:56)
01-31 08:11:07.649: E/AndroidRuntime(777):  at com.bernadette.remembermypassword.PasswordActivity$3.onClick(PasswordActivity.java:296)
01-31 08:11:07.649: E/AndroidRuntime(777):  at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
01-31 08:11:07.649: E/AndroidRuntime(777):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 08:11:07.649: E/AndroidRuntime(777):  at android.os.Looper.loop(Looper.java:137)
01-31 08:11:07.649: E/AndroidRuntime(777):  at android.app.ActivityThread.main(ActivityThread.java:4745)
01-31 08:11:07.649: E/AndroidRuntime(777):  at java.lang.reflect.Method.invokeNative(Native Method)
01-31 08:11:07.649: E/AndroidRuntime(777):  at java.lang.reflect.Method.invoke(Method.java:511)
01-31 08:11:07.649: E/AndroidRuntime(777):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-31 08:11:07.649: E/AndroidRuntime(777):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-31 08:11:07.649: E/AndroidRuntime(777):  at dalvik.system.NativeStart.main(Native Method)
01-31 08:30:21.998: E/Trace(827): error opening trace file: No such file or directory (2)

1 个答案:

答案 0 :(得分:0)

好的,我发现错误是什么。错误在“(this.selected_website)”行中。 为了解决这个问题,我在“(this.selected_website)”中删除了“this”并且它有效!谢谢你的帮助。