1

I have two activities.

The first activity contains a ListView widget that is populated such:

String products[] = {"Pull Restaurant names here", "Res. 1", "Res abc", "Res foo", "Res hello",
    "Res xyz", "Res test", "Res test2", "Denny's"};

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

// Adding items to listview
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
lv.setAdapter(adapter);

Once the user selects an item from the list, I load a new activity such:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        android.content.Intent intent = new android.content.Intent(GuestPage.this, RestaurantProfile.class);
        startActivity(intent);
    }
});

I want to be able to store the selected item string from the ListView into a global variable. I have a Global class that extends application, I have included the necessary name tag in my manifest. I am using something similar to:

Globals g = (Globals)getApplication();
g.setData(String s);

in order to set the Global variable.

My issue is with storing the selected ListView item because I don't know how to call it. I am not using any xml Item files to populate my ListView. How do I know which item is selected and how do I store that into my global variable?

FOR EXAMPLE: user selects "Res foo". New activity is loaded and I have a global variable to use among all activities that contains String "Res foo". Thanks.

Ziem
  • 6,059
  • 7
  • 49
  • 83
Hani Al-shafei
  • 139
  • 1
  • 2
  • 13

3 Answers3

1

What you're doing with your Globals is a very bad practice. Instead take a look a this solution for passing data between Activities.

https://stackoverflow.com/a/7325248/3474528

To get the selected string you would want to do something like:

 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    String selected = products[position];
    ....
 }                              
Community
  • 1
  • 1
Charles Durham
  • 2,225
  • 14
  • 16
0
lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList = (String) (lv.getItemAtPosition(myItemInt));
        android.content.Intent intent = new android.content.Intent(GuestPage.this, RestaurantProfile.class);
        startActivity(intent);
    }                  
});

I hope this fix your problem :)

Ziem
  • 6,059
  • 7
  • 49
  • 83
Ibtehaz
  • 49
  • 10
0
public void onItemClick(AdapterView<?> parent, View view, int position, long id)

int position holds the index of the item clicked in the ListView.

You can then use that position to get the text:

String theText = (ListView)parent.getItemAtPosition(position);

Rohn Adams
  • 812
  • 7
  • 16