从Hashmap对象中的键填充微调器和从微调器中选择值

时间:2016-11-19 21:06:31

标签: java android

我有一个微调器对象,我想用hashmap对象中的所有键填充它。 即我的hashmap包含所有美国州/首都的列表(例如加州/萨克拉门托),我希望我的微调器列出所有状态(因此我可以在用户选择状态时返回相关的资本)

这是我的完整代码。我有2个问题/问题 1 /微调器有效,但我想知道是否有更好/更容易的方法。 2 /微调器元素的选择不起作用

import android.os.Bundle;
import android.app.Activity;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import java.util.List;
import java.util.ArrayList;
import android.widget.AdapterView;
import android.view.View;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class States extends Activity implements OnItemSelectedListener{
Map<String, String> capitals = new HashMap<>();
Spinner spinnerStates;
List<String> states = new ArrayList<String>();

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

    String text = "US_states"; //text file in the assets folder

    byte[] buffer = null;

    InputStream is;
    try {
        is = getAssets().open(text);
        int size = is.available(); //size of the file in bytes
        buffer = new byte[size]; //declare the size of the byte array with size of the file
        is.read(buffer); //read file
        is.close(); //close file

    } catch (IOException e) {
        e.printStackTrace();
    }

    // Store text file data in the string variable
    String str_data = new String(buffer);

    //Split using the delimiter ":" to the all elements
    String[] stateCapsArray = str_data.split(":");
    //Iterate over the array
    for(int i=0;i<stateCapsArray.length-1;i++) {
        //Skip each other element as we are collecting 2 elements at a time
        if(i%2 == 0) {
            String state = stateCapsArray[i];
            String capital = stateCapsArray[i+1];
            capitals.put(state, capital);
        }
    }

    Iterator entries = capitals.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry entry = (Map.Entry) entries.next();
        String key = (String) entry.getKey();
        states.add(key); //Add each States to ArrayList
    }

    ArrayAdapter <String>adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item, states);
    spinnerStates = (Spinner) findViewById(R.id.spinner);
    spinnerStates.setPrompt("Select a State");
    spinnerStates.setAdapter(adapter);
}

@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
    String item = parent.getItemAtPosition(position).toString();
    Toast.makeText(parent.getContext(), "State Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{}

}

0 个答案:

没有答案