【问题标题】:AutoCompleteTextView wont work as EditText didAutoCompleteTextView 不会像 EditText 那样工作
【发布时间】:2017-12-25 02:27:43
【问题描述】:

我在我的应用中将 EditText 替换为 AutoCompleteTextView 以使操作更加用户友好,但我遇到了错误。

在应用程序中,用户输入植物的名称,然后单击按钮进入一个新活动,其中显示有关植物的一些信息。

错误:在用户输入植物名称后,我按下按钮进入下一个活动后,应用程序崩溃。当我还有一个 EditText 时,这并没有发生。也许我使用的 AutoCompleteTextView 错了?

相关代码如下:

public class Main2Activity extends AppCompatActivity {

AutoCompleteTextView edit;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    //this is the AutoComplete
    AutoCompleteTextView edit = (AutoCompleteTextView) findViewById(R.id.et_item);

    //this is the list of suggestions for the AutoComplete
    String[] items = getResources().getStringArray(R.array.items_array);
    java.util.Arrays.sort(items);
    ArrayAdapter<String> adapter =
            new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
    edit.setAdapter(adapter);

//this is the method that is called when the button is pressed
public void find(View view) {

    String name = edit.getText().toString();

    //basically, whatever is typed into the AutoComplete is turned into a string, and 
    //if the string matches one of the existing plants, the user is taken to 
    //the next activity

    if(name.equalsIgnoreCase("Sunflower")){
        Intent intent = new Intent(this, Sunflower.class);
        startActivity(intent);
    }
    else if(name.equalsIgnoreCase("Cactus")){
        Intent intent = new Intent(this, Cactus.class);
        startActivity(intent);
    }

谁能明白为什么这不起作用?

【问题讨论】:

    标签: java android autocomplete autocompletetextview


    【解决方案1】:

    更改如下:

     AutoCompleteTextView edit = (AutoCompleteTextView) findViewById(R.id.et_item);
    

    收件人:

     edit = (AutoCompleteTextView) findViewById(R.id.et_item);
    

    您的自动完成文本视图范围仅限于 onCreate()

    edit.getText().toString();

    您正试图从中获取尚未初始化的文本。所以会得到空指针异常。

    【讨论】:

    • 你帮了大忙!谢谢!
    • 很高兴它有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多