Insert value for items in listview - android

I have already created a listview with the codes as below that displays apple, orange and banana. When I click on the item (Eg: apple) I want it to be displayed in a different activity as a textview along with the value. Eg: apple = 40 cal. For now I do not have a database to store these values.
This is the code for the listview :
public class ViewMenuList extends ListActivity {
String[] food = { "Apple", "Banana", "Orange"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_list);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, food));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position, long id)
{
Toast.makeText(this, "You have selected " + food[position] , Toast.LENGTH_LONG).show();
}
}

You can do a couple different things then. You can simply pass the value using an Intent
public void onListItemClick(ListView parent, View v, int position, long id)
{
Toast.makeText(this, "You have selected " + food[position] , Toast.LENGTH_LONG).show();
String name = food[position];
Intent i = new Intent(CurrentActivityName.this, NextActivityName.class);
i.putExtra("foodName", name);
startActivity(i);
}
then retrieve it in the next Activity in onCreate()
Intent intent = getIntent();
String foodName = intent.getStringExtra("foodName");
Then call setText(foodName) on your TextView in the next Activity
You also could store the information in SharedPreferences or in a static variable in a different class that would hold associated information with the food item.

Related

Android: Storing selected ListView item in global variable

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.
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];
....
}
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);
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 :)

listView item click event not firing

I am having an issue with using a listview that when I click it nothing is happening. I would like for it when I click the listview item to make a toast so I know it is being clicked. I have been trying/researching for a while and nothing. Would anybody mind taking a look to see if I am missing something I just am overlooking? Many thanks in advance!
Here is my class:
public class MyCar extends Activity {
/**
* Called when the activity is first created.
*/
public ListView mylistView;
String carInfo;
private ArrayAdapter<String> mylistAdapter;
ArrayList<String> arrayListCar = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mycar);
mylistView = (ListView) findViewById(R.id.listView);
arrayListCar = new ArrayList<String>();
//Just had to remove setting this adapter 2 times. Took out line below to fix.
mylistView.setAdapter(mylistAdapter);
mylistView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
carInfo = trySomethin();
fillList();
}
public void fillList() {
String make = "";
String model = "";
String[] pieces = carInfo.split("\"");
make = pieces[3];
model = pieces[7];
ArrayList<String> carList = new ArrayList<String>();
carList.add(make + " " + model);
// Create ArrayAdapter using the car list.
mylistAdapter = new ArrayAdapter<String>(MyCar.this, android.R.layout.simple_list_item_single_choice, carList);
mylistView.setAdapter(mylistAdapter);
mylistAdapter.notifyDataSetChanged();
}
}
if you have any elements on listview item change this for them
android:focusable="false"
and if you are changing any elements visibility on runtime you have to handle focus programatically each time you change its visibility.
Try this
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});

How to select only one column in simplecursoradapter and pass it another activity?

I have a cursor in my main activity to query two columns of the database and display them using a simple cursor adapter.
private Cursor doQuery() {
return(db.getReadableDatabase().rawQuery("SELECT RestaurantID AS _id, RestaurantName, StoreNo "
+ "FROM RestaurantList ORDER BY RestaurantName", null));
}
public void onPostExecute() {
SimpleCursorAdapter adapter;
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
adapter=new SimpleCursorAdapter(this, R.layout.activity_all_restaurants,
doQuery(), new String[] {
RestaurantDB.colRestaurantName,
RestaurantDB.colRestaurantStore },
new int[] { R.id.title, R.id.value },
0);
}
else {
adapter=new SimpleCursorAdapter(this, R.layout.activity_all_restaurants,
doQuery(), new String[] {
RestaurantDB.colRestaurantName,
RestaurantDB.colRestaurantStore },
new int[] { R.id.title, R.id.value });
}
setListAdapter(adapter);
}
What I want to do is that when the users click on a particular item, another activity will pop up giving the users more information, which means I need to display the data stored in many other columns of the same item too. My question is how I can do that. I thought I should use onListItemClick, but I don't know how to associate the item selected in the main activity to the new activity.
Also, in the main activity, I have two textviews in the list that display colRestaurantName and colRestaurantStore respectively. When I use onListItemClick, how can I just retrieve colRestaurantName?
I can do the following to retrieve the position, but I don't know how I can use it in the new activity:
#Override
public void onListItemClick(ListView parent, View v, int position,
long id){
Cursor c = ((SimpleCursorAdapter)parent.getAdapter()).getCursor();
selection = String.valueOf(c.getPosition());
Intent i = new Intent(AllRestaurants.this, RestaurantsInfo.class);
i.putExtra("restaurantSelection", selection);
startActivity(i);
}
Thanks.
implement onListItemClick for listview and get textview text and send it to next activity as:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
TextView tv = (TextView)v.findViewById(R.id.title);
String strcolRestaurantName=tv.getText().toString();
Intent intent =new Intent(CurrentActivity.this,NextActivity.class);
Bundle bundle = new Bundle();
bundle.putString("RestaurantName",strcolRestaurantName);
intent.putExtras(bundle);
startActivity(intent);
}}
and in NextActivity get Intent as in onCreate :
Intent i = getIntent();
Bundle extras = i.getExtras();
String strRestaurantName = extras.getString("RestaurantName");

returning something other than the actual label in a list view

If I have a listview which is populated with a string array say:
Mazda
Renault
Holden
Audi
and when I want to click on an item, rather than returning string "Mazda" I'd rather return an associated number e.g. Mazda Returns 0, Renault returns 1 etc.
Is this possible and would I see a significant performance increase on querying an
SQLite DB using just ints rather than strings?
Thanks,
M
in your listview there are adapter are use, so in this method there are position variable also already exist there.if you print it in logcat it will get every time position of your list-item.you need to handle it in array easily
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String pen = o.toString();
Toast.makeText(this, "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show();
}
You could do something like the following:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] MY_CARS = new STRING[] { Mazda, Renault, Holden, Audi };
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, MY_CARS));
ListView lv = (ListView)findViewById(R.id.MyListView);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "Item at Position "+pos+" was clicked. This corresponds to "+MY_CARS[pos],
Toast.LENGTH_SHORT).show();
}
});
}
This should return the position of the item in the list that was clicked, which should be the index of the array.
I am not sure whether you will get a significant increase in db performance though.

How to interact with Android ListView

I have created a ListView where I have to add different items. Now, when I click on a particular item it displays another window. On that window, I want to display the name of that item which I click on the ListView.
My code:
private ListView contactList;
private String lv_arr[]={"Android","iPhone","BlackBerry","AndroidPeople"};
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.contact_activity);
contactList=(ListView)findViewById(R.id.ListView01);
contactList.setAdapter(new ArrayAdapter<String (this,android.R.layout.simple_list_item_1 , lv_arr));
contactList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/*Intent myIntent = new Intent(view.getContext(), CallActivity.class);
startActivity(myIntent);*/
}
});
}
you have to get the name of the item on itemclick event. pass it to the activity which will be called. in in the calling activity get the name of item and display
contactList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selecteditem = lv_arr[position];
Intent myIntent = new Intent(view.getContext(), CallActivity.class);
intent.putExtra("item", selecteditem);
startActivity(myIntent);
}
});
In CallActivity.java
write the following to get the selected item name
String selectedItem=getIntent().getStringExtra("item");
Instead of starting a new activity, use AlertDialog. You already have the position of the list item clicked. So displaying it on the dialog shouldn't be a problem if you follow the article linked.
EDIT :
As per your requirement, you have to launch a new activity to display a string
In the sending list activity
intent.putExtra(String key, String value)
In receiving activity,
String value = getIntent().getStringExtra(key);

Categories

Resources