Awatatah
Awatatah

Reputation: 474

Call and set Global variable

I'm trying to create a global variable that I can referece anywhere. I need to be able to set the variable depending on the selection the user makes from the ListAdapter onclick. I just can't figure out how to code this. I also need to use that variable for if statements. Sorry I am new to this :)

Here is my code:

@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();
            }




        }
    });



}

This is the Global class I created:

public class GlobalClass extends Application {

    public String flavorPreference;


    public String getFlavorPreference(){

        return flavorPreference;
    }

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

    }

}

Upvotes: 0

Views: 61

Answers (1)

Bruce
Bruce

Reputation: 8849

You can use android shared preference to this kind of usage

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

Editor editor = pref.edit();

Insert or Update Value

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

Get Value

pref.getString("key_name", null);

Upvotes: 1

Related Questions