How do I determine who fired onContextItemSelected? - java

I am using an ExpandableListView, same way they do in this sample code:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList1.html
The ExpandableListView gets populated with categories and their subcategories (once I click on a category). Example:
-Dairy (category)
-Milk (sub category)
-cheese (sub category)
When I long-click on milk or cheese, a menu pops up using this function:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
ExpandableListContextMenuInfo info =(ExpandableListContextMenuInfo) menuInfo;
String selectedWord = ((TextView) info.targetView).getText().toString();
menu.setHeaderTitle(selectedWord.split(",")[1]); //set header
String itemId = selectedWord.split(",")[0];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", "getProducts"));
nameValuePairs.add(new BasicNameValuePair("subcat_id", itemId));
String response = helper.makeHttpRequest(nameValuePairs);
String[] items = response.split(";");
for (int i=0; i<items.length; i++){
menu.add(0, 0, 0, items[i]);
}
}
Then, when I click on one of the items in the menu that pops up, I want to know which item in the list was selected (If I click on 'milk'. for example, the menu has "1% milk", "2% milk" etc._
This function gets fired:
#Override
public boolean onContextItemSelected(MenuItem item) {
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();
String title = ((TextView) info.targetView).getText().toString();
String selected="";
int type = ExpandableListView.getPackedPositionType(info.packedPosition);
if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
Toast.makeText(this, title + " selected: " + selected+ " " + childPos + " clicked in group " + groupPos , Toast.LENGTH_SHORT).show();
return true;
} else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
Toast.makeText(this, title + " selected: " + selected + " " + childPos + " clicked in group " + groupPos , Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
But I don't find a way to determine which item exactly in the list was clicked.
Any ideas?
Thank you in advance! Please let me know if I need to be more clear.

Each item that you add to the ContextMenu should have its own unique identifier. This is useful for when you need to figure out which menu item was selected. So adding menu items needs to look like this: menu.add(0, unique_id, 0, items_name);. Then when you want to determine which item was selected you do something like this in onContextItemSelected using the item id:
switch (item.getItemId()){
case UNIQUE_ID_1:
//handle what to do
break;
case UNIQUE_ID_2:
//handle what to do
break;
....
So you may need to change your implementation slightly. I would create a unique id as an int constant for each possible case and add each one specifically to the menu. It may a little more code but it will be so much easier to handle.
Also just a suggestion since you are new here: when someone provides a good answer, you should accept it by clicking the check mark next to the answer. Good luck!

Related

CheckBox isSelected() method always returns false

I am working on an Android application where I have to check the CheckBox selection onClick() so I made this
if (checkBoxRM.isSelected() == true) {
isSelectedValue = "True";
//debug
Toast.makeText(MainActivity.this, "Kiejölés értéke: " + isSelectedValue, Toast.LENGTH_SHORT).show();
} else {
//debug
isSelectedValue = "False";
Toast.makeText(MainActivity.this, "Kiejölés értéke: " + isSelectedValue, Toast.LENGTH_SHORT).show();
}
But seems like isSelectedValue is always false.
Instead of isSelected() perform isChecked().
You have to cast the checkBox to enable isChecked()
This works:
boolean selected = ((CheckBox)view.findViewById(R.id.main_cbSelectAll)).isChecked();
This not (here, you can only choose "isSelected"):
boolean selected = view.findViewById(R.id.main_cbSelectAll).isChecked();
If you want to use it as an SQLite-statement, you have to transform to an integer:
int selected = ((CheckBox)view.findViewById(R.id.main_cbSelectAll)).isChecked() ? 1 : 0;

How to access duplicate values in simple combo box in ExtJs

I have a SimpleComboBox in GUI which contains some duplicate items also. Assume there are 3 items which is same as "domain". When i select second "domain" or third "domain", the selected item and selected index is always pointing to first occurance of "domain". How can i correct, so that the selected index/item is right one, instead of first occurance of item?
ComboBox with duplicate values:
When i select "domain" at fourth occurence it will always pointing the first occurance of "domain".
Output:
When i select the "192.168.1.30" at last occurenece, it will point the first occurance of "192.168.1.30".
Please any one help me.
private SimpleComboBox<String> domainName = new SimpleComboBox<String>();
domainName = WidgetUtil.getStringCombo("Domain Name", 12, true, domainNameList, null);
domainName.addSelectionChangedListener(getReportSelectionListener());
domainName.setForceSelection(true);
domainName.setTriggerAction(TriggerAction.ALL);
private Button New, add, remove;
New = WidgetUtil.getButton("New", "new", "");
New.addSelectionListener(buttonAction());
thirdLayoutContainer.add(New);
add = WidgetUtil.getButton("Add", "add", "");
add.addSelectionListener(buttonAction());
add.setStyleAttribute("paddingTop", "10px");
thirdLayoutContainer.add(add, formData);
remove = WidgetUtil.getButton("Remove", "remove", "");
remove.addSelectionListener(buttonAction());
public void componentSelected(ButtonEvent ce){
String domain_name = null;
if (ce.getComponent().getId().equals("remove")){
System.err.println("Clicked remove button...");
domain_name = domainName.getRawValue();
domainNameList.remove(domain_name);
systemDetailsMap.remove(domain_name);
systemDetailsMap.remove(domain_name + "_USER_NAME");
systemDetailsMap.remove(domain_name + "_HOST_NAME");
systemDetailsMap.remove(domain_name + "_PASSWORD");
domainName.removeAll();
domainName.add(domainNameList);
userName.clear();
hostName.clear();
password.clear();
System.err.println("After remove domain name list ---> " + domainNameList);
System.err.println("After remove map ---> " + systemDetailsMap);
} else if (ce.getComponent().getId().equals("add")) {
System.err.println("Clicked add button...");
domain_name = domainName.getRawValue();
domainNameList.add(domain_name);
systemDetailsMap.put(domain_name, domain_name);
systemDetailsMap.put(domain_name + "_HOST_NAME", hostName.getValue());
systemDetailsMap.put(domain_name + "_USER_NAME", userName.getValue());
systemDetailsMap.put(domain_name + "_PASSWORD", password.getValue());
// domainName.clear();
domainName.add(domainNameList);
// domainName.reset();
System.err.println("After add domain name list ---> " + domainNameList);
System.err.println("After add map ---> " + systemDetailsMap);
} else if (ce.getComponent().getId().equals("new")) {
System.err.println("Clicked new button...");
userName.clear();
hostName.clear();
password.clear();
domainName.removeAllListeners();
domainName.removeAll();
domainName.clear();
domainName.setEmptyText("Add a new domain");
userName.setEmptyText("Add a new username");
hostName.setEmptyText("Add a new hostname");
password.setEmptyText("Add a new password");
domainName.addSelectionChangedListener(getReportSelectionListener());
}
}
};
private SelectionChangedListener<SimpleComboValue<String>> getReportSelectionListener(){
SelectionChangedListener<SimpleComboValue<String>> ReportListener = new SelectionChangedListener<SimpleComboValue<String>>() {
#Override
public void selectionChanged(SelectionChangedEvent<SimpleComboValue<String>> se) {
SimpleComboValue<String> selectedValue = se.getSelectedItem();
String value = selectedValue.getValue();
System.err.println("Selected Value ---> " + selectedValue.getValue());
if (value != null && !value.equals("---New---") ){
userName.clear();
hostName.clear();
password.clear();
userName.setValue(systemDetailsMap.get(value + "_USER_NAME").toString());
hostName.setValue(systemDetailsMap.get(value + "_HOST_NAME").toString());
password.setValue(systemDetailsMap.get(value + "_PASSWORD").toString());
}
}
};
return ReportListener;
}
Please help me. Thanks in advance.
I am not using Ext-gwt just the standard ext-js, but I think I know what you need! You should define a display and value field.
Ext.create('Ext.form.ComboBox', {
store: xyz,
queryMode: 'local',
displayField: 'name',
valueField: 'id',
renderTo: Ext.getBody()
});
You just have to make sure, that the duplicated items are getting unique id. I think that if this is possible in ext-js it should also be possible in ext-gwt!

Count Total Number of Items based on Condition

In my program i am using ListView and in each and every row i am showing one of the image icon (Yes/No) based on condition i am playing with, and using below code to get total number of item(s) in a list (includes both :- Yes & No) Icons.
String totalNumberOfItemsInAList = ""+ lstView.getAdapter().getCount();
Toast.makeText(getApplicationContext(), "Total number of Items are:" + totalNumberOfItemsInAList, Toast.LENGTH_LONG).show();
But what if i only want to know total number of items in a list which contains Yes Icon, my code looks like this:
private SparseBooleanArray flags = new SparseBooleanArray();
// to upload whole list
for(int position = 0; position < lstView.getAdapter().getCount(); position++)
{
flags.put(position, true);
}
((BaseAdapter) lstView.getAdapter()).notifyDataSetChanged();
}
});
/*** Get Images from SDCard ***/
listSDCardImages = fetchSDCardImages();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listSDCardImages);
lstView.setAdapter(new ListSDCardImagesAdapter(this));
Toast.makeText(getApplicationContext(), "Total number of Items are:" + String.valueOf(position), Toast.LENGTH_LONG).show();
}
Condition, i am using to show Yes/No icons is something like this:
if(resultAvailable)
{
holder.colView.setImageResource(R.drawable.icon_yes);
}
else
{
holder.colView.setImageResource(R.drawable.icon_no);
}
Use
yesImagesCount=0;
variable in your activity and increment this count in this code as
if(resultAvailable)
{
holder.colView.setImageResource(R.drawable.icon_yes);
yesImagesCount++;
}
else
{
holder.colView.setImageResource(R.drawable.icon_no);
}
And Finally display toast as
Toast.makeText(getApplicationContext(), "Total number of Yes Icons are:" + String.valueOf(yesImagesCount), Toast.LENGTH_LONG).show();

Change Spinner options based on another Spinner

I am trying to implement a user search through my database with the use of spinners.
I have fleets and vehicles(fleets contain vehicles). I have a list of fleets as one spinner and a list of vehicles as the other.
By default I want the fleets to be set to "All" and the vehicle one to show all the vehicles(This is currently the case), however when the fleet input is changed to a particular one, say fleet1, the vehicle spinner should update accordingly[this will be implemented via SQLite database search but I don't think the issue is here].
How do I make a listener for when fleet spinner data is changed?
vehicleSpinner = (Spinner) findViewById(R.id.vehicleSpinner);
String selected = (String)fleetSpinner.getSelectedItem();
ArrayAdapter<String> adapter5 = null;
if(selected == "All"){
//show all vehicles
adapter5 = new ArrayAdapter<String>(this, R.layout.sherlock_spinner_item, vehicleArrayListString);
}else{
String vehiclesInFleetQuery = "SELECT * FROM " + Database.TABLE_VEHICLE + " WHERE " + Database.COLUMN_FLEET + "='" + selected +"'";
Log.i(TAG,"QUERY: "+ vehiclesInFleetQuery);
Cursor cursor = Database.listOfVehiclesDesired(query);
if(cursor.moveToFirst()){
do {
String addToList = cursor.getString(cursor.getColumnIndex(Database.COLUMN_VEHICLE_ID));
vehicleArrayFleet.add(addToList);
} while (cursor.moveToNext());
}else{//error on fleet search, no vehicles in fleet
vehicleArrayFleet = vehicleArrayListString;
builderContinue.setMessage("Selected Fleet(" + selected + ") had zero associated vehicles").setTitle("Error").show();
}
if (cursor != null && !cursor.isClosed()) {
System.out.println("Closed");
cursor.close();
}
adapter5 = new ArrayAdapter<String>(this, R.layout.sherlock_spinner_item, vehicleArrayFleet);
}
adapter5.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
vehicleSpinner.setAdapter(adapter5);
You need to set an OnItemSelectedListener for the fleet spinner. You can find an example at http://start-jandroid.blogspot.com/2011/01/android-spinner-example.html. From the listener in the fleet spinner, you can set the selected item of the vehicle spinner.

Android: IndexOutOfBounds Error when deleting row in ListView

I have an application that has 2 screens. The first screen has a ListView of movies with a row consisting of 3 Elements: Title, Date and Gross declared in strings.xml. The user has the option of adding a movie by clicking the menu button, which sends him to another screen. The second screen has 3 Edit texts that correspond to Title Date and Gross, which is alphabetically sorted straight away when it returns to screen 1.
Similarly, the user can also Edit/Delete entries by long clicking a row thatbrings up a context menu. The Edit function works like this:
a.) User long clicks Titanic and chooses Edit
b.) Row gets deleted, and user is brought to screen 2
c.) Edit texts are populated with the initial data from the deleted Row
d.) When user edits data, new movie is added at the bottom of the ListView.
The problem arises when the user deletes this new movie at the bottom of the ListView. Logcat gives a
java.lang.IndexOutOfBoundsException: Invalid index 50, size is 50
Here is my code (Take note I am using Perst to persist data, but I don;t think that won't really matter with my problem):
case R.id.contextedit:
Lab9_082588FetchDetails row = (Lab9_082588FetchDetails) getListView()
.getItemAtPosition(info.position);
Intent editData = new Intent(MovieList.this, Lab9_082588Edit.class);
String startTitle = row.getTitle();
String startGross = row.getGross();
String startDate = row.getDate();
editData.putExtra(Lab9_082588Edit.TITLE_STRING, startTitle);
editData.putExtra(Lab9_082588Edit.GROSS_STRING, startGross);
editData.putExtra(Lab9_082588Edit.DATE_STRING, startDate);
startActivityForResult(editData, MovieList.EDIT_MOVIE);
int posEdit = info.position;
String editTitle = results.get(info.position).getTitle();
results.remove(posEdit);
adapter.notifyDataSetChanged();
//Perst
Index<Lab9_082588FetchDetails> rootEdit = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootEdit.remove(editTitle, results.get((int) info.id));
db.setRoot(rootEdit);
return true;
Edit Class:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection using item.getItemId()
switch (item.getItemId()) {
case R.id.edit:
next();
break;
}
return true;
}
private void next() {
// TODO Auto-generated method stub
EditText movieTitle = (EditText) findViewById(R.id.etTitle);
EditText movieGross = (EditText) findViewById(R.id.etGross);
EditText movieDate = (EditText) findViewById(R.id.etDate);
String title = movieTitle.getText().toString();
String gross = movieGross.getText().toString();
String date = movieDate.getText().toString();
if ((title.length() > 0) && (gross.length() > 0)
&& (date.length() == 4)) {
Intent hobby = getIntent();
hobby.putExtra(Lab9_082588Edit.TITLE_STRING, title);
hobby.putExtra(Lab9_082588Edit.GROSS_STRING, gross);
hobby.putExtra(Lab9_082588Edit.DATE_STRING, date);
setResult(RESULT_OK, hobby);
finish();
}
}
Delete function:
int posDelete = info.position;
String deleteTitle = results.get(
info.position).getTitle();
results.remove(posDelete);
adapter.notifyDataSetChanged();
Index<Lab9_082588FetchDetails> rootDelete = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootDelete.remove(deleteTitle,
results.get(info.position));
db.setRoot(rootDelete); //Perst
return;
OnActivityResult (Edit):
case EDIT_MOVIE:
Lab9_082588FetchDetails edittedMovie = new Lab9_082588FetchDetails();
NumberFormat formatterEdit = new DecimalFormat("###,###,###");
edittedMovie.setTitle(data
.getStringExtra(Lab9_082588Add.TITLE_STRING));
edittedMovie.setGross("$"
+ formatterEdit.format(Double.parseDouble(data
.getStringExtra(Lab9_082588Add.GROSS_STRING))));
edittedMovie.setDate(data
.getStringExtra(Lab9_082588Add.DATE_STRING));
results.add(edittedMovie);
adapter.notifyDataSetChanged();
Populating the Listview:
for (int i = 0; i < items.size(); i++) {
Lab9_082588FetchDetails sr = new Lab9_082588FetchDetails();
sr.setTitle(items.get(i).getTitle());
sr.setGross(items.get(i).getGross());
sr.setDate(items.get(i).getDate());
results.add(sr);
Collections.sort(results, ignoreCaseStart);
}
How do I remedy this?
This problem occurs because in your delete function, you first remove the element from the results collection("results.remove(posDelete);"), and then, a few lines later, you call "results.get(info.position)" to fetch a parameter for the rootDelete.remove call, but which is already removed.
If the element is the last element of your collection, let's say the 50th element, the value for "info.position" is 50. You remove one element, so the number of elements is now 49. In the rootDelete.remove line you call results.get(50), which produces the error.

Categories

Resources