sqlite database updating Gridview when searching with a searchview - java

i was able to create a database and fill it with some foods !! and display them in a gridview take a look screenshot of my app
i want to know how i can make the search view work so that when i search for a food the gridview gets updated too !!!
the second problem is : i implemented OnItemClickListener for each subitem in the gridview
public class FoodList extends AppCompatActivity {
GridView gridView;
static ArrayList<Food> list;
FoodListAdapter adapter = null;
SearchView sv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_list_activity);
gridView = (GridView) findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new FoodListAdapter(this, R.layout.food_items, list);
gridView.setAdapter(adapter);
// get all data from sqlite
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD ");
list.clear();
while (cursor.moveToNext()){
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
byte[] image = cursor.getBlob(3);
list.add(new Food(name, price, image, id));
}
adapter.notifyDataSetChanged();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Food food = list.get(position);
Intent i = new Intent(FoodList.this,Details.class);
i.putExtra("position", position);
Bundle bundle = new Bundle();
startActivity(i);
}
});
}
}
but this wont work when i add the searchview !! because the positions of the subitems will change and it wont return the right position when
Food food = list.get(position);
here is the activity that i am starting when subitems are clicked
public class Details extends AppCompatActivity {
int position;
Button b;
EditText edi;
ImageView im;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
b=(Button)findViewById(R.id.hotelbu);
edi=(EditText)findViewById(R.id.hoteled);
im = (ImageView)findViewById(R.id.hotelim);
text=(TextView)findViewById(R.id.hoteltx);
if(getIntent().getExtras() != null) {
position = getIntent().getExtras().getInt("position", 0);
}
switch(position){
case 9999:
break;
default:
text.setText(FoodList.list.get(position).getName());
edi.setText(FoodList.list.get(position).getPrice());
break;
}
}
}
i hope you guys understand what i am looking for , sorry for my bad english , any help is appreciated Thank you

You must have to use AutoCompleteTextView instead of simple EditText. AutoCompleteTextView is an editable text view that shows a list of suggestions in a drop down list automatically when user is typing, from which the user can choose an item to replace the content of the edit box with.
auto_complete_textview = (AutoCompleteTextView)findViewById(R.id.auto_complete_textview);
auto_complete_textview.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
adapter.getFilter().filter(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
Now create an adapter class that extends BaseAdapter and implements Filterable interface, override all methods of BaseAdapter and getFilter() method of Filterable interface and do all stuff what you want.
You can see the example of AutoCompleteTextView on this link
[http://www.javatpoint.com/android-autocompletetextview-example]
This is the xml code to create AutoCompleteTextView
<AutoCompleteTextView
android:id="#+id/auto_complete_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search"/>

Related

How to send random position to next activity

I am showing random images in gridview using string array urls with picasso in first activity and when I'm clicking on any image in gridview then I want to show that exact random image in next activity. i am using put extra and sending that position like int r = random.nextInt(array.length); I'm using that r into gridview put extra as position. but when i m setting that r in imageview its showing another random image not exact.
This is my code
public class MainActivity extends Activity {
static Random random;
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
static int p;
// Some items to add to the GRID
static final String[] icons= {
"https://abhiandroid.com/ui/wp-content/uploads/2015/12/horizontalSpacing-in-Gridview.jpg",
"http://www.whatsappstatusmessages.com/wp-content/uploads/2017/01/whatsapp-dp-images-in-english.jpg",
"http://www.sarkarinaukrisearch.in/wp-content/uploads/2019/02/whatsapp-dp-status-in-english-1-77.jpg",
"https://www.trueshayari.in/wp-content/uploads/2018/07/Love-Status-DP-for-Couple.jpg",
"https://4.bp.blogspot.com/-2iawNx83Kpw/XL21pPj0aPI/AAAAAAAAKiE/VRR7pupbWDUj0TNNAKdGH8Baaz_c9IcSgCLcBGAs/s1600/ss.jpg",
"https://www.trueshayari.in/wp-content/uploads/2018/07/Love-Status-DP-for-Couple.jpg",
"https://3.bp.blogspot.com/-8us6YRiZEh0/XL21c6ibbXI/AAAAAAAAKh4/eNyjErq7q04YCeWxDPWojYfOoAC8BCodwCLcBGAs/s1600/s.jpg"
};
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.albumGrid);
CustomAdopter customAdopter=new CustomAdopter();
gridView.setAdapter(customAdopter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SwipeView.class);
intent.putExtra("id", p);
startActivity(intent);
}
});
}
private static class CustomAdopter extends BaseAdapter {
static int p;
#Override
public int getCount() {
return icons.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.layout.phototem, null);
ImageView imageView = view.findViewById(R.id.cover);
random = new Random(); // or create a static random field...
p= random.nextInt(icons.length);
Picasso.get().load(icons[p]).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).into(imageView);
return view;
}
}
Showing Image in this Activity
public class SwipeView extends Activity
{
int positions;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_view);
// get intent data
Intent i = getIntent();
// Selected image id
positions = i.getExtras().getInt("id");
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(technoapps4.goodnightshayariworld.MainActivity.p);
}
private class ImagePagerAdapter extends PagerAdapter
{
String[] icons =MainActivity.icons ;
#Override
public int getCount()
{
return icons.length;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position)
{
Context context = SwipeView.this;
ImageView imageView = new ImageView(context);
Picasso.get().load(icons[position]).into(imageView);
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((ImageView) object);
}
}
}
For this purpose, you should create an Interface and pass the random position though that interface.
And the variable p isn't the clicked item position. The value of p is changing continuously while the gridView is populating items.
Edit:
Create an Interface like this:
public interface ItemClickListener {
void onItemClick(int position);
}
Now initialize the ItemClickListener instance inside your CustomAdopter class using the public setter.
public void setItemClickListener(ItemClickListener clickListener) {
onItemClickListener = clickListener;
}
and finally, add the following code inside the getview method to pass your adapter position to the listener.
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListener.onItemClick(p);
}
});
Now instead of GridView's OnItemClickListener(), use this interface to get the correct position. like this-
gridView.setAdapter(customAdopter);
customAdopter.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int position) {
Intent intent = new Intent(MainActivity.this, SwipeView.class);
intent.putExtra("id", position);
startActivity(intent);
}
});
I was going to provide you an alternative to this issue which is to use a recyclerview with gridLayoutManager and create a Custom layout that implements RecyclerView.Adapter....All of this might seem confusing to you I guess, so I quickly create a Unit Test to simulate what your code wants to achieve and below is the result.
public class ExampleUnitTest {
private static String data = null;
#Test
public void setParentData(){
data = "I set You";
Subclass subclass = new Subclass();
subclass.getParentData();
}
private static class Subclass{
void getParentData(){
assertEquals("I set You", data);
}
}
}
//Tests passed
I will take a minute to explain this, since you have your custom adapter as a subclass of MainActivity, then I believe that the subclass should have access to some values of its parent class.
I am talking about this: static int p; so you don't need to create two of that like you created in the subclass also which is the CustomAdopter class.
So below is the modification to your code and I believe it should work as far as the test passed, else, pls let me know so I can take a look again.
This is not really an answer but it's the only way I can share code and explain some things in details.
public class MainActivity extends Activity {
static Random random;
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
static int p;
// Some items to add to the GRID
static final String[] icons= {
"https://abhiandroid.com/ui/wp-content/uploads/2015/12/horizontalSpacing-in-Gridview.jpg",
"http://www.whatsappstatusmessages.com/wp-content/uploads/2017/01/whatsapp-dp-images-in-english.jpg",
"http://www.sarkarinaukrisearch.in/wp-content/uploads/2019/02/whatsapp-dp-status-in-english-1-77.jpg",
"https://www.trueshayari.in/wp-content/uploads/2018/07/Love-Status-DP-for-Couple.jpg",
"https://4.bp.blogspot.com/-2iawNx83Kpw/XL21pPj0aPI/AAAAAAAAKiE/VRR7pupbWDUj0TNNAKdGH8Baaz_c9IcSgCLcBGAs/s1600/ss.jpg",
"https://www.trueshayari.in/wp-content/uploads/2018/07/Love-Status-DP-for-Couple.jpg",
"https://3.bp.blogspot.com/-8us6YRiZEh0/XL21c6ibbXI/AAAAAAAAKh4/eNyjErq7q04YCeWxDPWojYfOoAC8BCodwCLcBGAs/s1600/s.jpg"
};
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.albumGrid);
random = new Random(); // or create a static random field...
p= random.nextInt(icons.length);
CustomAdopter customAdopter=new CustomAdopter();
gridView.setAdapter(customAdopter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SwipeView.class);
intent.putExtra("id", p);
startActivity(intent);
}
});
}
private static class CustomAdopter extends BaseAdapter {
#Override
public int getCount() {
return icons.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.layout.phototem, null);
ImageView imageView = view.findViewById(R.id.cover);
Picasso.get().load(icons[p]).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).into(imageView);
return view;
}
}

How to delete listview item in fragment?

I'm trying to delete an item from a listview, but there is a problem..i'm using a fragment and I don't know how to get the "delete image button" to add a onClickListener...
That's my xml of the delete button which is in payment_list_view.xml :
<ImageButton
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/trash_icon"
android:padding="10dp"
android:id="#+id/delete_payment_btn"
android:background="#android:color/white" />
Then, I have my PaymentFragment which contains my listview:
package com.nicola.baccillieri.splitpayment;
public class PaymentFragment extends Fragment {
private String descString;
private int price;
private String payedBy;
private ArrayList<String> descPayArray;
private ArrayList<Integer> priceArray;
private ArrayList<String> payedByArray;
int trash;
PaymentAdapter customAdapter;
private final static String SHARED_PREFS = "sharedPrefs";
FirebaseFirestore db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = FirebaseFirestore.getInstance();
trash = (R.drawable.trash_icon);
descPayArray = new ArrayList<>();
priceArray = new ArrayList<>();
payedByArray = new ArrayList<>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView=inflater.inflate(R.layout.payments_fragment,container,false);
ProgressBar detailsPb = rootView.findViewById(R.id.details_pb);
detailsPb.getIndeterminateDrawable().setColorFilter(0XFF3F51B5,
PorterDuff.Mode.MULTIPLY);
detailsPb.setVisibility(View.VISIBLE);
final ListView listView = rootView.findViewById(R.id.paymentLv);
String email = getEmail();
String groupName = getActivity().getIntent().getStringExtra("title");
DocumentReference docRef = db.collection("users").document(email).collection("Group").document(groupName);
docRef.collection("Payments")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (QueryDocumentSnapshot document : queryDocumentSnapshots) {
//Extracting payment description from each document
descString = document.getId();
descPayArray.add(descString);
//Extracting cost and who payed from each document
price = document.getLong("cost").intValue();
priceArray.add(price);
payedBy = document.getString("payed by");
payedByArray.add(payedBy);
trash = R.drawable.trash_icon;
customAdapter = new PaymentAdapter(getActivity(), descPayArray, payedByArray, priceArray, trash);
listView.setAdapter(customAdapter);
ProgressBar detailsPb = rootView.findViewById(R.id.details_pb);
detailsPb.setVisibility(View.GONE);
// That's the line that cause the error
ImageButton deleteBtn = rootView.findViewById(R.id.delete_payment_btn);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String groupName = getActivity().getIntent().getStringExtra("title");
int positionToRemove = (int) v.getTag();
String email = getEmail();
String paymentToRemove = descPayArray.get(positionToRemove);
DocumentReference docRef = db.collection("users").document(email).collection("Group").document(groupName).collection("Payments").document(paymentToRemove);
docRef.delete();
descPayArray.remove(positionToRemove);
customAdapter.notifyDataSetChanged();
}
});
}
// If there isn't any payment display a blank activity
ProgressBar detailsPb = rootView.findViewById(R.id.details_pb);
detailsPb.setVisibility(View.GONE);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
ProgressBar detailsPb = rootView.findViewById(R.id.details_pb);
detailsPb.setVisibility(View.GONE);
Toast.makeText(getContext(), "Failed to load payments", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
public String getEmail() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
String email = (sharedPreferences.getString("email", ""));
return email;
}}
and finally the file group_detail_activity.xml contains my 2 fragment with a tab layout.
Now, the app crash when It has to show the PaymentFragment, because ImageButton deleteBtn = rootView.findViewById(R.id.delete_payment_btn); says
`java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference".
That's because my rootView contains payment_fragment.xml, and not the payment_list_view.xml. So It doesn't find the button.
I've tryed to add final View rootListView=inflater.inflate(R.layout.payment_list_view,container,false);
and then it shows the list view, but when I click on the delete button, it doesn't do anything.
What should I do?
That's my PaymentAdapter:
package com.nicola.baccillieri.splitpayment;
public class PaymentAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> payDesc;
private ArrayList<String> payedBy;
private ArrayList<Integer> price;
private int trash;
LayoutInflater inflater;
public PaymentAdapter(Context context, ArrayList<String> payDesc, ArrayList<String> payedBy, ArrayList<Integer> price, int trash) {
this.context = context;
this.payDesc = payDesc;
this.payedBy = payedBy;
this.price = price;
this.trash = trash;
inflater = (LayoutInflater.from(context));
}
#Override
public int getCount() {
return payDesc.size();
}
#Override
public Object getItem(int position) {
return payDesc.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.payment_list_view, null);
TextView paymentDesc = convertView.findViewById(R.id.payedDescTv);
TextView payedByTv = convertView.findViewById(R.id.payedByTv);
TextView priceTv = convertView.findViewById(R.id.priceTv);
ImageButton trashIcon = convertView.findViewById(R.id.delete_payment_btn);
paymentDesc.setText(payDesc.get(position));
payedByTv.setText("Payed by " + payedBy.get(position));
priceTv.setText(String.valueOf(price.get(position)) + "€");
trashIcon.setImageResource(trash);
trashIcon.setTag(position);
return convertView;
}}
The problem is that I need to delete the item both from the listview and from firebase...so I need the getEmail() method e the getExtra which is in PaymentFragment..If i put the listener on the adapter, how can I delete o Firebase?
Try this way. On list clicked you can delete item
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
payedByArray.remove(position);
adapter.notifyItemRemoved(position);
}
});
Other way is to put the Delete Button in your payment_list_view and then in Adapter you can get position on that button click and delete it
From Custom_adapater's viewholder get the view id , and you can easily delete the item by using
payedByArray.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, payedByArray.size());
How to delete list item ,a SO's question already answered.. Have a look...
that might solve your problem.
You can set a listener to link the delete image button action to your fragment. Then can the button is click you trigger the listener and do what your want in your fragment. Yo can send the position to remove the good element
Your adapter don't know that list is being modified. you need to provide latest list to adapter after deletion of item.
Make your payedByArray list public in adapter code.
This activity code.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
payedByArray.remove(position);
//payedByArray is activity list;
adapter.payedByArray = payedByArray;
adapter.notifyItemRemoved(position);
}
});

How to hide and unhide a specific ListView item on switch preference on off?

I want to hide the 2nd option from the list on switch on off, I know how switch works, just tell me how to hide-unhide the option from the list. I want to hide list view item by item position or something like that.
New query : Is it possible to add two different adapter and switch them on switch preference change? if yes then how to do that?
This is 100% possible.
String [] titles = {"abc","def","ghi"};
String [] descriptions = {"abc","def","ghi"};
int [] images = {R.drawable.ic_abc,R.drawable.ic_def,R.drawable.ic_ghi};
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
lv = (ListView) findViewById(R.id.listView);
final Adapter adapter = new Adapter(getApplicationContext(), titles, descriptions, images);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
List view adapter
class Adapter extends ArrayAdapter {
int[] imageArray;
String[] titleArray;
String[] descriptionArray;
public Adapter(Context context, String[] titles1, String [] description1, int[] img1) {
super(context, R.layout.list_row, R.id.Titles, titles1);
this.imageArray = img1;
this.titleArray = titles1;
this.descriptionArray = description1;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_row,parent,false);
ImageView myImage = (ImageView) row.findViewById(R.id.Icons);
TextView myTitle = (TextView) row.findViewById(R.id.Titles);
TextView myDescription = (TextView) row.findViewById(R.id.Descriptions);
myImage.setImageResource(imageArray[position]);
myTitle.setText(titleArray[position]);
myDescription.setText(descriptionArray[position]);
return row;
}
}
Switch preference
public SwitchPreference sw;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_sw);
sw = (SwitchPreference) findPreference("001");
}
on switch on/off in main activity
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean sw = sharedPreferences.getBoolean("001", true);
if (sw) {
//hide list view item (only one)
} else {
//unhide list view item (only one)
}
Well, take a look, so you can call remove properly:
class Adapter extends ArrayAdapter {
List<ItemObject> data = new ArrayList();
public Adapter(Context context, String[] titles1, String [] description1, int[] img1) {
super(context, R.layout.list_row, R.id.Titles, titles1);
for(int i = 0; i < titles1.lenght; i++)
data.add(new ItemObject(titles1[i], description1[i], img1[i]);
}
static class ItemObject {
String title, description;
int image;
ItemObject(String ti, String desc, int img) {
title = ti;
description = desc;
image = img;
}
}
//plus the rest of your class
And change at getView
ItemObject row = data.get(position);
myImage.setImageResource(row.image);
myTitle.setText(row.title);
myDescription.setText(row.description);
And add this method in the adapter:
public void removeObject(int at) {
data.remove(at);
notifyDataSetChanged();
}
So you can call removeObject with a position.

I am trying to store the spinner data into SQLite database

I am trying to store the spinner data into SQLite database but in SQLite database cell android.widget.Spinner#411cf168 vale come
i.e value not fetch from spinner list. Please anyone help me i think my problem is in this line
ad1.insertquery(DatabaseDetail.getPAYMENT(), new String[]{ed_name.getText().toString(),ed_amount.getText().toString(),spin1.toString(),card_number.getText().toString(),ex_date.getText().toString()});
public class Payment_confirmation extends Activity implements OnItemSelectedListener
{
EditText ed_name,ed_amount,card_number,ex_date;
Button payment;
Spinner spin;
String[] accounttype = { "SBI MASTER CARD","SBI MAESTRO CARD","HDFC DEBIT/CREDIT CARD","BOB CREDIT CARD","INDIAN BANK CREDIT CARD"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.payment_confirmation);
ed_name=(EditText)findViewById(R.id.name);
ed_amount=(EditText)findViewById(R.id.amount);
card_number=(EditText)findViewById(R.id.crdnumber);
ex_date=(EditText)findViewById(R.id.date);
payment=(Button)findViewById(R.id.button2);
back = (Button)findViewById(R.id.button1);
spin=(Spinner)findViewById(R.id.spinner1);
spin.setOnItemSelectedListener(this);
ArrayAdapter aa= new ArrayAdapter(this,android.R.layout.simple_spinner_item, accounttype);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
payment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name=ed_name.getText().toString();
String amount=ed_amount.getText().toString();
String card=card_number.getText().toString();
String date=ex_date.getText().toString(); String spin1= spin.toString();
AdapterClass ad1 = new AdapterClass(getApplicationContext(), DatabaseDetail.PAYMENT);
ad1.Open();
ad1.insertquery(DatabaseDetail.getPAYMENT(), new String[]{ed_name.getText().toString(),ed_amount.getText().toString(),spin1.toString(),card_number.getText().toString(),ex_date.getText().toString()});
Cursor lCursor1 = ad1.fetchRecords(new String[]{"CUS_NAME","AMOUNT","CARD_NAME","CARD_NUMBER","EX_DATE"},null);
startManagingCursor(lCursor1);
lCursor1.moveToFirst();
if(lCursor1.getCount()!=0)
{
Intent i = new Intent(getApplicationContext(),Thankpayment.class);
startActivity(i);
}
ad1.close();
finish();
}
});
}
}
Try this way:
Spinner spinner1 = (Spinner) findViewById(R.id.spin1);
ArrayAdapter aa= new ArrayAdapter(this,android.R.layout.simple_spinner_item, accounttype);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(aa);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Object item = parent.getItemAtPosition(pos);
String spin_value = item.toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Replace
spin1.toString()
--- As it will return the spinner object reference as string like you are getting android.widget.Spinner#411cf168
With
spin1.getSelectedItem().toString() -- As it will return the spinner object's content i.e selected item as string..
When you do this:
public class SpinnerActivity extends Activity implements OnItemSelectedListener
You dont really have to write
spin.setAdapter(aa);
Just override the following methods in your class
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}

How to select spinning values from listview?

I'm facing some issue with getting spinning values from list view.. in list view i have textview and related to spinner to it..
this is my Result.java
public class Result extends ListActivity{
SpinnerWrapper wrapper=new SpinnerWrapper();
Spinner sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
MyAdapter adap=new MyAdapter(this, android.R.layout.simple_list_item_1,R.id.textView1, getResources().getStringArray(R.array.modules));
adap.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
setListAdapter(adap);
Button b=(Button) findViewById(R.id.button12);
//final Spinner sp=(Spinner) findViewById(R.id.spinner1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(Result.this,Cal.class);
for(int i=0;i<15;i++){
//String text= sp1.getSelectedItem().toString();
//Log.d("This", text);
}
//Spinner sp1=og.getSp();
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(Result.this, R.array.grades, android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(wrapper);
intent.putExtra("values", sp.getSelectedItem().toString());
//intent.putExtra("values", sp.setOnItemSelectedListener(wrapper));
startActivity(intent);
}
});
}
public void getObject(Spinner sp){
this.sp=sp;
}
private class MyAdapter extends ArrayAdapter<String>{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] strings) {
super(context, resource, textViewResourceId, strings);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.item_layout, parent,false);
String[] items=getResources().getStringArray(R.array.modules);
TextView tv=(TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
Spinner sp=(Spinner)row.findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(Result.this, R.array.grades, android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
getObject(sp);
//og.setSp(sp);
//sp.setOnItemSelectedListener(wrapper);
//int dd=row.getId();
return row;
}
}
}
My Spinner Wrapper class is looks like this..
public class SpinnerWrapper implements OnItemSelectedListener {
public SpinnerWrapper() {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
String text=parent.getSelectedItem().toString();
int intee=parent.getSelectedItemPosition();
String pos=Integer.toString(intee);
String tex=parent.getItemAtPosition(position).toString();
Log.d("Selected", text);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
I want to get spinning value of each spinner ..how can i do that??
//sp.setOnItemSelectedListener(wrapper);
I see your code is commented. so the OnItemSelectedListener is not called.
You call different listener for different spinner.
I don't see why you can't get the value by
String tex=parent.getItemAtPosition(position).toString();
Log.d("You have selected", tex);
You can create an ArrayList<String> and add the selected value to that ArrayList. It will be something like this.
static ArrayList<String> sth = new ArrayList<String>();
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(
parent.getContext(),
"OnItemSelectedListener : "
+ parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
for (int i = 0; i < parent.getItemIdAtPosition(pos); i++) {
sth.add(parent.getItemAtPosition(pos).toString());
}
Log.w(getClass().getSimpleName(), "sth size " + sth.size());
}
You can pass that ArrayList around since the selected values are stored.

Categories

Resources