Android - spinner position value - android

Im using a Spinner in an AlertDialog as a Filter. When I reopen the Dialog after selecting an item, I want to select the chosen item from before by default. But some kind of magic is happening and I cant understand why the spinner is selecting the wrong item. The item list for the spinner is a String array with numbers from 4 to 42. {"4","6",.."42"}
When I select the first item "4" the position should be 0 and when I reopen the Dialog the exact item should be displayed. But instead it displays the item "10" on position 4.
Code Dialogfragment:
public class FittingSelectionDialogFragment extends DialogFragment {
private String dTitle;
private String[] list;
private int position;
private String filterItem;
private List<String> chosenFilterItems;
public interface FittingSelectionDialogListener {
public void onChosenDialogItem(String filterStrings,int menuPosition);
}
FittingSelectionDialogListener mListener;
public Dialog onCreateDialog(Bundle savedInstanceState){
final Spinner spinner2 = new Spinner(getActivity());
final TextView label = new TextView(getActivity());
final TextView label2 = new TextView(getActivity());
LinearLayout layout = new LinearLayout(getActivity());
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setGravity(Gravity.CENTER);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getContext(), R.layout.support_simple_spinner_dropdown_item, list);
spinner2.setAdapter(adapter2);
if(chosenFilterItems.get(position).equals("")) {
spinner2.setSelection(0);
}
else{
spinner2.setSelection(Integer.valueOf(chosenFilterItems.get(position)));
}
label.setText("Rohr AD:");
label.setTextColor(getResources().getColor(R.color.colorParkerBlack2));
label.setTextSize(16);
label.setPadding(60,0,40,0);
label2.setText("mm");
label2.setTextSize(16);
label2.setTextColor(getResources().getColor(R.color.colorParkerBlack2));
dialog.setTitle(getdTitle());
layout.addView(label);
layout.addView(spinner2);
layout.addView(label2);
dialog.setView(layout);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int spinner2Position, long id) {
filterItem = list[spinner2Position];
chosenFilterItems.set(position,String.valueOf(spinner2Position));
Toast.makeText(getContext(),chosenFilterItems.get(position),Toast.LENGTH_SHORT).show(); //correct value
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
dialog.setPositiveButton("Bestätigen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListener.onChosenDialogItem(filterItem,position);
Toast.makeText(getContext(),chosenFilterItems.get(position),Toast.LENGTH_SHORT).show();//wrong value
dismiss();
}
});
dialog.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
filterItem = "";
chosenFilterItems.set(position,"");
mListener.onChosenDialogItem(filterItem, position);
}
});
return dialog.create();
}
}
I made two Toasts inside the Listeners. The crazy thing is that in the OnItemSelectedListener the correct position value is displayed. In the PositiveButton OnClickListener is displaying the wrong value. Have you any idea?

I made a workaround by myself. I did not found the mistake by debugging. So I dont work with the position. I use the value to reselect the chosen Item. Not the best way, but works for this small itemlist.
Code:
if(chosenFilterItems.get(position).equals("")) {
spinner2.setSelection(0);
}
else{
for(int i=0; i<list.length;i++){
if(list[i].equals(chosenFilterItems.get(position))){
spinner2.setSelection(i);
}
}
}
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int spinner2Position, long id) {
filterItem = list[spinner2Position];
}
dialog.setPositiveButton("Bestätigen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
chosenFilterItems.set(position,filterItem);
mListener.onChosenDialogItem(filterItem,position);
dismiss();
}
});

Use Handler and add some delay
int delay = 1000;
runOnUiThread (new Runnable () {
#Override
public void run () {
if(chosenFilterItems.get(position).equals("")) {
spinner2.setSelection(0);
} else {
Integer.valueOf(chosenFilterItems.get(position)));
}
}
}, delay);

Related

Remove item list from DB MSSQL using ListView.setOnItemLongClickListener Android

I have created a database which is displayed in a ListView using an SimpleAdapter. Now, I want to show a layout which contain (edit & delete ), so when user longClick on an item of the list it will get a dialog to choose if its want to delete or to edit on this item. Now, I'm focusing on delete statement and
I have tried with this code, but it does not work for me, the program always force close when I use this code.
Thanks
#Override
protected void onCreate(Bundle savedInstanceStates){
super.onCreate(savedInstanceStates);
setContentView(R.layout.activity_user_lstview);
userDataListView = (ListView) findViewById(R.id.ListViewUser);
List<Map<String, String>> data = new ArrayList<Map<String, String>>(
String[] from = {"tvId", "tvUsr", "tvPass", "tvDept","tvAuth"};
int[] to = {R.id.tvId, R.id.tvUsr, R.id.tvPass, R.id.tvDept, R.id.tvAuth};
adapter = new SimpleAdapter(UserListView.this, data, R.layout.userlisttemplate, from, to);
userDataListView.setAdapter(adapter);
userDataListView.setLongClickable(true);
userDataListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),"Clicked item : " +adapter.getItem(position), Toast.LENGTH_LONG).show();
}
});
userDataListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
final int which_item = position;
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UserListView.this);
dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
dialogBuilder.setTitle("Confirmation");
dialogBuilder.setMessage("Choose an option edit or delete data ?");
dialogBuilder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
// Edit
­­
dialogInterface.dismiss();
}
});
dialogBuilder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
// Delete
data.remove(which_item);
adapter.notifyDataSetChanged();
Toast.makeText(UserListView.this, "Data has been removed", Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
});
dialogBuilder.create().show();
return true;
}
});
}

DeleteFunction(Long) in DatabaseHelper Cannot be applied to java.lang.String

Good Day, I'm new to android development and i practice CRUD operation but i got an error in deleting the the selected item on my List View and i want to Update the list view after deleting.
Here's my code for deleting in Database Helper
public void deletegroce(int groceId){
String groceid[] = {String.valueOf(groceId)};
SQLiteDatabase sqdb = this.getWritableDatabase();
sqdb.delete(TABLE_NAME, KEY_GROCE_ID + " = ?", groceid);
sqdb.close();
}
}
And this is my code for my list
public class Grocery_list extends Activity {
ListView lvGorc;
DatabaseHelper dbhelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grocery_list);
lvGorc = (ListView) findViewById(R.id.lvGroc);
dbhelper = new DatabaseHelper(Grocery_list.this);
final ArrayList<String> aList = dbhelper.getAllGroceries();
ArrayAdapter<String> La = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, aList);
lvGorc.setAdapter(La);
lvGorc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, int i, long l) {
AlertDialog.Builder adb = new AlertDialog.Builder(Grocery_list.this);
adb.setTitle("Option");
adb.setMessage("What do you want to do?");
adb.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
adb.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dbhelper.deletegroce(i);
}
});
adb.show();
}
});
La.notifyDataSetChanged();
lvGorc.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder adb = new AlertDialog.Builder(Grocery_list.this);
adb.setTitle("Delete?");
adb.setMessage(aList.get(position));
adb.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dbhelper.deletegroce(aList.get(position));
}
});
adb.show();
return true;
}
});
}
}
THANK YOU SO MUCH
Your deleteGroce() method expects an int (groceId), but your ArrayAdapter get() method will return a String value, you need to use Int.parseInt(aList.get(position)) instead of just aList.get(position) in the call method :)

my OnItemClickListener and OnItemLongClickListener didn't function at all

This is my MainActivity.java
public class MainActivity extends Activity implements OnClickListener{
ArrayList<Product> products = new ArrayList<Product>();
final Context context = this;
ListAdapter boxAdapter;
String[] dataArray;
EditText editText;
//name that get back through the dialog
private String getName;
private String selectedItem;
private ArrayAdapter<String> adapter; // The list adapter
/** Called when the activity is first created. */
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
fillData();
boxAdapter = new ListAdapter(this, products);
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(boxAdapter);
Button btn = (Button) findViewById(R.id.AddItem);
//the add item button function
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
//get the dialog view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.insert);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// get user input and set it to result
// edit text
getName=userInput.getText().toString();
products.add(new Product(getName,false));
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
// Create the listener for normal item clicks
OnItemClickListener itemListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long rowid) {
Toast.makeText(
getApplicationContext(),
"You have clicked on " + parent.getItemAtPosition(position).toString() + ".",
Toast.LENGTH_SHORT).show();
}
};
//the long press to delete function
OnItemLongClickListener itemLongListener = new OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// Store selected item in global variable
selectedItem = parent.getItemAtPosition(position).toString();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Do you want to remove " + selectedItem + "?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
products.remove(selectedItem);
boxAdapter.notifyDataSetChanged();
Toast.makeText(
getApplicationContext(),
selectedItem + " has been removed.",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Create and show the dialog
builder.show();
// Signal OK to avoid further processing of the long click
return true;
}
};
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
}
void fillData() {
dataArray = getResources().getStringArray(R.array.ChecklistData);
for(String productName : dataArray)
{
products.add(new Product(productName,false));
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
This is ListAdapter.java
public class ListAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;
ListAdapter(Context context, ArrayList<Product> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Product p = getProduct(position);
((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
/*((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);*/
CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
cbBuy.setOnCheckedChangeListener(myCheckChangList);
cbBuy.setTag(position);
cbBuy.setChecked(p.box);
return view;
}
Product getProduct(int position) {
return ((Product) getItem(position));
}
ArrayList<Product> getBox() {
ArrayList<Product> box = new ArrayList<Product>();
for (Product p : objects) {
if (p.box)
box.add(p);
}
return box;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
getProduct((Integer) buttonView.getTag()).box = isChecked;
}
};
}
OnItemClickListener and OnItemLongClickListener didn't function at all. Anyone help me out here.. I did diagnose the problem but it still doesn't have function
OnItemClickListener itemListener = new OnItemClickListener() {
OnItemLongClickListener itemLongListener = new OnItemLongClickListener() {
You just define those variables but you don't assign them to your ListView.
You should call these lines somewhere:
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
UPDATE:
You also miss to register the list for context menu.
registerForContextMenu(lvMain);
implement View.OnItemClickListener and AdapterView.OnItemLongClickListener and their corresponding methods in your class.
initialize your views correctly (findViewById...)
set click listeners to your views (button.setOnClickListener(this) / button.setOnLongClickListener(this)
react to the push events in the implemented methods like:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
this.doSomething();
}
}
and
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//react to the view or react to the position
switch (view.getId()) {
case R.id.button:
this.doSomething();
}
return true;
}
You need to register listeners. Add following lines to the end of your onCreate() method.
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
I had the exact same problem. When onclick or onlongclick are enabled in the Layout; onitemclickListener wont work. Just remove the tags android:clickable and android:longclickable from your Layout XML resource and it will all work.

popup menu for spinner in android

i want a spinner with items'A','B','C'
if u select 'A' or'B' means the chronometer has to run.
while select the item 'C' the popup window has 2 open with edittext and 'Ok' button..
if you type the'D' in the edittext means that has too add in the spinner while add the chonometer has to run
here is my code:
public class Starttracker extends Activity {
PopupWindow popupWindow;
String[] Items = {
"A",
"B",
"C",
"D",
};
Spinner s1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
s1 = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item,Items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
int index = s1.getSelectedItemPosition();
Toast.makeText(getBaseContext(),
"You have selected item : " + Items[index],
Toast.LENGTH_SHORT).show();
if (index==3)
{
LayoutInflater inflater = (LayoutInflater) Starttracker.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
popupWindow = new PopupWindow(inflater.inflate(R.layout.popup,null, false),300,100,true);
// RelativeLayout01 is Main Activity Root Layout
popupWindow.showAtLocation(findViewById(R.id.relativelayout), Gravity.CENTER, 0,0);
} else
{
Chronometer chrono=(Chronometer)findViewById(R.id.chronometer);
chrono.start();
}
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
can any help to me
final String[] items = {"A", "B", "C"};
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose me!");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if ("A".equals(items[item]) || "B".equals(items[item])) {
// run whatever...
}
if ("C".equals(items[item])) {
final EditText edit = new EditText(context);
final Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose a custom option.");
builder.setView(edit);
builder.setPositiveButton("Save", new OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
String input = edit.getText().toString();
// add input to array, or do whatever.
dialog.dismiss();
}
});
builder.create().show();
}
dialog.dismiss();
}
});
builder.create().show();
I didn't test it (written straight from my mind), but it should work with a few modifications.
Good luck
Tom
TRy this code..
public class Starttracker extends Activity {
String[] Items = {
"A",
"B",
"C",
"D",
};
Spinner s1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
s1 = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item,Items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
}
public boolean onItemSelected(AdapterView parent,View v, int position, long id) {
if (((items[position])=="A")||((items[position])=="B")) {
Chronometer chrono=(Chronometer)findViewById(R.id.chronometer);
chrono.start();
}
}
//.....
GoodLuck
the answer is following to my question:
{
int size=tempArray.length;
for(int i=0;i<size;i++){
Items.add(tempArray[i]);
}
and
if(index==3)
{
final Dialog dialog=new Dialog(Starttracker.this);
dialog.setContentView(R.layout.popup);
dialog.setTitle("Enter The Item");
dialog.setCanceledOnTouchOutside(true);
final EditText filename=(EditText)dialog.findViewById(R.id.filename);
filename.setText("");
Button d_ok=(Button)dialog.findViewById(R.id.d_ok);
Button d_cancel=(Button)dialog.findViewById(R.id.d_cancel);
d_ok.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
String textHolder = filename.getText().toString();
dialog.dismiss();
Items.add(textHolder);
// s1.setAdapter(adapter);
// notifyDataSetChanged();
}
});
d_cancel.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View v,MotionEvent me){
dialog.dismiss();
return false;
}
});
dialog.show();
return;
}
thank a lot to all
Shameless plug for my project.
Check out Android Popup Spinner View

AlertDialog doesn't display items from ListAdapter Hide options

When I try to set the Alert using ArrayAdaptor to display a set of
items, the list is displayed but the items' characters are invisible.
If the item is selected, then the characters are visible. Scratching
my head on why. Appreciate any advice. Below is the code and the
screenshot from the emulator.
public class MessageTest extends Activity implements
View.OnClickListener {
public final static String debugTag = "MessageDemo::";
Button alert;
Button toast;
String[] items={"item1", "item2", "item3", "item4", "item5" };
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.message);
alert=(Button)findViewById(R.id.alert);
alert.setOnClickListener(this);
}
public void onClick(View view) {
if (view==alert) {
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, items);
new AlertDialog.Builder(this)
.setTitle("MessageTest")
.setSingleChoiceItems(aa, 0, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dlg, int which) {
Log.d(MessageDemo.debugTag,
"DialogInterface.OnClickListener::onClick() is called -> which =
"+which);
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
Log.d(MessageDemo.debugTag, "OK button is clicked -> sumthin
= "+sumthin);
}
})
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
Log.d(MessageDemo.debugTag, "Close button is clicked ->
sumthin = "+sumthin);
// do nothing -- it will close on its own
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dlg, int sumthin) {
Log.d(MessageDemo.debugTag, "Cancel button is clicked ->
sumthin = "+sumthin);
}
})
.show();
}
}
I know I'm a bit late at answering, but I had the same problem and I fixed it by simply changing
ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, items);
to
ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.layout.select_dialog_singlechoice, items);
I hope it helps someone.
As Quintin already mentioned in the comment, the problems reason maybe that the text color and background of the list items are the same. Use another view template for your list items, eg. android.R.layout.select_dialog_item:
builder.setAdapter(
new ArrayAdapter<Object>(context, android.R.layout.select_dialog_item, my_array)
{
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row;
if (null == convertView)
{
row = inflater.inflate(android.R.layout.select_dialog_item, null);
}
else
{
row = convertView;
}
TextView tv = (TextView) row.findViewById(android.R.id.text1);
tv.setText(getItem(position).toString());
return row;
}
}, ...
The layout inflater can be grabbed over a context:
final LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Categories

Resources