Android ListView with Spinner and get its value - android

I am trying to create a List which has a TextView and a Spinner. The data for TextView and Spinner comes from array or JSON. I have the following files:
main Activity:
public class ListViewTestActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String coba="tes";
ListView listView = (ListView) findViewById(R.id.listView1);
DataHolder data = new DataHolder(this);
DataHolder data1 = new DataHolder(this);
DataHolder data2 = new DataHolder(this);
DataHolder data3 = new DataHolder(this);
DataHolder data4 = new DataHolder(this);
DataHolder data5 = new DataHolder(this);
DataAdapter d = new DataAdapter(this, R.layout.rowview, new DataHolder[] { data, data1, data2, data3, data4, data5 });
listView.setAdapter(d);
}
}
DataHolder class:
public class DataHolder {
private int selected;
private String name;
private ArrayAdapter<CharSequence> adapter;
String[] count={"0","1","2","3","4","5","6","7","8","9","10"};
public DataHolder(Context parent) {
//adapter = ArrayAdapter.createFromResource(parent, R.array.choices , android.R.layout.simple_spinner_item);
//adapter= new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,count);
//this.name="tes";
adapter = new ArrayAdapter<CharSequence>(parent, android.R.layout.simple_spinner_item, count);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayAdapter<CharSequence> getAdapter() {
return adapter;
}
public String getText() {
return (String) adapter.getItem(selected);
}
public int getSelected() {
return selected;
}
public void setSelected(int selected) {
this.selected = selected;
}
}
DataAdapter class:
public class DataAdapter extends ArrayAdapter<DataHolder> {
private Activity myContext;
String tes="makanan";
public DataAdapter(Activity context, int textViewResourceId, DataHolder[] objects) {
super(context, textViewResourceId, objects);
myContext = context;
}
// We keep this ViewHolder object to save time. It's quicker than findViewById() when repainting.
static class ViewHolder {
protected DataHolder data;
protected TextView text;
protected Spinner spin;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
// Check to see if this row has already been painted once.
if (convertView == null) {
// If it hasn't, set up everything:
LayoutInflater inflator = myContext.getLayoutInflater();
view = inflator.inflate(R.layout.rowview, null);
// Make a new ViewHolder for this row, and modify its data and spinner:
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.text);
viewHolder.data = new DataHolder(myContext);
viewHolder.spin = (Spinner) view.findViewById(R.id.spin);
viewHolder.spin.setAdapter(viewHolder.data.getAdapter());
// Used to handle events when the user changes the Spinner selection:
viewHolder.spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
viewHolder.data.setSelected(arg2);
viewHolder.text.setText(viewHolder.data.getText());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// Update the TextView to reflect what's in the Spinner
viewHolder.text.setText(tes);
view.setTag(viewHolder);
Log.d("DBGINF", viewHolder.text.getText() + "");
} else {
view = convertView;
}
// This is what gets called every time the ListView refreshes
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(getItem(position).getText());
holder.spin.setSelection(getItem(position).getSelected());
return view;
}
}
main .xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="#+id/listView1"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</LinearLayout>
rowview.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content" android:weightSum="1">
<TextView android:layout_width="wrap_content"
android:layout_height="match_parent" android:id="#+id/text"
android:layout_weight="0.5" android:textSize="25sp" />
<Spinner android:layout_width="0dp" android:layout_height="wrap_content"
android:id="#+id/spin"
android:prompt="#string/choice_prompt"
android:layout_weight="0.5" />
</LinearLayout>
My problem is I can't change the TextView with data of array, and get value of that Spinner and TextView. How do I do this?

Related

Added items to cart list

I have created an android application. in that application when I click on add, item added to the array list and this array list I want to show in Cart Activity. how to do that.
here is my activity1
public void addShirt(View view) {
MainActivity.cartItems.add(getString(R.string.shirt));
}
public void addPant(View view) {
MainActivity.cartItems.add(getString(R.string.pant));
}
public void view(View view) {
Intent i =new Intent(OnlyIron.this,CartActivity.class);
startActivity(i);
}
and cart activity is
for(int i=0; i<MainActivity.cartItems.size();i++) {
Toast.makeText(this, "item : " + MainActivity.cartItems.get(i), Toast.LENGTH_SHORT).show();
}
it showing toast but I enter code here want this show in listview
First lets Create model class and store data in it.
public class Cart {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now to add items in that list i would call it this way :
private ArrayList<Cart > cart_array;
cart_array= new ArrayList<>();
Cart cart1 = new Cart ();
cart.setId("1");
cart.setName("first product");
Cart cart2 = new Cart ();
cart.setId("2");
cart.setName("first product");
Cart cart3 = new Cart ();
cart.setId("3");
cart.setName("first product");
//and than add your model into array
cart_array.add(cart1);
cart_array.add(cart2);
cart_array.add(cart3);
//and finaly set your adapter
Cart_Adapter adapter = new Cart_Adapter(cart_array, getActivity());
Recycler.setAdapter(adapter );
Please take a list view in CartActivity & create an Custom Adapter as according to your need(UI). Pass the MainActivity.cartItems this list to Adapter. It will start to show in your CartActivity.
You can see below example:
public class CustomAdapter extends BaseAdapter{
Activity mContext;
public ArrayList<String> mCartList = new ArrayList<String>();
private LayoutInflater mInflater=null;
public CustomAdapter(Activity activty, ArrayList<String> list)
{
this.mContext = activty;
mInflater = activty.getLayoutInflater();
this.mCartList=list;
}
#Override
public int getCount() {
if (mCartList != null){
return mCartList.size();
} else{
return 0;
}
}
#Override
public String getItem(int arg0) {
return mCartList.get(arg0);
}
#Override
public long getItemId(int index) {
return index;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
final ViewHolder holder;
if (convertView == null ) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_layout, null);
holder.mItemNameTV= (TextView) convertView.findViewById(R.id.itemtv);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.mNameTV.setText(mCartList.get(position));
return convertView;
}
private static class ViewHolder {
TextView mNameTV;
}
}
// Item Layout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/forty_dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/fieldTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/five_dp"
android:layout_weight="0.4"
android:padding="#dimen/ten_dp"
android:text="Custom Field"
android:textColor="#color/dark_gray_color"
android:textSize="#dimen/normal_font_size"
android:visibility="visible" />
</LinearLayout>
// Let Suppose your CartActivity is following:
ListView mListView = (ListView)findViewById(R.id.listview);
CustomAdapter adapter = new CustomAdapter(this, MainActivity.cartItems);
mListView.setAdapter(adapter);

What to put in the fab to create cardviews - recyclerviews, adapter

I have been following this tutorial right through with a few minor adjustments for my own use: Android RecyclerView and CardView Tutorial
(The point of my app is when you press the fab, a cardview appears. Inside each cardview is a spinner, edittext, textview and checkbox.)
However I need to finally add some code into the FAB so that a cardview is added. But I am unsure how to do this with all I have done with adapters. the tutorial asked me to do productList = new ArrayList<>(); and so I could use productList.add but I don't know how to go on from there.
Here is the snippet of my main activity code:
FloatingActionButton floatingActionButton =(FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
productList.add //what goes here???//
}
});
And this is my current create.java code (which the above snippet is in)
public class create extends AppCompatActivity {
//a list to store all the products
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
//opens csv
InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
CSVFile csvFile = new CSVFile(inputStream);
Product.spinnerItemsList = csvFile.read();
//getting the recyclerview from xml
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
//TODO FAB BUTTON
FloatingActionButton floatingActionButton =
(FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
productList.add //what goes here???//
}
});
//creating recyclerview adapter
ProductAdapter adapter = new ProductAdapter(this, productList);
//setting adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream) {
this.inputStream = inputStream;
}
public List<String> read() {
List<String> resultList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
//TODO I edited this part so that you'd add the values in our new hash map variable
/*
numberItemValues.put(row[1], row[0]);
*/
resultList.add(row[1]);
}
} catch (IOException e) {
Log.e("Main", e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Main", e.getMessage());
}
}
return resultList;
}
}
}
This is MyListAdapter.java which is for the Spinner.
public class MyListAdapter extends ArrayAdapter<String> {
int groupid;
List<String> items;
Context context;
String path;
public MyListAdapter(Context context, int vg, int id, List<String> items) {
super(context, vg, id, items);
this.context = context;
groupid = vg;
this.items = items;
}
static class ViewHolder {
public TextView textid;
public TextView textname;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
{
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(groupid, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.textid = (TextView) rowView.findViewById(R.id.txtid);
viewHolder.textname = (TextView) rowView.findViewById(R.id.txtname);
rowView.setTag(viewHolder);
}
// Fill data in the drop down.
ViewHolder holder = (ViewHolder) rowView.getTag();
String row = items.get(position);
//holder.textid.setText(row[0]); //prints aisle number, dont need
holder.textname.setText(row);
return rowView;
}
}
}
This is Product.Java from tutorial
public class Product {
private String editText;
private Boolean checkBox;
private String textView5;
public static List<String> spinnerItemsList = new ArrayList<String>();
public Product(List spinner, String editText, Boolean checkBox, String textView5) {
this.editText = editText;
this.checkBox = checkBox;
this.textView5 = textView5;
}
public String getEdittext () {
return editText;
}
public boolean getCheckbox () {
return checkBox;
}
public String getTextview () {
return textView5;
}
}
And this is ProductAdapter.java also from tutorial
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
//this context we will use to inflate the layout
private Context mCtx;
private Spinner spinner;
//we are storing all the products in a list
private List<Product> productList;
//getting the context and product list with constructor
public ProductAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.layout_products, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
//getting the product of the specified position
Product product = productList.get(position);
//binding the data with the viewholder views
MyListAdapter adapter = new MyListAdapter(mCtx, R.layout.listrow, R.id.txtid, Product.spinnerItemsList);
spinner.setAdapter(adapter);
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
Spinner spinner;
EditText editText;
TextView textView5;
CheckBox checkBox;
public ProductViewHolder(View itemView) {
super(itemView);
spinner = itemView.findViewById(R.id.spinner);
editText = itemView.findViewById(R.id.editText);
textView5 = itemView.findViewById(R.id.textView5);
checkBox = itemView.findViewById(R.id.checkBox);
}
}
}
I've done the same xml stuff as the tutorial fyi.
EDIT
final Spinner spinner;
final EditText editText;
final CheckBox checkBox;
final TextView textView5;
spinner = findViewById(R.id.spinner);
editText = findViewById(R.id.editText);
checkBox = findViewById(R.id.checkBox);
textView5 = findViewById(R.id.textView5);
final ProductAdapter adapter = new ProductAdapter(this, productList);
//TODO FAB BUTTON
FloatingActionButton floatingActionButton =
(FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Product mProduct = new Product(List spinner, String editText, Boolean checkBox, String textView5);
productList.add(mProduct); //what goes here???//
if(adapter != null)
adapter.notifyDataSetChanged();
//Handle the empty adapter here
}
});
layout_products.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<Spinner
android:id="#+id/spinner"
android:layout_width="159dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="36dp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="89dp"
android:text="TextView" />
<EditText
android:id="#+id/editText"
android:layout_width="34dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="number" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Change your Product Model with the following
public class Product {
private String editText;
private Boolean checkBox;
private String textView5;
// The following list is useless unless u don't use it somewhere so lets create getters and setters for this item
private List<String> spinnerItemsList = new ArrayList<String>();
public Product(List spinner, String editText, Boolean checkBox, String textView5) {
this.editText = editText;
this.spinnerItemsList = spinner;
this.checkBox = checkBox;
this.textView5 = textView5;
}
public String getEdittext () {
return editText;
}
public boolean getCheckbox () {
return checkBox;
}
public String getTextview () {
return textView5;
}
public String getSpinnerItemsList () {
return spinnerItemsList;
}
}
Well I think you just need to add a dummy object in your array list and then just call notifyDataSetChanged()
//Step 1 reposition your adapter
ProductAdapter adapter = new ProductAdapter(this, productList);
//TODO FAB BUTTON
FloatingActionButton floatingActionButton =
(FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//The problem is in the following line you need to pass the values but what you are doing is incorrect
//Product mProduct = new Product(List spinner, String editText, Boolean checkBox, String textView5);
//So replace the above line with the following code
ArrayList<String> spinnerItem = new ArrayList<String>();
spinnerItem.add("StackOverFlow");
//There are better and efficient ways to achieve this, If you explain what do you want exaclty I might be able to help
Product mProduct = new Product(spinnerItem, "EditText Value", true, "TextView Value");
productList.add(mProduct); //what goes here???//
if(adapter != null)
adapter.notifyDataSetChanged();
else
//Handle the empty adapter here
}
});
I guess now with the above code you are good to go!
UPDATE Try changing the following code block inside ProductAdapter.java
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
//getting the product of the specified position
Product product = productList.get(position);
//binding the data with the viewholder views
//MyListAdapter adapter = new MyListAdapter(mCtx, R.layout.listrow, R.id.txtid, Product.spinnerItemsList);
//spinner.setAdapter(adapter);
//Try using Simple ArrayAdapter if all you need to display is one text
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String> (mCtx, android.R.layout.simple_spinner_item, Product.getSpinnerItemsList());
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
}
productList is a list of products. You must supply an object of type product when doing `productList.add().
example:
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Product p = new Product(...)
productList.add(p);
ProductAdapter adapter = new ProductAdapter(this, productList);
//setting adapter to recyclerview
recyclerView.setAdapter(adapter);
}
});
p.s: The first argument in the constructor of Product is useless as you aren't using it anywhere.
There are better ways of implementing this tho.

ListView is not showing data

i am create a list view for audio files there is listView is not showing data
only showing images 3 time not showing a audio i dont know where i am doing wrong please help me...
ListActivity
public class MainActivity extends Activity {
Cursor c;
int index;
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.audio_list);
String cols[] = {MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA
};
c = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cols, null, null, null);
String imagePath = Environment.getExternalStorageDirectory() + "/audio/recording.3gp`";
File f=new File(imagePath);
Uri uri = Uri.fromFile(f);
List<String> data = new ArrayList<String>();
for (int i = 0; i < c.getColumnCount(); i++){
data.add(String.valueOf(f));
}
CustomAdapter customAdapter = new CustomAdapter(this,data);
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
}
Adapter
public class CustomAdapter extends BaseAdapter {
private final Context context;
private final List<String> items;
private final Map<View, Map<Integer, View>>
cache = new HashMap<View, Map<Integer, View>>();
public CustomAdapter(Context context, List<String> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return getItem(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView tv;
ImageView iv;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.item, parent, false);
}
Map<Integer, View> itemMap = cache.get(v);
if (itemMap == null) {
itemMap = new HashMap<Integer, View>();
tv = (TextView) v.findViewById(android.R.id.text1);
iv = (ImageView) v.findViewById(R.id.imageView);
itemMap.put(android.R.id.text1, tv);
itemMap.put(R.id.imageView, iv);
cache.put(v, itemMap);
} else {
tv = (TextView) itemMap.get(android.R.id.text1);
iv = (ImageView) itemMap.get(R.id.imageView);
}
final String item = (String) getItem(position);
tv.setText(item);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,
String.format("Image clicked: %s", item),
Toast.LENGTH_SHORT).show();
}
});
return v;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:layout_height="wrap_content"
android:id="#android:id/list"
android:layout_width="match_parent" />
itm.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical">
<TextView
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:id="#android:id/text1"
android:layout_height="wrap_content"
android:layout_weight="1" />
<ImageView android:src="#mipmap/ic_launcher"
android:layout_width="wrap_content"
android:id="#+id/imageView"
android:layout_height="wrap_content"
android:clickable="true" />
You have not initialize any data to List "data"
You have to initialize data inside the for loop.
List<String> data = new ArrayList<String>();
for (int i = 0; i < c.getColumnCount(); i++){
}
CustomAdapter customAdapter = new CustomAdapter(this,data);
Edit:
Replace the for loop with the code bellow
if (c!=null && c.moveToFirst()) {
do{
String audio_name_with_path = c.getString(2).toString();
data.add(audio_name_with_path);
}while(c.moveToNext());
}

selected item of listview remain at same position after notifyDataSetChanged

I implemented a simple listview with an option to select each time only one item from it, this functionality is working properly.
Also I have a button for sorting the records in Asc or Desc order, when I am selecting a record and after that I am sorting the records the selector of the old record remains in the same old position, even when the selected position is updated different position.
MainActivity:
public class MainActivity extends Activity
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("abc", "defg", 1));
_data.add(new Person("aaa", "defg", 12));
_data.add(new Person("ccc", "defg", 13));
_data.add(new Person("bb", "defg", 14));
_data.add(new Person("aa", "defg", 144));
_data.add(new Person("fff", "defg", 199));
_adapter = new PersonAdapter(this, _data);
_listView.setAdapter(_adapter);
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
});
}
public static class Person
{
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String fName, String lName, int age)
{
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
}
listView adapter
public class PersonAdapter extends BaseAdapter
{
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
}
}
item layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_layout"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#drawable/list_selector"
android:weightSum="3" >
<TextView
android:id="#+id/f_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<TextView
android:id="#+id/l_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<TextView
android:id="#+id/age"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
I tried already to use clearChoices but after sorting I do not see the selector at all, also I tried to change the choise mode from single mode to none and then again single but without any success.
It is because you are switching the contents of the items inside the list item, but the click is bound to the position withing the ListView, therefore it doesn't "update" to the new position of the item.
I suggest you to programatically click on the new item when you finish the sorting.
Get the ID of the clicked item
public int getItemPosition(long id)
{
for (int position=0; position<mList.size(); position++)
if (mList.get(position).getId() == id)
return position;
return 0;
}
then after the sorting do the click
mList.performItemClick(
mList.getAdapter().getView(mActivePosition, null, null),
mActivePosition,
mList.getAdapter().getItemId(mActivePosition));
hope it helps!
I suggest to store the id of the selected item when it is selected, and after order the dataset, search for that id and re-select it.

Load data from SQLite in Spinner

I'm trying to load my employees names from my SQL to my spinner but instead this is what I get:
As you can see, my app's directory is getting loaded instead and I have no idea why.
My activity:
public class AddAbsenceForm extends Activity implements OnItemSelectedListener {
Spinner spinner;
Button buttonAdd;
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_absence_form);
//spinner element
spinner = (Spinner) findViewById(R.id.names_spinner);
//spinner click listener
spinner.setOnItemSelectedListener(this);
//loading spinner data from database
loadSpinnerData();
}
private void loadSpinnerData() {
//database handler
LysandrosDatabaseAdapter db = new LysandrosDatabaseAdapter(getApplicationContext());
//spinner drop down elements
List<DataBean> list = db.getAllDat();
//creating adapter for spinner
ArrayAdapter<DataBean > dataAdapter = new ArrayAdapter<DataBean>(this, android.R.layout.simple_spinner_dropdown_item, list);
//drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String list = parent.getItemAtPosition(position).toString();
//showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + list, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Database method:
public List <DataBean> getAllDat(){
List<DataBean> list = new ArrayList<>();
SQLiteDatabase db = helper.getReadableDatabase();
String [] columns = {LysandrosHelper.UID, LysandrosHelper.NAME, LysandrosHelper.SURNAME, LysandrosHelper.DEPARTMENT, LysandrosHelper.WORKPLACE};
Cursor cursor = db.query(LysandrosHelper.TABLE_NAME, columns, null, null, null, null, null);
while (cursor.moveToNext()) {
int index = cursor.getColumnIndex(LysandrosHelper.UID);
int index2 = cursor.getColumnIndex(LysandrosHelper.NAME);
int index3 = cursor.getColumnIndex(LysandrosHelper.SURNAME);
int index4 = cursor.getColumnIndex(LysandrosHelper.DEPARTMENT);
int index5 = cursor.getColumnIndex(LysandrosHelper.WORKPLACE);
int cid = cursor.getInt(index);
String persoName = cursor.getString(index2);
String personSurname = cursor.getString(index3);
String personDepartment = cursor.getString(index4);
String personWorkplace = cursor.getString(index5);
DataBean bean = new DataBean(cid, persoName, personSurname, personDepartment, personWorkplace);
list.add(bean);
}
return list;
}
Spinner in XML:
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/names_spinner"
android:text="#string/select_employee">
</Spinner>
Please somebody tell me what I'm missing
EDIT:
My DataBean class:
public class DataBean {
protected int id;
protected String name;
protected String surname;
protected String department;
protected String workplace;
public DataBean() {
}
public DataBean (int id, String name, String surname, String department, String workplace ) {
this.id = id;
this.name = name;
this.surname = surname;
this.department = department;
this.workplace = workplace;
}
public DataBean (String name, String surname, String department, String workplace) {
this.name = name;
this.surname = surname;
this.department = department;
this.workplace = workplace;
}
public int getID() {
return this.id;
}
public String getName() {
return this. name;
}
public String getSurname() {
return this.surname;
}
public String getDepartment() {
return this.department;
}
public String getWorkplace() {
return this.workplace;
}
}
EDIT 2: My layout changed to this..
replace your loadSpinnerData() method with this if you want to display only name otherwise go for Custome Adapter
private void loadSpinnerData() {
//database handler
LysandrosDatabaseAdapter db = new LysandrosDatabaseAdapter(getApplicationContext());
//spinner drop down elements
List<DataBean> list = db.getAllDat();
//creating adapter for spinner
String[] nameList=new String[list.size()];
for(int i=0;i<list.size();i++){
nameList[i]=list.get(i).getName(); //create array of name
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, nameList);
//drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
Create Custom Adapter that extends ArrayAdapter.
public class MyAdapter extends ArrayAdapter<DataBean>{
Context context;
int layoutResourceId;
ArrayList<DataBean> data;
public MyAdapter(Context context, int layoutResourceId, ArrayList<DataBean> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.persoName = (TextView)row.findViewById(R.id.persoName);
row.setTag(holder);
}
else
{
holder = (ViewHolder)row.getTag();
}
holder.persoName.setText(list.get(position).getName());
return row;
}
static class ViewHolder
{
TextView persoName;
}
}
Here is xml file for spinner list item.
spinner_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp" >
<TextView
android:id="#+id/persoName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_weight="70"
android:text="Name"
android:textColor="#000000"
android:textSize="22sp"
android:textStyle="bold" />
</LinearLayout>
Here i have given example of only one data string.
then use it like this.
private void loadSpinnerData() {
//database handler
LysandrosDatabaseAdapter db = new LysandrosDatabaseAdapter(getApplicationContext());
//spinner drop down elements
ArrayList<DataBean> list = db.getAllDat();
//creating adapter for spinner
MyAdapter<DataBean > dataAdapter = new MyAdapter<DataBean>(this, R.layout.spinner_list_item, list);
//drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
You can refer this link to check how to use Custom Adapter.
You can also simply override the toString method of your DataBean class and return the text you want to display in the Spinner.

Categories

Resources