Java – How to display the value of the HashMap key when the user clicks autocom

How to display the value of the HashMap key when the user clicks autocom… here is a solution to the problem.

How to display the value of the HashMap key when the user clicks autocom

I am new to android development and Java programming. In my code (shown below), when the user clicks the search button, the value >key is displayed in the displayField TextView. But I want it so that value is displayed when the user clicks (touches) an item on the AutoCompleteTextView drop-down item, without the click Search button.

import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity 
{   

Map<String, String> map = new HashMap<String, String>();

private EditText autocomplete_searchField;
    private TextView displayField;
    String note;

@Override
    protected  void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    autocomplete_searchField = (AutoCompleteTextView) findViewById(R.id.autocomplete_searchField);

 Get a reference to the AutoCompleteTextView in the layout
    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_searchField);

 Gets the string array
    String[] music_note = getResources().getStringArray(R.array.music_notes_array);

 Creates the adapter and set it to the AutoCompleteTextView 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android. R.layout.simple_list_item_1, musicNote);
    textView.setAdapter(adapter);

displayField = (TextView) findViewById(R.id.displayField);
    Button button = (Button)findViewById(R.id.button);  I want to completely remove this button eventually
    button.setOnClickListener(new View.OnClickListener() {

@Override
    public void onClick(View v) {

String note = autocomplete_searchField.getText().toString();
            displayField.setText(map.get(note));

map.put("Doe", "a deer, a female deer");
    map.put("Ray", "a drop of golden sun");
}

Solution

I

don’t understand why you need autocomplete_searchField in your code, anyway, if I understand well, you just need to remove button.setOnClickListener and add the following code:

textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

displayField.setText(map.get(adapterView.getItemAtPosition(position).toString()));

}

});

Related Problems and Solutions