How to fill with my own strings - android

I have implementing a tutorial and I have a problem to adapt to my way.
The main.xml with de ListView
<?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>
The 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>
The strings.xml file.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, ListViewTestActivity!</string>
<string name="app_name">ListViewTest</string>
<string name="choice_prompt">Select a choice</string>
<string-array name="choices">
<item>Alpha</item>
<item>Bravo</item>
<item>Charlie</item>
</string-array>
</resources>
The ListViewActivity class:
public class ListViewTestActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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);
DataAdapter d = new DataAdapter(this, R.layout.rowview, new DataHolder[] { data, data1, data2, data3, data4 });
listView.setAdapter(d);
}
}
The DataHolder class:
public class DataHolder {
private int selected;
private ArrayAdapter<CharSequence> adapter;
public DataHolder(Context parent) {
adapter = ArrayAdapter.createFromResource(parent, R.array.choices, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
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;
}
}
All the DataHolder class :
public class DataAdapter extends ArrayAdapter<DataHolder> {
private Activity myContext;
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(viewHolder.data.getText());
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;
}
}
To see the result of this code, see -> Android Listview with spinner and a checkbox
This code works, I have a listView with a spinner for each item, but how I can fill spinners with my own Strings? I tryed to fill them in the DataHolder class but it fails. (I have a list of Strings).
Thank's in advance.

All the work is done in the ADAPTER here your DataAdapter.
The cells are constructed in the method GetView, each cells is recycled : if convertView is null you create a new cell to use or else you use convertView.
i assume you must change some code in your DataHolder
public DataHolder(Context parent) {
adapter = ArrayAdapter.createFromResource(parent, R.array.choices, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
For now you must understand that the array of choices is provided statically :
R.array.choices
One solution would be to pass your data when constructing the viewHolders here :
viewHolder.data = new DataHolder(myContext);
should looks like something like this :
viewHolder.data = new DataHolder(myContext, myDataArray);
and then in your class change the instanciation of the adapter with something more like that..
public DataHolder(Context parent, ArrayList<String> dataArray) {
adapter = new ArrayAdapter<String>(myContext, yourTextViewId, dataArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
hopes it help
good luck

Related

How to display checkbox on every entry in a listView

From this Activity i get text from textField and display it in a ListView.
Now i want to to add check box on every entry in a listView Cell and also like to know how to display more than one text in a single ListView Cell.
Help with code will be appreciated.
Here is my code ....
public class AfterRegister extends AppCompatActivity
{
ListView listView;
EditText editText;
Button insertItemButton;
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> adapter;
CheckBox checkBox;
StoreRegistrationDataBase storeRegistrationDataBase;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_register);
storeRegistrationDataBase = new StoreRegistrationDataBase(this);
storeRegistrationDataBase = storeRegistrationDataBase.open();
checkBox = (CheckBox) findViewById(R.id.checkbox);
insertItemButton = (Button) findViewById(R.id.button4);
insertItemButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
editText = (EditText) findViewById(R.id.editText2);
listView = (ListView) findViewById(R.id.listView);
String getEditTextString = editText.getText().toString();
if(isAlphaNumeric(getEditTextString))
{
if(!getEditTextString.equals(""))
{
arrayList.add(getEditTextString);
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.text_view_layout, R.id.achView1, arrayList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
editText.setText("");
}
else
{
Toast.makeText(AfterRegister.this, "You can not insert empty field", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(AfterRegister.this, "Remove Space", Toast.LENGTH_SHORT).show();
}
}
});
listView.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return false;
}
});
}
public boolean isAlphaNumeric(String s)
{
String pattern= "^[a-zA-Z0-9]*$";
if(s.matches(pattern))
{
return true;
}
return false;
}
}
You have to use a BaseAdapter and some Getter/Setter methods to add multiple texts/images/other UI elements in each item of your list view.
You have to implement multiple things to get this result. Here they are --
Create a Custom Layout for each item of your ListView.
listview_item_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/layout_textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginRight="5dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/layout_textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginLeft="5dip"
android:textStyle="bold"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkbox"
android:text="Test"/>
</LinearLayout>
Create a custom class and add some Getter/Setter methods.
ListRowItem.java
public class ListRowItem implements Serializable{
String carrier,number;
public String getCarrier(){
return carrier;
}
public String getNumber(){
return number;
}
public void setCarrier(String ba_carrier){
carrier = ba_carrier;
}
public void setNumber(String ba_number){
number = ba_number;
}
}
Create a custom class and extend the BaseAdapter class.
public class MyBaseAdapter extends BaseAdapter {
public Context ba_context;
public ArrayList<ListRowItem> listitem = new ArrayList<>();
public LayoutInflater inflater;
ListRowItem currentlistitem;
public MyBaseAdapter(Context ma_context, ArrayList<ListRowItem> ma_listitem) {
super();
this.ba_context = ma_context;
this.listitem = ma_listitem;
inflater = (LayoutInflater) ba_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.listitem.size();
}
#Override
public Object getItem(int position) {
return this.listitem.get(position);
}
#Override
public long getItemId(int position) {
return (long) position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listview_item_layout, parent, false);
TextView carrier = (TextView) vi.findViewById(R.id.layout_textview1);
TextView number = (TextView) vi.findViewById(R.id.layout_textview2);
currentlistitem = listitem.get(position);
String str_carrier = currentlistitem.getCarrier();
String str_number = currentlistitem.getNumber();
carrier.setText(str_carrier);
number.setText(str_number);
return vi;
}
}
Finally, populate your ArrayList and set the Adapter in your MainActivity.
ArrayList<ListRowItem> listitem = new ArrayList<>();
Context context = TestActivity.this;
MyBaseAdapter baseAdapter;
ListRowItem lr = new ListRowItem();
lr.setNumber(number);
lr.setCarrier(carrier);
listitem.add(lr);
baseAdapter = new MyBaseAdapter(context,listitem);
setContentView(R.layout.activity_test);
listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(baseAdapter);
Hope this helps!!

ListView, Change each row with Array of color codes in Android

I'm trying to change the color of each row, I have 2 arrays. One has names of color, the other has color codes.
I have a ListView with Color names, the names are stored in an array of String.
String[] colourNames;
String[] colourCodes;
protected void onCreate(Bundle savedInstanceState) {
colourNames = getResources().getStringArray(R.array.listArray);
colourCodes = getResources().getStringArray(R.array.listValues);
ListView lv = (ListView) findViewById(R.id.listView);
ArrayAdapter aa = new ArrayAdapter(this, R.layout.activity_listview, colourNames);
lv.setAdapter(aa);
for(int i=0; i<colourCodes.length; i++)
lv.getChildAt(i).setBackgroundColor(Color.parseColor(colourCodes[i]));
}
In arrays.xml:
<string-array name="listArray">
<item>aliceblue</item>
<item>antiquewhite</item>
<item>aquamarine</item>
<item>azure</item>
</string-array>
<string-array name="listValues">
<item>00f0f8ff</item>
<item>00faebd7</item>
<item>007fffd4</item>
<item>00f0ffff</item>
</string-array>
The app crashes at lv.getChildAt(i).setBackgroundColor(Color.parseColor(colourCodes[i]));
You must write your own custom ArrayAdapter.
First write a color class:
color.java:
public class color {
private String name;
private String color;
public color(String name, String color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
Then List item layout:
list_item_layout.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Finally write custom adapter:
ColorListAdapter.java:
public class ColorListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<color> mColorList;
public ColorListAdapter(Activity activity, List<color> mColorList) {
mInflater = (LayoutInflater) activity.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
this.mColorList = mColorList;
}
#Override
public int getCount() {
return mColorList.size();
}
#Override
public Object getItem(int position) {
return mColorList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
// Get item_layout:
rowView = mInflater.inflate(R.layout.list_item_layout, null);
// Get TextView from item_layout:
TextView textView =
(TextView) rowView.findViewById(R.id.name);
// Get color and text from current position set TextView
color myColor = mColorList.get(position);
textView.setText(myColor.getName());
textView.setBackgroundColor(Color.parseColor(myColor.getColor()));
return rowView;
}
}
And these are MainActivity.java and activity_main.xml
MainActivity.java:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<color> colorList = new ArrayList<>();
// Add color objects:
colorList.add(new color("RED", "#FF0000"));
colorList.add(new color("GREEN", "#00FF00"));
colorList.add(new color("BLUE", "#0000FF"));
colorList.add(new color("MY BEST", "#013583"));
// Add list to your custom adapter
ListView myListView = (ListView) findViewById(R.id.liste);
ColorListAdapter mAdapter = new ColorListAdapter(this, colorList);
// Set Adapter
myListView.setAdapter(mAdapter);
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/liste"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</RelativeLayout>
Try this code
String[] colourNames;
String[] colourCodes;
protected void onCreate(Bundle savedInstanceState) {
colourNames = getResources().getStringArray(R.array.listArray);
colourCodes = getResources().getStringArray(R.array.listValues);
ListView lv = (ListView) findViewById(R.id.listView);
ArrayAdapter aa = new ArrayAdapter(this, R.layout.activity_listview, colourNames);
lv.setAdapter(aa);
for(int i=0; i<colourCodes.length; i++){
View wantedView = lv.getChildAt(i);
view.setBackgroundColor(Color.BLUE);
}
}
The problem is at this point ListView does not have any children. If you want to alter how children are displayed, you need create your own Adapter implementation and override getView(). You can simply subclass ArrayAdapter in this case and pass it your array of colors (or have it load the colors in the adapter, as I have done), then choose a color based on position.
Also, you might as well make your colors an integer array.
<integer-array name="listValues">
<item>0xfff0f8ff</item>
<item>0xfffaebd7</item>
<item>0xff7fffd4</item>
<item>0xfff0ffff</item>
</integer-array>
public class ColorsAdapter extends ArrayAdapter<String> {
private int[] mColors;
public ColorsAdapter(Context context) {
super(context, R.layout.activity_listview,
context.getResources().getStringArray(R.array.listArray));
mColors = context.getResources().getIntegerArray(R.array.listValues);
{
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
int color = mColors[position % mColors.length]; // might as well be safe
view.setBackgroundColor(color);
return view;
}
}
I also highly recommend watching this video on how ListView works: The World of ListView. Also, nowadays people are moving toward RecyclerView instead; you don't have to do that necessarily, but either way this video should help you understand how these components behave.

ListView in a fragment Clickable and on item clicked listener

I have a listview in a fragment here is my current code for it:
public static class AllSectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public AllSectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tasks_all,
container, false);
// /////////////////////////////////////////////////////////////////
// Set up all components here:: ie text views , buttons lists etc.//
// that correspond to the layout fragment xml file //
////////////////////////////////////////////////////////////////////
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.fragment_tasks_all_textView);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
ArrayList<String> arrayList = new ArrayList<String>();
ListView allList = (ListView) rootView
.findViewById(R.id.fragment_tasks_all_list);
MyCustomAdapter mAdapter = new MyCustomAdapter(getActivity(),
arrayList); // Class to populate a ListView with an
// ArrayList
allList.setAdapter(mAdapter);
// Populate array list
for (int i = 0; i < 5; i++) {
arrayList.add(" All Task " + i);
}
mAdapter.notifyDataSetChanged();
return rootView;
}
public void onListItemClick(ListView l, View v, int position, long id) {
System.out.println("pos: "+ position);
}
}
and my layout.xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".TasksActivity$DummySectionFragment" >
<TextView
android:id="#+id/fragment_tasks_all_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/fragment_tasks_all_list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="0.41"
android:cacheColorHint="#00000000"
android:clickable="true"
android:listSelector="#android:color/transparent"
android:transcriptMode="alwaysScroll" >
</ListView>
First of all. how can i make it so that i can click on an item in the list,
and second of all how do i add the onclick listener for it.
Why dont you just use ListFragment:
public static class ArrayListFragment extends ListFragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, Shakespeare.TITLES));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
}
}
Use the alternative constructor for ArrayAdapter that allows you to specify a layout file to host your listview:
public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
I had a similar issue and was resolved by creating a interface with onClick method and implementing it in fragment.
Try do this:
Create a interface:
MyOnViewClickListener.java
public interface MyOnViewClickListener {
public void myOnViewClickListener(View v);
}
In your custom adapter class, create a constructor passing MyOnViewClickListener as argument:
private Context context;
private MyOnViewClickListener itemListener;
private List<String> items;
public MyCustomAdapter(Context context, List<String> items, MyOnViewClickListener itemListener) {
this.itemListener = itemListener;
this.context = context;
this.items = items;
}
Inside getView() method, put:
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.your_row_layout, parent, false);
TextView textView1 = (TextView) row.findViewById(R.id.quizchallenge);
textView1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
itemListener.myOnViewClickListener(v);
}
});
Finally, in your fragment class, implement the new interface:
public class ListFriendFragment extends Fragment implements MyOnViewClickListener {
.
.
.
#Override
public void myOnViewClickListener(View v){
//call your method
quickQuiz();
}
Set up the adapter:
adapter = new MyCustomAdapter(getContext(), myItemsList, MyFragment.this);

How do I dynamically update a spinner using ArrayList?

I have created a Spinner that is populated with an ArrayList. I want to dynamically add values to the ArrayList, so the the Spinner populates dynamically. However, when I try to add values to my ArrayList, I get a NullPointerException.
What am I missing? Do I have to reset the adapter before amending the ArrayList?
Here is my code:
My spinner, arraylist, and adapter:
deleteselection = (Spinner)view.findViewById(R.id.deletespinner);
portfoliosdelete = new ArrayList<String>();
portfoliosdelete.add("Select Portfolio");
adapterdeletetype = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,portfoliosdelete){
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
// If this is the initial dummy entry, make it hidden
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
// Pass convertView as null to prevent reuse of special case views
v = super.getDropDownView(position, null, parent);
}
// Hide scroll bar because it appears sometimes unnecessarily, this does not prevent scrolling
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
adapterdeletetype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
deleteselection.setAdapter(adapterdeletetype);
My code to dynamically update spinner:
else if(users.contains(usernull)){
pn1 = enterportfolioname.getText().toString();
user1 = new PortfolioRecord(pn1, "someemail#gmail.com");
users.remove(usernull);
users.add(user1);
portfoliosdelete.add(pn1); // <-- This causes a null pointer exception
adapterdeletetype.notifyDataSetChanged();
portfoliolist.invalidateViews();
Use the code below. This code will add a new item when the user selects and add a new item from the spinner.
Code sample:
layout main.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="vertical"
android:weightSum="10" >
<Spinner
android:id="#+id/cmbNames"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
layout spinner_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="vertical" >
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Activity class:
public class MainActivity extends Activity {
private static final String NAME = "name";
private static final String ADD_NEW_ITEM = "Add New Item";
private SimpleAdapter adapter;
private Spinner cmbNames;
private List<HashMap<String, String>> lstNames;
private int counter;
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
HashMap<String, String> map = lstNames.get(arg2);
String name = map.get(NAME);
if (name.equalsIgnoreCase(ADD_NEW_ITEM)) {
lstNames.remove(map);
counter++;
addNewName(String.valueOf(counter));
addNewName(ADD_NEW_ITEM);
adapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populateList();
cmbNames = (Spinner) findViewById(R.id.cmbNames);
adapter = new SimpleAdapter(this, lstNames, R.layout.spinner_item,
new String[] { NAME }, new int[] { R.id.tvName });
cmbNames.setAdapter(adapter);
cmbNames.setOnItemSelectedListener(itemSelectedListener);
}
private void populateList() {
lstNames = new ArrayList<HashMap<String, String>>();
addNewName("abc");
addNewName("pqr");
addNewName("xyz");
addNewName(ADD_NEW_ITEM);
}
private void addNewName(String name) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(NAME, name);
lstNames.add(map);
}
}
Try to call delete on adapterdeletetype instead of the arraylist. If it fails, then please post your logcat output.

How do I populate spinner with global string array variable?

I am trying to populate a a spinner but I am getting an error with my String array saying "Array constants can only be used in initializers". My code works fine when i employ the string array as a local variable, but as a global variable it doesn't. I really need to be able to use my string array as a global variable. Thank you in advance. Here is my code:
deleteselection = (Spinner)view.findViewById(R.id.deletespinner);
ArrayAdapter<String> adapterdeletetype;
//createdenominationsarray = getResources().getStringArray(R.array.createdenominations); //<--works
//String [] createdenominationsarray = {"Select Portfolio", "Two", "Three"}; //<--works
createdenominationsarray = {"Select Portfolio", "Two", "Three"};// <--doesn'twork
adapterdeletetype = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,createdenominationsarray){
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
// If this is the initial dummy entry, make it hidden
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
// Pass convertView as null to prevent reuse of special case views
v = super.getDropDownView(position, null, parent);
}
// Hide scroll bar because it appears sometimes unnecessarily, this does not prevent scrolling
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
adapterdeletetype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
denominationselection.setAdapter(adapterdeletetype);
I did the same thing for one of my project and it works for me. Below is the code snippet for your reference..
ArrayList<String> languages = new ArrayList<String>();
languages.add("English");
languages.add("German");
languages.add("French");
ArrayAdapter<String> langAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,languages);
ListView lv =(ListView)findViewById(R.id.listmain);
lv.setAdapter(langAdapter);
lv.setOnItemClickListener(new listclklisten(MainActivity.this));
public class listclklisten implements OnItemClickListener{
private Context parent;
public listclklisten(Context p){
parent=p;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TO DO your code here
}
}
inside string.xml Write:
<string-array name="spinner_array_environtment">
<item>Test</item>
<item>Production</item>
</string-array>
Inside your MainActivity.java :
public class MainActivity extends Activity {
Spinner spinner_environment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner_environment = (Spinner) findViewById(R.id.spinnerview);
adapter =ArrayAdapter.createFromResource(this, R.array.spinner_array_environtment,R.layout.spinner_phone);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_environment.setAdapter(adapter);
}
Inside spinner_phone.xml :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="13dp"
android:textColor="#4C4646" />
try this out. Hope it will help you.

Categories

Resources