1

我是 Java/android 的新手,所以很多这些术语都是外来的,但我愿意学习。我不会详细介绍该应用程序,因为我认为它不相关。我的问题就目前而言,我使用了博客中的教程和代码片段,并让我的代码正常工作。尝试清理和组织我的代码时,当我移动一行(创建我的自动完成文本视图)时,我得到了一个空指针异常。下面是我使用的代码。我的 1 行代码给我一个问题是

AutoCompleteTextView companyAutoComplete = (AutoCompleteTextView) addAddressDialog.findViewById(R.id.add_record_dialog_autocomplete);

当我将它移到函数开始的右侧时,它会出错,但是当它留在原处时,它就像一个魅力。我想了解这是为什么。

public void addAddress() {
    final Dialog addAddressDialog = new Dialog(this);
    final int[] to = new int[] { android.R.id.text1 };
    final String[] from = new String[] { "CompanyName" };

    // Create a SimpleCursorAdapter for the CompanyName field.
    SimpleCursorAdapter adapter =  new SimpleCursorAdapter(this, android.R.layout. select_dialog_item, null, from, to);

    addAddressDialog.setContentView(R.layout.add_record_dialog);
    addAddressDialog.setTitle(getString(R.string.add_record_dialog_address_title));
    addAddressDialog.setCancelable(true);

    final EditText text1 = (EditText) addAddressDialog.findViewById(R.id.add_record_dialog_edittext);
    text1.setHint(getString(R.string.add_record_dialog_company_hint));

    Button buttonOK1 = (Button) addAddressDialog.findViewById(R.id.add_record_dialog_ok);
    buttonOK1.setText(getString(R.string.add_record_dialog_ok_button));

    Button buttonCancel1 = (Button) addAddressDialog.findViewById(R.id.add_record_dialog_cancel);
    buttonCancel1.setText(getString(R.string.add_record_dialog_cancel_button));

    buttonOK1.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            Bundle addressBundle = new Bundle();
            addressBundle.putString("CompanyName", text1.getText().toString());

            Intent intent = new Intent(MenuActivity.this, AddAddressActivity.class);
            intent.putExtras(addressBundle);
            startActivity(intent);

            addAddressDialog.dismiss();
        }   
    });

    buttonCancel1.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            Toast.makeText(getBaseContext(), "Cancel button clicked", Toast.LENGTH_SHORT).show();
            addAddressDialog.dismiss();
        }   
    });
    AutoCompleteTextView companyAutoComplete = (AutoCompleteTextView) addAddressDialog.findViewById(R.id.add_record_dialog_autocomplete);

    companyAutoComplete.setAdapter(adapter);

    // Set an OnItemClickListener, to update dependent fields when
    // a choice is made in the AutoCompleteTextView.
    companyAutoComplete.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> listView, View view,
                    int position, long id) {
            // Get the cursor, positioned to the corresponding row in the
            // result set
            Cursor cursor = (Cursor) listView.getItemAtPosition(position);

            // Get the CompanyID from this row in the database.
            String companyID = cursor.getString(cursor.getColumnIndexOrThrow("_id"));

            // test to make sure CompanyID returned
            Toast.makeText(getBaseContext(), companyID, Toast.LENGTH_SHORT).show();
        }
    });

    // Set the CursorToStringConverter, to provide the labels for the
    // choices to be displayed in the AutoCompleteTextView.
    adapter.setCursorToStringConverter(new CursorToStringConverter() {
        public String convertToString(android.database.Cursor cursor) {
            // Get the label for this row out of the "CompanyName" column
            final int columnIndex = cursor.getColumnIndexOrThrow("CompanyName");
            final String str = cursor.getString(columnIndex);
            return str;
        }
    });

    // Set the FilterQueryProvider, to run queries for choices
    // that match the specified input.
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            Cursor cursorReturn = dbAdapter.getCompanies(constraint != null ? constraint.toString() : null);

            startManagingCursor(cursorReturn);
            return cursorReturn;
        }
        });

    addAddressDialog.show();
}
4

2 回答 2

2

发生这种情况是因为您setContentView稍后调用。

setContentView设置addAddressDialog对话框的布局。如果您不调用setContentView,则它没有布局项,因此addAddressDialog.findViewById(...);将是null,并且显然您不能将其转换为任何东西,也不能调用setHint它。

这行代码在您的方法中的位置无关紧要,只要在它之前setContentView调用您的行。

于 2012-08-01T20:28:21.470 回答
0

唯一重要的是findViewById()在调用 to 之后调用您的调用setContentView(),即这一行:

addAddressDialog.setContentView(R.layout.add_record_dialog); 

XML 文件add_record_dialog.xml是您要遍历以查找 ID 为 的视图的视图层次结构add_record_dialog_autocomplete。直到您给出视图层次结构的对话框,它才能遍历它,因此NullPointerException当您尝试使用时您会得到一个,AutoCompleteTextView因为它找不到您的视图。

编辑:另外,如果你的意思是你把它放在方法的最开始,那也将失败,因为在addAddressDialog你调用之前它将为空

final Dialog addAddressDialog = new Dialog(this); 
于 2012-08-01T20:31:20.560 回答