调用并设置全局变量

Call and set Global variable

我正在尝试创建一个我可以在任何地方引用的 global variable。我需要能够根据用户从 ListAdapter onclick 所做的选择来设置变量。我只是不知道如何编写代码。我还需要将该变量用于 if 语句。对不起,我是新手:)

这是我的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.select_flavor);

    String[] select_flavor_list = {"Kansas City", "Memphis", "Texas", "North Carolina", "South Carolina","Alabama"};

    ListAdapter FlavorListAdapter = new ArrayAdapter<String>(this, R.layout.row_layout_flavor, R.id.flavor_text_view,
            select_flavor_list);

    ListView listView = (ListView) findViewById(R.id.listView);

    listView.setAdapter(FlavorListAdapter);

    //For list view selection, begin here...
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
            GlobalClass flavorPref = ((GlobalClass)getApplicationContext());


            flavorPref.setFlavorPreference(String a) = String.valueOf(adapterView.getItemAtPosition(position));


            if (flavorPref.equals("Kansas City")) {
                Intent intent = new Intent(FlavorListView.this, KansasCity.class);
                startActivity(intent);
                setContentView(R.layout.kansas_city);
                Toast.makeText(FlavorListView.this, "test " + flavorPref,
                        Toast.LENGTH_LONG).show();




            }
            else if (flavorPicked.equals("Memphis")) {
                Intent intent = new Intent(FlavorListView.this, KansasCity.class);
                startActivity(intent);
                setContentView(R.layout.kansas_city);
                Toast.makeText(FlavorListView.this, "test " + flavorPref,
                        Toast.LENGTH_LONG).show();
            }




        }
    });



}

这是我创建的全局class:

public class GlobalClass extends Application {

    public String flavorPreference;


    public String getFlavorPreference(){

        return flavorPreference;
    }

    public void setFlavorPreference(String a){
        flavorPreference = a;

    }

}

你可以用android shared preference这种用法

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 

Editor editor = pref.edit();

插入或更新值

editor.putString("key_name", "string value");

获取值

pref.getString("key_name", null);