Android Spinner OnItemSelect doesnt work - java

I have three different Spinner objects (two of them have a custom layout, one - spMode - is standard).
When the OkayButton is pressed, a Toast should be displayed with 3 Numbers: the SpinnerItemNumber of Mode, Color1 and Color2. But Mode is 0 each time the button is pressed. The others work fine. Just Mode is showing that item 0 is selected even if I select Item 2 or 3 in the App.
Here is the relevant code; any ideas why?
public class NewTimer extends Activity implements OnItemSelectedListener,OnClickListener
{
Button btnOkay;
EditText etTime;
int mode, minutes, color1, color2;
String[] strings = {"","",
"", "", "", ""};
int arr_images[] = { R.drawable.yellow,
R.drawable.orange, R.drawable.red,
R.drawable.blue, R.drawable.green, R.drawable.white};
public void onClick(View v)
{
if (v == btnOkay)
{
Toast.makeText(v.getContext(), Integer.toString(mode) + Integer.toString(color1) + Integer.toString(color2), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.newtimer);
Spinner spColor1 = (Spinner)findViewById(R.id.spColor1);
spColor1.setAdapter(new MyAdapter(NewTimer.this, R.layout.row, strings));
spColor1.setOnItemSelectedListener(this);
Spinner spColor2 = (Spinner)findViewById(R.id.spColor2);
spColor2.setAdapter(new MyAdapter(NewTimer.this, R.layout.row, strings));
spColor2.setOnItemSelectedListener(this);
etTime = (EditText) findViewById(R.id.etTime);
btnOkay = (Button) findViewById(R.id.btnOkay);
btnOkay.setOnClickListener(this);
Spinner spMode = (Spinner) findViewById(R.id.spMode);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.spMode_items, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spMode.setAdapter(adapter);
}
public void onItemSelected(AdapterView<?> parent,
View v, int pos, long id)
{
switch (parent.getId())
{
case R.id.spMode:
mode = pos;
break;
case R.id.spColor1:
color1 = pos;
break;
case R.id.spColor2:
color2 = pos;
break;
}
}
public void onNothingSelected(AdapterView<?> parent)
{
}
public class MyAdapter extends ArrayAdapter
{
public MyAdapter(Context context, int textViewResourceId,
String[] objects)
{
super(context, textViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater=getLayoutInflater();View row=inflater.inflate(R.layout.row, parent, false);
TextView label=(TextView)row.findViewById(R.id.color);
label.setText(strings[position]);
ImageView icon=(ImageView)row.findViewById(R.id.image);
icon.setImageResource(arr_images[position]);
return row;
}
}
}

You never set the setOnItemSelectedListener for that spinner:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newtimer);
Spinner spColor1 = (Spinner)findViewById(R.id.spColor1);
spColor1.setAdapter(new MyAdapter(NewTimer.this, R.layout.row, strings));
spColor1.setOnItemSelectedListener(this);
Spinner spColor2 = (Spinner)findViewById(R.id.spColor2);
spColor2.setAdapter(new MyAdapter(NewTimer.this, R.layout.row, strings));
spColor2.setOnItemSelectedListener(this);
etTime = (EditText) findViewById(R.id.etTime);
btnOkay = (Button) findViewById(R.id.btnOkay);
btnOkay.setOnClickListener(this);
Spinner spMode = (Spinner) findViewById(R.id.spMode);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.spMode_items, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spMode.setAdapter(adapter);
spMode.setOnItemSelectedListener(this); }
public void onItemSelected(AdapterView<?> parent,
View v, int pos, long id) {
switch (parent.getId())
{
case R.id.spMode:
mode = pos;
break;
case R.id.spColor1:
color1 = pos;
break;
case R.id.spColor2:
color2 = pos;
break;
} }

Related

Get name of the rowItem in listView onClick

I am trying to implement a simple listView with onClick functionality. On clicking the item in the listView, I want to show the name of the item in a 'toast message, but I am unable to do that. I have used the method suggested in this link and link but couldn't get the desired result. I have added my code below :
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItem = new AppList();
final ListView userInstalledApps = (ListView)findViewById(R.id.appListView);
List<AppList> installedApps = getInstalledApps();
CustomAppAdapter installedAppAdapter = new CustomAppAdapter(MainActivity.this, installedApps);
userInstalledApps.setAdapter(installedAppAdapter);
userInstalledApps.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView appName = (TextView)adapterView.findViewById(R.id.list_app_name);
Toast.makeText(getApplicationContext(),
"Clicked "+ adapterView.getItemAtPosition(i),Toast.LENGTH_LONG).show();
}
});
}
CustomAppAdapter.java
public class CustomAppAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private List<AppList> listStorage;
Context context;
public CustomAppAdapter(Context context, List<AppList> listStorage) {
layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.listStorage = listStorage;
}
#Override
public int getCount() {
return listStorage.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder listViewHolder;
if(convertView == null){
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.installed_app_list, parent, false);
listViewHolder.textInListView = (TextView)convertView.findViewById(R.id.list_app_name);
listViewHolder.imageInListView = (ImageView)convertView.findViewById(R.id.app_icon);
convertView.setTag(listViewHolder);
}else{
listViewHolder = (ViewHolder)convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
return convertView;
}
static class ViewHolder{
TextView textInListView;
ImageView imageInListView;
}
}
Below is the screenshot of the listView :
On trying this method:
Toast.makeText(getApplicationContext(),
"Clicked "+ adapterView.getItemAtPosition(i),Toast.LENGTH_LONG).show();
Suppose I clicked on the 2nd item in the listView so I get a toast message as Clicked 2. But I want that it shows me Clicked PhonePe
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItem = new AppList();
final ListView userInstalledApps = (ListView)findViewById(R.id.appListView);
List<AppList> installedApps = getInstalledApps();
CustomAppAdapter installedAppAdapter = new CustomAppAdapter(MainActivity.this, installedApps);
userInstalledApps.setAdapter(installedAppAdapter);
userInstalledApps.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView appName = (TextView)adapterView.findViewById(R.id.list_app_name);
Toast.makeText(getApplicationContext(),
"Clicked "+ installedApps.get(i).getName(),Toast.LENGTH_LONG).show();
}
});
}
Try this.

Android How to refresh or reload listview data and final totaling data

Android How to refresh or reload listview data and final totaling data that is total of the all price of the cart
check image i want the blue circle price add and show on the red circle and but if i delete or change quantity of product then also update the price in red circle
this is my code
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolderItem viewHolder;
if(convertView==null){
inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.toptext = (TextView) convertView.findViewById(R.id.cartname);
viewHolder.prc = (TextView) convertView.findViewById(R.id.textView76);
viewHolder.shp = (TextView) convertView.findViewById(R.id.textView77);
viewHolder.subtotal = (TextView) convertView.findViewById(R.id.textView79);
//viewHolder.textView80 = (TextView) convertView.findViewById(R.id.textView80);
viewHolder.img = (ImageView) convertView.findViewById(R.id.imageView7);
viewHolder.imageView2 = (ImageView) convertView.findViewById(R.id.imageView2);
viewHolder.spinner = (Spinner)convertView.findViewById(R.id.spinner);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolderItem) convertView.getTag();
}
final CartResponse response = getItem(position);
int subtotal1=0;
mydb = new DBHelper(getContext());
if(response != null) {
/* ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
R.array.qty, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
viewHolder.spinner.setAdapter(adapter);*/
viewHolder.spinner.setSelection(Integer.parseInt(response.getQty())-1);
viewHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
response.setQty(viewHolder.spinner.getSelectedItem()+"");
if(mydb.updateContact(Integer.parseInt(response.getid()),response.getPname(),Integer.parseInt(response.getPrice()),Integer.parseInt(response.getCutPrice()),++pos,Integer.parseInt(response.getShipping()),response.getPhoto())){
Log.d("key",""+response.getQty());
updateResults();
//Toast.makeText(getContext(),"updated", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
viewHolder.imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mydb.deleteContact(Integer.parseInt(response.getid()));
//int index =callback.indexOf(response.getid());
callback.remove(response);
updateResults();
Toast.makeText(getContext(),"Remove", Toast.LENGTH_SHORT).show();
}
});
int tamount=0,tship=0,gt=0;
tamount=tamount+(Integer.parseInt(response.getPrice())* Integer.parseInt(response.getQty()));
tship=tship+(Integer.parseInt(response.getShipping())* Integer.parseInt(response.getQty()));
gt=tamount+tship;
subtotal1=Integer.parseInt(response.getPrice()) + Integer.parseInt(response.getShipping());
viewHolder.toptext.setText(response.getPname());
viewHolder.prc.setText("Rs."+tamount);
//Log.d("key",""+response.getPrice());
viewHolder.shp.setText("Rs."+tship);
viewHolder.subtotal.setText("Sub total Rs."+gt);
Picasso.get().load("https://www.exmple.com/photos/"+response.getPhoto()+".png").placeholder(R.drawable.placeholder).memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(viewHolder.img);
}
Cart class
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_cart, container, false);
mydb = new DBHelper(getContext());
cart_list = mydb.getAllCotacts();
cartitems=cart_list.size();
int amount=0,shping=0;
for(int i=0;i<cartitems;i++){
int price = (Integer.parseInt(cart_list.get(i).getPrice())*Integer.parseInt(cart_list.get(i).getQty()));
int shp=(Integer.parseInt(cart_list.get(i).getShipping())*Integer.parseInt(cart_list.get(i).getQty()));
amount=amount+price;
shping=shping+shp;
}
TextView cout=(TextView)view.findViewById(R.id.textView75);
TextView gprice=(TextView)view.findViewById(R.id.textView87);
TextView gship=(TextView)view.findViewById(R.id.textView88);
gprice.setText("Rs."+amount);
gship.setText("Rs."+shping);
if(cartitems>0){
cout.setText("Your Cart Item");
}else{
cout.setText("Shopping Cart is Empty");
}
final CartAdapter adapter = new CartAdapter(getContext(), R.layout.cart_item, cart_list);
final ListView order_list = (ListView)view.findViewById(R.id.cartlist);
order_list.setAdapter(adapter);
adapter.notifyDataSetChanged();
order_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
adapter.notifyDataSetChanged();
//mydb.deleteContact(cart_list.get(position).getid());
//Log.d("key",""+cart_list.get(position).getQty());
//cart_list.get(position).getid();
}});
return view;
}

how to stop the duplicates of the elements in list view?

I am using a list view in my app. I wanted to get a list of chapters that I inserted but I saw that the list view elements are repeated until the end. However I didn't get the items that I listed it for because the same object keeps on repeating.
Here is the code that I used in my chapterAdapter.java and physics.java
chapterAdapter.java
public class chapterAdapter extends BaseAdapter {
private Context context;
private ArrayList<model1> models;
public chapterAdapter(Context context, ArrayList<model1> models) {
this.context = context;
this.models = models;
}
#Override
public int getCount() {
return models.size();
}
#Override
public Object getItem(int position) {
return models.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView ==null){
convertView = View.inflate(context, R.layout.chapters_view,null);
ImageView images = convertView.findViewById(R.id.chapterImage);
TextView title = convertView.findViewById(R.id.chapterTitle);
model1 model1 = models.get(position);
images.setImageResource(model1.getChapterImage());
title.setText(model1.getChapterTitle());
}
return convertView;
}
}
physics.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_physics);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView1 = (ListView)findViewById(R.id.chapters_list_view);
models = chapter_list_details.getList();
chapterAdapter = new chapterAdapter(physics.this,models);
listView1.setAdapter(chapterAdapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position )
{
case 0:
Intent newActivity = new Intent(physics.this, physics.class);
startActivity(newActivity);
break;
case 1:
Intent toy = new Intent(physics.this, ModelQuestions.class);
startActivity(toy);
break;
case 2:
Intent intent = new Intent(physics.this, chemistry.class);
startActivity(intent);
break;
}
}
});
}
please try removing the condition
if(convertView==null)

Programmatically create spinner work on click

I'm creating spinner programmatically spinner show perfectly dropdown but when I click ant item is not show Toast message when I debug is not go inside spinner click method what is wrong in my code? spinner item will show but click event not work what is wrong?
public class MainActivity extends Activity {
Spinner spinner;
String[] strings = { "Power Options", "Power off", "Restart" };
String[] subs = { "", "Shut phone down", "Close all apps and restart phone" };
int arr_images[] = { R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spinner = new Spinner(this);
spinner.setAdapter(new MyAdapter(this, R.layout.row, strings));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> adapterView, View view,
int i, long l) {
// TODO Auto-generated method stub
if (i == 1) {
Toast.makeText(MainActivity.this, "PowerOff Perform",
Toast.LENGTH_SHORT).show();
}
if (i == 2) {
Toast.makeText(MainActivity.this, "Reboot Perform",
Toast.LENGTH_SHORT).show();
}
}
// If no option selected
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
TextView label = (TextView) row.findViewById(R.id.company);
label.setText(strings[position]);
TextView sub = (TextView) row.findViewById(R.id.sub);
sub.setText(subs[position]);
ImageView icon = (ImageView) row.findViewById(R.id.image);
icon.setImageResource(arr_images[position]);
return row;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
spinner.performClick();
return true;
}
return super.onKeyDown(keyCode, event);
}
maybe use setOnItemClickListener instead of setOnItemSelectedListener ?
Try to use
spinner.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> arg0, final View arg1, final int arg2, final long arg3) {
}
});
instead of
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> adapterView, View view,
int i, long l) {...

how to write code for onitemClickListener for customized listview using BaseAdapter?

here is the code for custom listview using BaseAdapter in android its working fine:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<TaskClass> _listData;
Context _c;
public CustomListAdapter(Context context, ArrayList<TaskClass> listData) {
_listData = listData;
_c = context;
}
#Override
public int getCount() {
return _listData.size();
}
#Override
public Object getItem(int position) {
return _listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position,View convertView,ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater layoutInflator = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflator.inflate(R.layout.listview_row, null);
}
TextView titleText = (TextView)v.findViewById(R.id.holdTitleText);
TextView catText = (TextView)v.findViewById(R.id.holdCatText);
TextView descText = (TextView)v.findViewById(R.id.holdDescText);
TextView dateText = (TextView)v.findViewById(R.id.holdDateText);
//CheckBox checkBoxForEachItem = (CheckBox)v.findViewById(R.id.)
TaskClass taskClassInstance = _listData.get(position);
titleText.setText(taskClassInstance.getTitle());
catText.setText(taskClassInstance.getTaskCategory());
descText.setText(taskClassInstance.getDescription());
dateText.setText(taskClassInstance.getTaskDate());
return v;
}
}
and in activity i m binding listview with custom adapter :
listViewInstance.setAdapter(new CustomListAdapter(getApplicationContext(),taskClasslistInstance));
where "taskclasslistinstance" is my arraylist conatining data from DB its working fine
now i need to write function for listitemclick so that when user click on any listitem i can get rowid of that listitem record from Database.so after getting rowwid I can delete records from listview and from db and can edit informations
Well, we don't know about your TaskClass, but I expect you want something like this:
listViewInstance.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
TaskClass taskClass = taskClasslistInstance.get(pos);
Log.d(TAG, "Clicked on: " + taskClass)
// Do stuff with taskClass
}});
Here a small example from my project:
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LazyAdapterAlbum(getActivity(), songs);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(), AlbumActivity.class);
Bundle args = new Bundle();
args.putString(AlbumActivity.ALBUM_NAME, adapter.getItem(position).getName());
i.putExtras(args);
startActivity(i);
}
});
You have to set an onClickListener on your ListView.
you can also set in getView method like below:
public View getView(int position,View convertView,ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater layoutInflator = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflator.inflate(R.layout.listview_row, null);
}
TextView titleText = (TextView)v.findViewById(R.id.holdTitleText);
TextView catText = (TextView)v.findViewById(R.id.holdCatText);
TextView descText = (TextView)v.findViewById(R.id.holdDescText);
TextView dateText = (TextView)v.findViewById(R.id.holdDateText);
//CheckBox checkBoxForEachItem = (CheckBox)v.findViewById(R.id.)
TaskClass taskClassInstance = _listData.get(position);
titleText.setText(taskClassInstance.getTitle());
catText.setText(taskClassInstance.getTaskCategory());
descText.setText(taskClassInstance.getDescription());
dateText.setText(taskClassInstance.getTaskDate());
v.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform an action when this list item is clicked
}
});
return v;
}

Categories