Android : List Styling - android

Trying to display List based on Color code by verifying the condition (if (vehicleColor[i].equals("1")) ) and so on. If i am closing for loop, codes are working fine with single color using this code segment(getListView().setBackgroundColor(Color.WHITE);). I need to display List according to color code. Need Help Guys.
private void showColouredList() {
final ListAdapter adapter = new ArrayAdapter<String>(this,
R.layout.list_items, R.id.label, vehicleList);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
getListView().setDividerHeight(1);
// getListView().setBackgroundColor(Color.WHITE);
for (int i = 0; i < vehicleList.length; i++) {
System.out.println("--" + vehicleColor[i]);
if (vehicleColor[i].equals("1")) {
System.out.println("ListColour");
getListView().getChildAt(i).setBackgroundColor(Color.GREEN); // giving NullPointerException
} else if (vehicleColor[i].equals("2")) {
getListView().getChildAt(i).setBackgroundColor(Color.RED);
} else if (vehicleColor[i].equals("3")) {
getListView().getChildAt(i).setBackgroundColor(Color.YELLOW);
} else if (vehicleColor[i].equals("4")) {
getListView().getChildAt(i).setBackgroundColor(Color.GRAY);
}
}
getListView().setPadding(5, 10, 0, 10);
getListView().setCacheColorHint(Color.BLUE);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setEnabled(true);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index,
long arg3) {
// TODO Auto-generated method stub
Intent secondActivity = new Intent(First.this,
SecondActivity.class);
Utility.setDeviceId(listBean.getVehicleDeviceIdArr()[index]);
Utility.setWindowTitle(list[index]);
startActivity(secondActivity);
}
});
}

You can use the listAdapter, and do your job in the getView(); method of List(Array)Adapter.

Related

How to add 'select one' to a spinner, which gets data after api call

I have a spinner which populates data after an API call. I need to add an item that says "select one" as a first item in spinner. This item should not be able to be selected. I tried several ways online, but not able to implement it in my code since the array is filled after the api call and couldn't figure out a correct way to add "select one" item to that array.. Could anyone tell me how to do this in my code?
public void TEMPLATE_PARSE(JSONArray array) {
TemplateArrayList = new ArrayList<>();
TemplateNames = new ArrayList<String>();
for (int i = 0; i < array.length(); i++) {
JSONObject json = null;
try {
json = array.getJSONObject(i);
ModelTemplate GetTemplateDataModel = new ModelTemplate();
GetTemplateDataModel.setTemplateID(json.getInt("TemplateID"));
GetTemplateDataModel.setTemplateText(json.getString("TemplateText"));
TemplateArrayList.add(GetTemplateDataModel);
TemplateNames.add(TemplateArrayList.get(i).getTemplateText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
} // Close for loop here
if (array.length() != 0) {
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, simple_spinner_item, TemplateNames);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinTemplate.setAdapter(spinnerArrayAdapter);
spinTemplate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.i("ssssmIsSpinnerFirstCall",mIsSpinnerFirstCall.toString());
if(!mIsSpinnerFirstCall) {
selectedTemplateID = TemplateArrayList.get(position).getTemplateID();
String selectedTemplateText = TemplateArrayList.get(position).getTemplateText();
editText.setText(selectedTemplateText);
saveInSp("selectedTemplateID", String.valueOf(selectedTemplateID));
templateSelected = true;
}
mIsSpinnerFirstCall = false;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
First add Select One at position 0 to TemplateNames and then create adapter and set it to Spinner
TemplateNames.add(0, "Select One");
And then inside onItemSelected, check selected position and do whatever you want.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position == 0)
// Skip or show validation message if you want
else {
// Do your actual task here
...
selectedTemplateID = TemplateArrayList.get(position - 1).getTemplateID();
String selectedTemplateText = TemplateArrayList.get(position - 1).getTemplateText();
...
}
}

Android: how get ID of an item selected in a spinner?

I have this private method to render a spinner in a fragment:
private void renderSpinner() {
List<String> spinnerArray = new ArrayList<String>();
for (int i = 0; i<mPromotionList.size(); i++) {
ModelPromotion modelPromotion = (ModelPromotion) mPromotionList.get(i);
String name_promotion = modelPromotion.getName();
int id_promotion = modelPromotion.getIdPromotion();
spinnerArray.add(name_promotion);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mBaseApp, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerPromotion.setAdapter(adapter);
mSpinnerPromotion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String name_promotion_selected = parent.getItemAtPosition(pos).toString();
//TODO REMOVE
Log.d(LOGTAG, "Il nome della promo selezionata รจ " + name_promotion_selected);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
As you can see, I have "ready" the id_promotion (It's the real value that I need)... And I know that I'm not adding (for now) at the List.
How I can get it, inside the onItemSelected?
Thank you very much
You can use the position of the selected item and use that to get the ID from the original list.
((ModelPromotion) mPromotionList.get(pos)).getIdPromotion()
Another option is to create a custom ArrayAdapter subclass that will accept ModelPromotion instead of String and override getItemId to return the idPromotion
An example about custom ArrayAdapter on Github.

Search Filter in the ListView Not Working as Expected

We have a list view fragment that contains a listview, edit text(for search) and check box(Select All). As mentioned we are using Edit Text for searching the values from the list view.
Problem:
We have list view displaying 10 items( list view sorted alphabetically).
When we type 'W' in the edit text we are displayed with two values i.e. WF and WH.
The selection is made for WF(first item displayed).
After clearing the characters in the edit text, we are now displayed with the complete list of the list view.
But the selection is now made for first item in the list AHMD. (we intended to select WF)
Basically, the positions of the data in the list view is not getting refreshed after we have performed search.
code:
public static class ListViewFragment extends Fragment {
private ListView myListView;
private EditText editsearch;
private CheckBox selectAll;
private String SELECTED_FILTER;
private ArrayList<String> SelectedFilter1;
private ArrayList<String> checkekprev=new ArrayList<String>();
private ArrayList<String> CheckedFitlers=new ArrayList<String>();
ArrayAdapter<String> adapter_list;
OnCheckedItemsLister onCheckedItemsLister;
public ListViewFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onCheckedItemsLister = (OnCheckedItemsLister) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement onSomeEventListener");
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
SelectedFilter1=getArguments().getStringArrayList("ArrayList");
SELECTED_FILTER=getArguments().getString("SELECTED_FILTER");
checkekprev=getArguments().getStringArrayList("checkedprevlist");
if(checkekprev.size()==SelectedFilter1.size())
selectAll.setChecked(true);
else
selectAll.setChecked(false);
adapter_list = new ArrayAdapter<String>(this.getActivity(),
android.R.layout.simple_list_item_multiple_choice,SelectedFilter1);
adapter_list.notifyDataSetChanged();
myListView.setAdapter(adapter_list);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myListView.setTextFilterEnabled(true);
try{
if(checkekprev.isEmpty()==false){
Log.i("Adapter set", "Yes");
for(int j=0;j<checkekprev.size();j++){
Log.i("Adapter set", "Yes:"+j);
int pos=adapter_list.getPosition(checkekprev.get(j));
Log.i("Adapter set", "Pos:"+pos);
myListView.setItemChecked(pos,true);
}
}
}catch(NullPointerException e){
Log.i("Null set", "Yes");
}
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter_list.getFilter().filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Log.i("CheckBOX","Is Checked:"+isChecked);
if(isChecked)
{
for ( int i=0; i< myListView.getCount(); i++ )
myListView.setItemChecked(i, true);
}else
{
for ( int i=0; i< myListView.getCount(); i++ )
myListView.setItemChecked(i, false);
}
SparseBooleanArray checked = myListView.getCheckedItemPositions();
CheckedFitlers.clear();
for(int i=0;i<=checked.size();i++){
if (checked.get(i)){
CheckedFitlers.add(SelectedFilter1.get(i));
}
}
onCheckedItemsLister.someEvent(CheckedFitlers,SELECTED_FILTER);
}
}
);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id){
setItemChecked(position);
onCheckedItemsLister.someEvent(CheckedFitlers,SELECTED_FILTER);
}
});
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(savedInstanceState!=null){
checkekprev=savedInstanceState.getStringArrayList("Checked_Values");
}
}
public void setItemChecked(int position){
//if(SelectedFilter1.get(position).)
//int len = myListView.getCount();
SparseBooleanArray checked = myListView.getCheckedItemPositions();
for(int i=0;i<=checked.size();i++){
Log.i("Check Sparse Array","Check Sparse Array: "+checked.get(i));
}
//for (int i = 0; i < len; i++){
Log.i("SelectedFilter1.get(position)","SelectedFilter1.get(position):::"+SelectedFilter1.get(position));
Log.i("checked.get(position))","checked.get(position)):::"+checked.get(position));
for (int i=0; i<CheckedFitlers.size();i++){
Log.i("CheckedFitlers","CheckedFitlers:::" + CheckedFitlers.get(i));
}
for (int i=0; i<checkekprev.size();i++){
Log.i("checkekprev","checkekprev:::" + checkekprev.get(i));
}
Log.i("CheckedFitlers","CheckedFitlers:::" + CheckedFitlers.size());
Log.i("checkekprev","checkekprev:::" + checkekprev.size());
if(CheckedFitlers.size() == 0 && checkekprev.size() != 0){
CheckedFitlers = checkekprev;
}
Log.i("CheckedFitlers","CheckedFitlers:::" + CheckedFitlers.size());
if (checked.get(position)) {
Log.i("Adding","Adding::"+checked.get(position));
CheckedFitlers.add(SelectedFilter1.get(position));
for(int i=0;i<checkekprev.size();i++){
//Log.i("Checked Filters FOr loop","Checked Filters:"+CheckedFitlers.get(i));
}
} else
{
Log.i("Removing","Removing::"+checked.get(position)+":"+SelectedFilter1.get(position));
CheckedFitlers.remove(SelectedFilter1.get(position));
for(int i=0;i<checkekprev.size();i++){
//Log.i("Checked Filters for loop","Checked Filters:"+CheckedFitlers.get(i));
}
}
Log.i("CheckedFitlers","CheckedFitlers:::" + CheckedFitlers.size());
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_view, container, false);
myListView=(ListView) rootView.findViewById(R.id.listView_brand);
editsearch = (EditText) rootView.findViewById(R.id.search);
selectAll=(CheckBox) rootView.findViewById(R.id.checkBox1);
selectAll.setFocusable(false);
return rootView;
}
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.i("savedInstanceState in listfragment","savedInstanceState in listfragment");
//onCheckedItemsLister.someEvent(CheckedFitlers,SELECTED_FILTER);
onCheckedItemsLister.getSelectedFilter(SELECTED_FILTER);
}
}
When you typed 'W' in the edit text we are displayed with two values i.e. WF and WH. The selection is made for WF(first item displayed).
But you have performed action for first row of a listview, Now the checkbox of listview is checked and when clearing the characters in the edit text, your are seeing the complete list of the list view with first box checked. which is correct.
If you want to avoid this issues, Create custom adapter and override getfilter method.
Otherwise, Create your own logic and call listView.setItemChecked( stored positions, true/false); in ontextchanged.
In this example, let's say that the activity labels and listview items have equal values. There are 10 items from WF to WZ. (I sampled with 4 items) When "WZ" is typed in the edittext, the "WZ" item is displayed on the first line of the listview. When the first line is clicked, it is desirable to calling the "WZ" activity, not the "WF" activity. I've created the following little code for it, and it works fine.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String v1 = getString(R.string.title_activity_wf).toString();
String v2 = getString(R.string.title_activity_wh).toString();
String v3 = getString(R.string.title_activity_wm).toString();
String v4 = getString(R.string.title_activity_wt).toString();
.
.
.
.
.
.
String selectedFromList = (String) (listView.getItemAtPosition(position));
if (selectedFromList.equalsIgnoreCase(v1)) {
startActivity(new Intent(getApplicationContext(), Wf.class));
} else if (selectedFromList.equalsIgnoreCase(v2)) {
startActivity(new Intent(getApplicationContext(), Wh.class));
} else if (selectedFromList.equalsIgnoreCase(v3)) {
startActivity(new Intent(getApplicationContext(), Wm.class));
} else if (selectedFromList.equalsIgnoreCase(v4)) {
startActivity(new Intent(getApplicationContext(), Wt.class));
}
});

Using Spinner And List Views with setOnItemSelectedListener

I'm supposed to make a task , I have a spinner connected with a String array x , this array contains three values , so I want when clicking any choice of the spinner a specific list view will will give a specific three values and , this is my code :
public class Four extends ActionBarActivity {
String x [] = {"Jordan","Saudi Arabia", "Syria"};
String Jordan[] = {"Amman","Aqaba","Sarqa"};
String Saudi[] = {"Riyadh","Jeddah","Khobar"};
String Syria[] = {"Hems","Halab","Demashk"};
Spinner sp1 ;
ListView lv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.four);
lv1 = (ListView)findViewById(R.id.listView1);
// Jordan List View
ArrayAdapter<String> jor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Jordan);
lv1.setAdapter(jor);
// Saudi Arabia List View
ArrayAdapter<String> saud = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Saudi);
lv1.setAdapter(saud);
// Syria List View
ArrayAdapter<String> syr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Syria);
lv1.setAdapter(syr);
sp1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> a = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , x);
sp1.setAdapter(a);
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
The thir parameter of onItemSelected() (int arg2 in your example, but I would suggest you rename them) is the position you selected in the Spinner. So you could implement that method like this:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
if (position == 0)
lv1.setAdapter(jor);
else if (position == 1)
lv1.setAdapter(saud);
else if (position == 1);
lv1.setAdapter(syr);
}
Remember that all the variables involved (lv1, jor, saud, syr) must be defined as final to be used inside the anonymous class, e.g.
final ArrayAdapter<String> jor = ...
final ArrayAdapter<String> saud = ...

How to refresh a ListView in the activity

I have a ListActivity class. It has a button which sorts the item according to one of their attributes. But it so happens that the item are getting sort by their name but upon clicking the item of its original position is getting executed.
Here is the code snippet :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
mButton = (ToggleButton) findViewById(R.id.mButton);
ArrayList<myObject> ListData = new ArrayList<myObject>();
back = (ImageButton) findViewById(R.id.backButton);
label = (TextView) findViewById(R.id.likethis);
label.setText("List");
inputSearch = (EditText) findViewById(R.id.inputSearch);
//Manager -- class that reads from the sdcard
Manager plm = new Manager();
// get all files from sdcard
//getList() function of Manager class
//List declared outside oncreate()
this.List = plm.getList();
final ArrayList<myObject> backUp = new ArrayList<myObject>(songsList);
if(sortCalled) {
mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_checked));
mButton.setChecked(true);
Collections.sort(List);
notifyDataChanged(List);
}
else {
mButton.setBackground(getResources().getDrawable(R.drawable.m_unchecked));
mButton.setChecked(false);
notifyDataChanged(backUp);
}
back.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
inputSearch.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
adapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
//ArrayList <Song> temp;
((SimpleAdapter) PlayListActivity.this.adapter).getFilter().filter(s, new Filter.FilterListener() {
public void onFilterComplete(int count) {
// TODO Auto-generated method stub
adapter.notifyDataSetChanged();
}
});
adapter.notifyDataSetChanged();
}
});
mButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mButton.isChecked()){
mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_checked));
Collections.sort(List);
sortCalled = true;
notifyDataChanged(List);
}
else{
sortCalled = false;
mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_unchecked));
notifyDataChanged(backUp);
}
}
});
}
public void settingListAdapter(SimpleAdapter adapter){
setListAdapter(adapter);
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int Index = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
MainActivity.class);
// Sending Index to MainActivity
in.putExtra("Index", Index);
setResult(100, in);
// Closing ListView
finish();
}
});
}
public void notifyDataChanged(ArrayList<Song> songsList) {
// TODO Auto-generated method stub
setListAdapter(null);
sortCalled = true;
ArrayList<myObject> songsListData = new ArrayList<myObject>();
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
myObject ob = sList.get(i);
// adding HashList to ArrayList
ListData.add(ob);
}
ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String,String>>();
// int j = 0;
for(myObject i : ListData){
HashMap<String, String> feed = new HashMap<String, String>();
feed.put("Title", i.getTitle());
array.add(feed);
}
BaseAdapter adapter1;
// int i = 0;
// Adding menuItems to ListView
adapter1 = new SimpleAdapter(this, array,
R.layout.list_item, new String[]{"Title" }, new int[] {
R.id.Title });
setListAdapter(adapter1);
adapter1.notifyDataSetChanged();
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int Index = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
MainActivity.class);
// Sending songIndex to MainActivity
in.putExtra("Index", Index);
setResult(100, in);
// Closing ListView
finish();
}
});
I think you should try this.when you sort the data of your listview.it is working me perfectly
adapter.notifyDataSetChanged();
Everytime you make a change to adapter you should call notifyDataSetChanged() in UIThread
Please check this video to understand listView better
Edit
For an ArrayAdapter, notifyDataSetChanged only works if you use the add, insert, remove, and clear functions on the Adapter.
When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.
Your choices are:
Use the functions of the ArrayAdapter to modify the underlying List (add, insert, remove, clear, etc.)
Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
Use the notifyDataSetChanged every time the list is update. To call it on the UI-Thread use the runOnUiThread method of the Activity. Then notifyDataSetChanged will work.
You could try the Adapter.notifyDataSetChanged() function. It might work.
If you are using a SimpleCursorAdapter, calling requery() on the cursor attached to the adapter will automatically refresh the adapter and attached view.
If it's BaseAdapter content changes, you call BaseAdapter.notifyDataSetChanged() which will tell the ListView to update itself.
In other words you only need to make the following tiny change:
public void setValue(Object newValue) {
this.value = newValue;
notifyDataSetChanged();
}
Actually, since you're changing the state of an existing item (rather than adding new ones etc) then notifyDataSetInvalidated() would be a better choice.

Categories

Resources