android simple listview with colors - android

I work in an activity to show a list of strings, simply like this:
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
String[] lKeys = new String[mKey.size()];
int i = 0;
if (lKeys != null) {
for (Iterator<String> ite = mKey.iterator(); ite.hasNext();) {
String element = ite.next();
if (element.contains("Data")) {
lKeys[i++] = element;
} else {
lKeys[i++] = element + ": " + mValue.get(element);
}
}
}
//
this.setTitle(mTitle);
setListAdapter(new ArrayAdapter<String>(this,R.layout.popupactivity,lKeys));
whit this xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tvResults"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#000000"
android:background="#ffffff"
android:layout_marginLeft="5dp"
android:textSize="12sp"
android:padding="5dp" >
</TextView>
this works nice, but I need to put some colors to the lines of the list.
who can help me?
Really thanks!

You can add different colors to the background of each row of a ListView by extending SimpleAdapter and override the getView() method and apply background color to the current view row. Use the custom adapter as your list afterwards.
public class CustomList extends SimpleAdapter {
private int[] colors = new int[] { 0x30ADD8E6, 0x30800080 };
public CustomList(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
super(context, items, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
int colorPos = position % colors.length;
view.setBackgroundColor(colors[colorPos]);
return view;
}}
Next step is using the customList adapter as your list. Like this
myList = new CustomList (this,R.layout.lay,R.layout.grid_item,from,target);

Related

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.

Custom SimpleCursorAdapter doesn't bind data, and shows rows even when there's no data

So I'm trying to make a custom SimpleCursorAdapter, because I want to make list rows that look something like this:
ToggleButton | TextView | ImageButton,
and I know of no way to do this without making a custom adapter.
The problem being that my code doesn't work and I'm not really sure why. Even if there's no data to be displayed, I get a row with the default format:
ToggleButton | "default" | ImageButton.
Furthermore, all rows displayed look exactly the same as the default row, and the OnClickListener I set up doesn't do anything.
Can someone tell me what I'm doing wrong, or at least point me in the direction of a decent tutorial for how to deal with custom CursorAdapters and OnClickListeners? Because I've been totally unable to find anything remotely helpful.
Here is my code for the adapter:
public class AlarmCursorAdapter extends SimpleCursorAdapter {
private Cursor mCursor;
private Context mContext;
private Activity mActivity;
public AlarmCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
// TODO Auto-generated constructor stub
mCursor = c;
mContext = context;
mActivity = (Activity) context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.alarm_list_row, parent, false);
}
if(mCursor == null || mCursor.getCount() == 0) {
return view;
}
mCursor.moveToPosition(position);
// Set the alarm time view
TextView alarmView = (TextView) view.findViewById(R.id.alarmView);
int timeStringIndex = mCursor.getColumnIndexOrThrow(DailyAlarmTable.ALARM_TIME);
String alarmTime = mCursor.getString(timeStringIndex);
alarmView.setText(alarmTime);
// Set up the toggle button
int isActiveIndex = mCursor.getColumnIndexOrThrow(DailyAlarmTable.ALARM_ISACTIVE);
int isActive = mCursor.getInt(isActiveIndex);
ToggleButton alarmToggle = (ToggleButton)view.findViewById(R.id.alarmToggle);
if(isActive == 1) {
alarmToggle.setChecked(true);
} else {
alarmToggle.setChecked(false);
}
final int currentPosition = mCursor.getPosition();
int idIndex = mCursor.getColumnIndexOrThrow(DailyAlarmTable.ALARM_ID);
final long alarmId = mCursor.getLong(idIndex);
alarmToggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String toastStr = "clicked alarm " + alarmId + " at position " + currentPosition;
Toast.makeText(mContext, toastStr, Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
Here's the implementation, which occurs inside a fragment:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/*
mAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.alarm_list_row, null,
new String[] { DailyAlarmTable.ALARM_TIME, DailyAlarmTable.ALARM_ISACTIVE },
new int[] { R.id.alarmView, R.id.alarmToggle }, 0);
*/
mAdapter = new AlarmCursorAdapter(getActivity(),
R.layout.alarm_list_row, null,
new String[] { DailyAlarmTable.ALARM_TIME, DailyAlarmTable.ALARM_ISACTIVE },
new int[] { R.id.alarmView, R.id.alarmToggle }, 0);
//mAdapter.setViewBinder(new AlarmViewBinder());
ListView alarmList = (ListView) this.getActivity().findViewById(R.id.alarmListView);
TextView emptyView = (TextView) this.getActivity().findViewById(R.id.empty);
alarmList.setEmptyView(emptyView);
alarmList.setAdapter(mAdapter);
// Initialize the loader
getLoaderManager().initLoader(1, savedInstanceState, this);
}
Here's the XML file for the row:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ToggleButton
android:id="#+id/alarmToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/details_default" />
<TextView
android:id="#+id/alarmView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/details_default"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageButton
android:id="#+id/alarmDiscard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_discard"
android:contentDescription="#string/alarm_discard_description" />
</LinearLayout>
If there's any other code you need, I can gladly add that. Thank you very much in advance.
As suggested by pskink's comment, the solution was not to use a custom SCA at all, but to just implement a View Binder.

Generate background colour in listView from database

I have a listView generated from a database, is there a way to make a background colour or a picture to each "section" in the list:
if the first symbol in "Tip" is "W" the background should be Green, and if its "L" it should be red
Im thinking something like this, but i have no idea where to put it since it have to be done in every section:
tipvalue = BetsDbAdapter.KEY_TIP;
//Here to split the value to gain only "W" or "L"
String arrtip[] = tipvalue.split(" ", 2);
temptip = arrtip[0];
//then set background
if (temptip.equals("W")) {
getWindow().getDecorView().setBackgroundColor(Color.GREEN);
To the left is my listView and right is the xml file to make each "section" in the listview
Here is my database:
This is code generating the listView
public class StoredBets extends Activity {
private BetsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
dbHelper = new BetsDbAdapter(this);
dbHelper.open();
}
#Override
public void onStart(){
super.onStart();
displayListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.results, menu);
return true;
}
public void testknap1(View v) {
Intent myIntent = new Intent(StoredBets.this, Overview.class);
startActivity(myIntent);
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllStats();
String[] columns = new String[] {
BetsDbAdapter.KEY_SMATCH,
BetsDbAdapter.KEY_TIP,
BetsDbAdapter.KEY_BETAMOUNT,
BetsDbAdapter.KEY_BODDS
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.smatch,
R.id.tip,
R.id.bodds,
R.id.betamount,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.storedbets,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView2);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String betMatch =
cursor.getString(cursor.getColumnIndexOrThrow("smatch"));
Toast.makeText(getApplicationContext(),
betMatch, Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(StoredBets.this, SetWinVoidLoss.class);
myIntent.putExtra("id", id);
startActivity(myIntent);
}
});
}
}
EDIT 2:
#amal
This is the layout(results.xml) with the listview
<RelativeLayout 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: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=".StoredBets" >
<ListView
android:id="#+id/listView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignTop="#+id/button1" >
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="180dp"
android:onClick="testknap1"
android:text="Button" />
</RelativeLayout>
you can get a fair idea from my code,
code snippet for displaying ListViews where the "curSelected" item has a different background:
final ListView lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(new BaseAdapter()
{
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = new TextView(ListHighlightTestActivity.this);
convertView.setPadding(10, 10, 10, 10);
((TextView)convertView).setTextColor(Color.WHITE);
}
convertView.setBackgroundColor((position == curSelected) ?
Color.argb(0x80, 0x20, 0xa0, 0x40) : Color.argb(0, 0, 0, 0));
((TextView)convertView).setText((String)getItem(position));
return convertView;
}
public long getItemId(int position)
{
return position;
}
public Object getItem(int position)
{
return "item " + position;
}
public int getCount()
{
return 20;
}
});
This is a tutorial of how to write an adapter for a list view. amal is right, you can change the separate items in the list view in the getView() method.

Set TypeFace for ListView

I have 2 XML file for list View. One for views and other for use first.
note_list.XML is :
<?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="match_parent"
android:orientation="vertical"
android:padding="10dip" >
<Button
android:id="#+id/allNotes_btn_refresh_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/all_note_refresh_list" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</LinearLayout>
and list_otem.XML is :
<?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="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/list_lbl_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/list_lbl_subject"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/list_lbl_date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
in below code, i set adapter for list:
ArrayList<HashMap<String, String>> noteList;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_list);
noteList = new ArrayList<HashMap<String, String>>();
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String note_id = ((TextView) view
.findViewById(R.id.list_lbl_id)).getText().toString();
Intent i = new Intent(getApplicationContext(), NoteDetail.class);
i.putExtra("note_id", note_id);
startActivityForResult(i, 100);
}
});
}
public class LoadAllNotes extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllNotes.this);
pDialog.setMessage("???? ??? ????...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
noteList.clear();
}
protected String doInBackground(String... args) {
UserFunctions userFunctions = new UserFunctions();
jSon = userFunctions.getAllNotes(userId);
Log.i("AllNotes >> jSon >>", jSon.toString());
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
try {
if (jSon.has(KEY_SUCCESS)) {
String success = jSon.getString(KEY_SUCCESS);
if (success.equals("1")) {
notes = jSon.getJSONObject("notes");
for (int i = 0; i < notes.length(); i++) {
JSONObject c = notes.getJSONObject(Integer
.toString(i));
Log.i("JSONObject c >>", c.toString());
String id = c.getString(KEY_NOTE_ID);
String subject = c.getString(KEY_NOTE_SUBJECT);
String date = c.getString(KEY_NOTE_DATE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_NOTE_ID, id);
map.put(KEY_NOTE_SUBJECT, subject);
map.put(KEY_NOTE_DATE, date);
noteList.add(map);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(AllNotes.this,
noteList, R.layout.list_item, new String[] {
KEY_NOTE_ID, KEY_NOTE_SUBJECT,
KEY_NOTE_DATE }, new int[] {
R.id.list_lbl_id, R.id.list_lbl_subject,
R.id.list_lbl_date });
setListAdapter(adapter);
}
});
}
}
How can i set type face for TextViews in item_list.XML? I set note_list for content view in java code. so can't access to views of list_item.xml. thanks for helping me.
You'll need to override the SimpleAdapter's getView(int position, View convertView, ViewGroup parent) method and cast the result to a TextView. That should be safe to do for the R.layout.list_item layout, although you may want to double check that.
From there, setting a typeface works as usual.
Snippet, to be placed inside an (anonymous) extension of SimpleAdapter:
Typeface mTypeface = ... // only needs to be initialised once.
#Override public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textview = (TextView) view;
textview.setTypeface(mTypeface);
return textview;
}
If, perhaps at some point in the future, you're going to have a more complex layout made out of more than just a single TextView, I'd consider implementing your own extension of ArrayAdapter. There are heaps of examples on how to go about that (also look up the ViewHolder/RowWrapper pattern) and it'll give you full control.
Edit: example code below.
public class TypefacedSimpleAdapter extends SimpleAdapter {
private final Typeface mTypeface;
public TypefacedSimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
mTypeface = Typeface.createFromAsset(context.getAssets(), /* typeface */);
}
#Override public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textview = (TextView) view;
textview.setTypeface(mTypeface);
return textview;
}
}
Copy-paste the class above and make sure to set up the type face field as per your requirements. Then replace the current SimpleAdapter; i.e. something like this:
ListAdapter adapter = new TypefacedSimpleAdapter(AllNotes.this,
noteList, R.layout.list_item, new String[] {
KEY_NOTE_ID, KEY_NOTE_SUBJECT,
KEY_NOTE_DATE }, new int[] {
R.id.list_lbl_id, R.id.list_lbl_subject,
R.id.list_lbl_date }
);
Note that I didn't actually compile or run any of this. I'll leave it up to you to fill in any gaps and/or make corrections.
I add this below class :
public class myAdapter extends SimpleAdapter {
public myAdapter(Context context, List<HashMap<String, String>> items,
int resource, String[] from, int[] to) {
super(context, items, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
Typeface typeFace = Typeface.createFromAsset(getAssets(),
"fontsfolder/B Yekan.ttf");
TextView lbl_subject = ((TextView) view
.findViewById(R.id.list_lbl_subject));
TextView lbl_date = ((TextView) view
.findViewById(R.id.list_lbl_date));
lbl_date.setTypeface(typeFace);
lbl_subject.setTypeface(typeFace);
return view;
}
}
And change code when fill list by this :
myAdapter adapter = new myAdapter(AllNotes.this, noteList,
R.layout.list_item, new String[] { KEY_NOTE_ID,
KEY_NOTE_SUBJECT, KEY_NOTE_DATE },
new int[] { R.id.list_lbl_id,
R.id.list_lbl_subject, R.id.list_lbl_date });
setListAdapter(adapter);
Thanks to #MH. for help

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.

Categories

Resources