NotifyDataSetChanged() not refreshing list? - java

I know this question has been asked thousands of times but I couldn't find an answer for my case for some reason.
What I have is a thread that fetches data from a web services and populates a list with the info. Then I want to press a button and call the same thread to fetch some more data and add it to the list.
But when I call notifyDataSetChanged(), the list for some reason doesn't refresh. The data is in the adapter though...
Here's the code:
#Override
protected void onPostExecute(PropertyNotesParser result) {
this.progressDialog.dismiss();
ArrayList<PropertyNoteHistory> propertyNoteList = result.getAllTheNotes();
addNoteListItems(propertyNoteList);
Collections.sort(getNoteList());
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> subtitles = new ArrayList<String>();
DateHandler handleDate = new DateHandler();
DataResolve convert = new DataResolve();
for(Iterator<PropertyNoteHistory> i = getNoteList().iterator(); i.hasNext(); ) {
PropertyNoteHistory item = i.next();
PropertyNoteHistory.Note note = item.getNotes();
PropertyNoteHistory.Jobs jobs = item.getJobs();
// Default value is office in case the xml does not have the tag "job" associated with "note".
String service = "Office";
if(jobs != null){
service = convert.getServiceName(jobs.getServiceID());
}
titles.add(note.getTitle() + " (" + service + ")");
subtitles.add(handleDate.formatDate(note.getDate(), "dd MMM yyyy") + " Ref: " + note.getJobID());
}
if(getConnectionCount() == 0){
adapter = new SimpleListAdapter(getActivity(), titles, subtitles);
lv.setAdapter(adapter);
}
else {
adapter.addItem(titles, subtitles);
}
and my adapter:
public class SimpleListAdapter extends BaseAdapter {
private int count = 0;
private static LayoutInflater inflater = null;
private ArrayList<String> titles = new ArrayList<String>();
private ArrayList<String> subtitles = new ArrayList<String>();
private ArrayList<Integer> imageResource = new ArrayList<Integer>();
private boolean hasImage = false;
public SimpleListAdapter(Activity activity, ArrayList<String> titles,
ArrayList<String> subtitles, ArrayList<Integer> imageResource) {
count = titles.size();
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.titles = titles;
this.subtitles = subtitles;
this.imageResource = imageResource;
this.hasImage = true;
}
/**Constructor that creates an adapter with only a title and subtitle.
* #param activity The context.
* #param titles ArrayList with the titles of each list option.
* #param subtitles ArrayList with the subtitles of each list option. */
public SimpleListAdapter(Activity activity, ArrayList<String> titles,
ArrayList<String> subtitles) {
count = titles.size();
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.titles = titles;
this.subtitles = subtitles;
this.hasImage = false;
}
public void addItem(ArrayList<String> title, ArrayList<String> subtitle){
this.titles.addAll(title);
this.subtitles.addAll(subtitle);
notifyDataSetChanged();
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null)
v = inflater.inflate(R.layout.layout_simple_list, null);
final ImageView icon = (ImageView) v.findViewById(R.id.icon);
final TextView title = (TextView) v.findViewById(R.id.title);
final TextView subtitle = (TextView) v.findViewById(R.id.subtitle);
title.setText(titles.get(position));
subtitle.setText(subtitles.get(position));
if (hasImage) {
icon.setImageResource(imageResource.get(position));
}
else {
icon.setVisibility(ImageView.GONE);
}
return v;
}
}

You will need to update your count variable too in addItem so that the all the rows are created when notifyDataSetChanged is called

Related

How to adjust a search filter for a ListView, in which items are objects containing 2 strings each? (Not 1 string per item.)

I have a ListView fulfilled with arrayList finalArray.
finalArray items are objects , each object
consisting of two TwxtViews - swedish word and its english translation
(all taken from 2 arrayLists - swedishPractice and englishPractice).
I have made EditText theFilter in order to search through the ListView,
but when I type anythong in theFilter all the items desappear from
the screen and nothing is found (whereas matches have to remain).
Why so and how to make matches remain?..
(When I made a ListView with objects containing
only 1 TextView, everything worked.)
That's how is object Word created:
public class Word {
private String swedish;
private String english;
public Word(String swedish, String english) {
this.swedish = swedish;
this.english = english;
}
public String getSwedish() {
return swedish;
}
public void setSwedish(String swedish) {
this.swedish = swedish;
}
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
}
That's how I made the ListView:
ListView mListView = (ListView) findViewById(R.id.switchList);
EditText theFilter = (EditText) findViewById(R.id.searchFilter);
Log.d(TAG, "onCreate: Started");
ArrayList<Word> finalArray = new ArrayList<Word>();
for (int i = 0; i < Practice.swedishPractice.size(); i++) {
finalArray.add(new Word(Practice.swedishPractice.get(i),Practice.englishPractice.get(i)));
}
adapter = new CheckListAdapter(this, R.layout.list_item_layout, finalArray, this);
mListView.setAdapter(adapter);
theFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
(VisaEj.this).adapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
And this is its adapter (in case you need to see it to give an answer)
(made in separate class):
public class CheckListAdapter extends ArrayAdapter<Word> {
private static final String TAG = "CheckListAdapter";
private Context mContext;
private int mResource;
private int lastPosition = -1;
/**
* Hold variables in a view
*/
static class ViewHolder {
TextView swedish;
TextView english;
}
/**
* Default constructor for the CheckListAdapter
* #param context
* #param resource
* #param objects
*/
public CheckListAdapter(#NonNull Context context, int resource, #NonNull ArrayList<Word> objects, Context mContext) {
super(context, resource, objects);
this.mContext = mContext;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//get the word two examples
String swedish = getItem(position).getSwedish();
String english = getItem(position).getEnglish();
//create the word object with two examples
Word word = new Word(swedish, english);
//create the view result for showing the animation
final View result;
//Viewholder object
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder = new ViewHolder();
holder.swedish = (TextView) convertView.findViewById(R.id.textView1);
holder.english = (TextView) convertView.findViewById(R.id.textView2);
result = convertView;
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext,
(position > lastPosition) ? R.anim.loading_down_anim : R.anim.loading_up_anim);
result.startAnimation(animation);
lastPosition = position;
holder.swedish.setText(word.getSwedish());
holder.english.setText(word.getEnglish());
return convertView;
}
}

Android : Add random data with different images and proper text

I am working on a demo android app. Currently, I have a list of products which I am displaying, but they all have same image and the text generated is also random characters generated with Java method. Needless to say, it doesn't look very good.
I am using an adapter and displaying the data. How can I efficiently use random images(either from URL or from a selected folder), and names from some XML file to make the UI look better.
Code :
public class Products extends Activity{
ProductAdapter productAdapter;
List<Product> productList = new ArrayList<>();
private SecureRandom random = new SecureRandom();
public static final String productName = "productName";
public static final String productComments = "productComments";
public static final String productLikes = "productLikes";
public static final String productDescription = "productDescription";
public static final String userName = "userName";
ListView productsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
for(int i=1;i<100;i++){
Product product = createProduct();
productList.add(product);
}
ArrayList<HashMap<String, String>> productsArrayHashList = new ArrayList<>();
for (Product product : productList){
HashMap<String,String> productDisplay = new HashMap<>();
productDisplay.put(productName,product.getName());
productDisplay.put(productComments,String.valueOf(product.getCommentCount()));
productDisplay.put(productLikes,String.valueOf(product.getLikes()));
productDisplay.put(productDescription,product.getDescription());
productDisplay.put(userName,new BigInteger(130, random).toString(32));
productsArrayHashList.add(productDisplay);
}
productsList = (ListView) findViewById(R.id.productList);
productAdapter = new ProductAdapter(this,productsArrayHashList);
productsList.setAdapter(productAdapter);
}
public Product createProduct(){
int minimum = 1;
int maxValue = 20;
Product product = new Product();
product.setCommentCount(minimum + random.nextInt(maxValue - minimum + 1));
product.setLikes(minimum + random.nextInt(maxValue - minimum + 1));
product.setSaveDate(new Timestamp(System.currentTimeMillis()));
product.setDescription(new BigInteger(130, random).toString(32));
product.setName(new BigInteger(130, random).toString(32));
product.setSize(new BigInteger(130, random).toString(32));
if(getRandomBoolean()) {
product.setSold(true);
}else {
product.setSold(false);
}
return product;
}
Adapter code :
public class ProductAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
private SecureRandom random = new SecureRandom();
public ProductAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null) {
view = inflater.inflate(R.layout.product_row, null);
TextView productName = (TextView) view.findViewById(R.id.productName);
TextView userUploader = (TextView)view.findViewById(R.id.uploadingUser);
RatingBar ratingBar = (RatingBar)view.findViewById(R.id.productStars);
TextView comments = (TextView) view.findViewById(R.id.comments);
TextView productDetails = (TextView) view.findViewById(R.id.description);
ImageView prodImage = (ImageView) view.findViewById(R.id.productImage);
prodImage.setImageResource(R.drawable.productwatch);
HashMap<String, String> productList;
productList = data.get(position);
productName.setText(productList.get(Products.productName));
comments.setText("Comments("+productList.get(Products.productComments)+")");
productDetails.setText(productList.get(Products.productDescription));
userUploader.setText(productList.get(Products.userName));
int minimum = 1;
int maxValue = 5;
ratingBar.setRating((float) (minimum + random.nextInt(maxValue - minimum + 1)));
}
return view;
}
}
Thank you.
I have a solution.
You'll need Picasso library for Android
Add this line to build.gradle under dependancies
compile 'com.squareup.picasso:picasso:2.5.2'
In your Adapter code, add this after initializing your ImageView.
Picasso.with(getApplicationContext)
.load("http://lorempixel.com/200/200/")
.into(imageView);`
For more info : Picasso - Github
The numbers after that URL are the dimensions, you can specify suitable dimensions.
I used http://lorempixel.com/ (Visit it to explore more features)
You can use any site to get the images.

ListView - Item selection disappears with scrolling

I'm newbie. For couple of days I'm trying to resolve this issue, but no luck. Any help ? Thanks in advance.
Below is the images,
I selected few items and then scrolled up
Once scrolled down selection disappears
Below the adapter class I implemented,
/**
* Created by abcd on 27/1/17.
*/
public class ListItemAdapterTaxCheckBox extends BaseAdapter {
//flag = 1 name/id
//flag =2 //ID/Name
public class HolderCheck
{
TextView tv;
CheckBox ck;
}
private static LayoutInflater inflater=null;
Tax[] result;
Context context;
Tax[] selections = null;
String [] IDs = null;
boolean bAllSel = false;
Resources res = null;
public ListItemAdapterTaxCheckBox(Activity mainActivity, Tax[] prgmNameList, Tax[] sel, Resources rs, String [] ids) {
result=prgmNameList;
context=mainActivity;
selections = sel;
if(selections==null)
{
selections = new Tax[1];
selections[0] = new Tax();
}
IDs = ids;
res = rs;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return result.length + 1;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final HolderCheck holderCk = new HolderCheck();;
View rowView = convertView;
final int pos = position;
rowView = inflater.inflate(R.layout.custom_list_check_box, null);
holderCk.tv = (TextView) rowView.findViewById(R.id.code);
holderCk.ck = (CheckBox) rowView.findViewById(R.id.checkBox1);
if(position==0) {
holderCk.tv.setText(context.getString(R.string.all_text));
}
else {
holderCk.tv.setText("" + result[position-1].m_TaxID + " - " + result[position-1].m_TaxName);
}
holderCk.tv.setTextSize(16);
holderCk.tv.setTextColor(Color.BLACK);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holderCk.ck.isChecked()) {
holderCk.tv.setBackgroundColor(Color.WHITE);
holderCk.ck.setChecked(false);
if(pos!=0)
{
if (IDs != null)
IDs[pos -1] = "0";
}
else
{
bAllSel = false;
}
} else {
holderCk.tv.setBackgroundColor(GetResourceColor.getColorWrapper(context, R.color.selHintColor));
holderCk.ck.setChecked(true);
if(pos!=0)
{
if (IDs != null)
IDs[pos -1] = "" + result[pos-1].m_TaxID;
}
else
{
bAllSel = true;
}
}
}
});
return rowView;
}
public String [] getIDs() {
if(bAllSel)
return null;
else {
ArrayList<String> arrayList = new ArrayList<String>();
for (int i = 0, j = 0; i < IDs.length; i++) {
if (IDs[i].trim() != "0") {
arrayList.add(j, IDs[i].trim());
j = j + 1;
if (arrayList.size() == MySQLHelper.MAXITEMSLISTDELETE)
break;
}
}
return arrayList.toArray(new String[arrayList.size()]);
}
}
}
Below the way I'm populating the ListView
//class member
Tax[] valuesTaxID = null;
//inside a method
//default
Tax[] tx = new Tax[1];
tx[0] = new Tax();
if (valuesTaxID != null) {
listV.setAdapter(null);
listV.setAdapter(new ListItemAdapterTaxCheckBox(ctx, valuesTaxID, tx, rs, Ids));
listV.setVisibility(View.VISIBLE);
ListView will create and destroy views when you scroll. Your code is changing a checkbox when a view is clicked, but you store that info nowhere else, you scroll, ListView destroys the view when you scroll, and there you lost the status of the view.
You want to store the "checked" state of the view somewhere. Could be an ArrayList with states, could be a tag attached to the ViewHolders, ... just store it somewhere.

java.lang.ArrayIndexOutOfBoundsException after creating list view with >100 items

After creating a list view containing over 100 items (111 to be precise) and deploying the app, it runs as expected but as soon as I scroll through my list, the app crashes and an ArrayIndexOutOfBoundsException is returned. I really don't understand why the length and index are returning '19'. Does anyone know why 19 is shown? What needs to be done to resolve this issue?
java.lang.ArrayIndexOutOfBoundsException: length=19; index=19
at com.helloapps.helloworldapp.adapters.OrangeListAdapter.getPositionForSection(OrangeListAdapter.java:160)
XML
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice"
android:fastScrollEnabled="true"
android:scrollbarStyle="outsideInset"/>
Java
public class OrangeListAdapter extends BaseAdapter implements Filterable, SectionIndexer {
private List<Orange> mData;
private List<Orange> mFilteredData;
private LayoutInflater mInflater;
private ItemFilter mFilter;
private Object[] mSections;
private int[] mSectionsIndexedByPosition;
private int[] mPositionsIndexedBySection;
public OrangeListAdapter (List<Orange> data, Context context) {
mData = data;
mFilteredData = new ArrayList(mData);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
setupSections();
}
#Override
public int getCount() {
return mFilteredData.size();
}
#Override
public Orange getItem(int position) {
return mFilteredData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_dualline, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.item_name);
holder.description = (TextView) convertView.findViewById(R.id.item_description);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Orange orange = getItem(position);
holder.title.setText(orange.getName());
holder.description.setText(orange.getDescrption());
if (orange.isSelected()) {
convertView.setBackgroundColor(Color.parseColor("#FF6600"));
holder.title.setTextColor(Color.parseColor("#FFFFFF"));
holder.description.setTextColor(Color.parseColor("#FFFFFF"));
} else {
convertView.setBackgroundColor(Color.TRANSPARENT);
holder.title.setTextColor(Color.parseColor("#FFFFFF"));
holder.description.setTextColor(Color.parseColor("#B5B5B5"));
}
holder.title.setText(mFilteredData.get(position).getStation());
holder.description.setText(mFilteredData.get(position).getZone());
return convertView;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemFilter();
}
return mFilter;
}
/**
* View holder
*/
static class ViewHolder {
private TextView title;
private TextView description;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (TextUtils.isEmpty(constraint)) {
results.count = mData.size();
results.values = new ArrayList(mData);
} else {
//Create a new list to filter on
List<Orange> resultList = new ArrayList<Orange>();
for (Orange str : mData) {
if (str.getStation().toLowerCase().contains(constraint.toString().toLowerCase())) {
resultList.add(str);
}
}
results.count = resultList.size();
results.values = resultList;
}
return results;
}
/**
* Runs on ui thread
* #param constraint the constraint used for the result
* #param results the results to display
*/
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count == 0) {
mFilteredData.clear();
notifyDataSetInvalidated();
} else {
mFilteredData = (ArrayList<Orange>)results.values;
notifyDataSetChanged();
}
setupSections();
}
}
#Override
public int getPositionForSection(int section) {
return mPositionsIndexedBySection[section];
}
#Override
public int getSectionForPosition(int position) {
return mSectionsIndexedByPosition[position];
}
#Override
public Object[] getSections() {
return mSections;
}
private void setupSections() {
String initial = "\0";
List<String> sections = new ArrayList<String>();
mSectionsIndexedByPosition = new int[mFilteredData.size()];
mPositionsIndexedBySection = new int[mFilteredData.size()];
int section = 0;
for (int pos = 0; pos < mFilteredData.size(); pos++) {
Orange orange = mFilteredData.get(pos);
if (initial.charAt(0) != orange.getName().charAt(0)) {
initial = orange.getName().substring(0, 1);
section = sections.size();
sections.add(initial);
mPositionsIndexedBySection[section] = pos;
mSectionsIndexedByPosition[pos] = section;
} else {
mSectionsIndexedByPosition[pos] = section;
}
}
mSections = sections.toArray();
mPositionsIndexedBySection = Arrays.copyOf(mPositionsIndexedBySection, mSections.length);
}
}
Your array declared to have only 19 places, that means you can access maximum index of 18 as in arrays index starts with 0, but in above code you are accessing 19th index, then it will complain that your index is out of bound that is 18.
This line looks problematic to me:
mPositionsIndexedBySection = Arrays.copyOf(mPositionsIndexedBySection, mSections.length);
**To solve the problem**: Ensure that you are putting things in an array based on its size. If arrays has size n i.e. 19 then you are supposed to put element only till n-1 index i.e. 18.
Fast Scroller only read your sections from SectionIndexer.getSections() once, and will not change afterwards.
So the problem seems to occur when your first list contains over 19 sections, and afterwards reload a list where you want to reduce the number of sections to less than 19, which reduce the size of mPositionsIndexedBySection as well.
Because the Fast Scroller still remember the old sections, and try to get the position of the 19th section, error occurs.
To solve the problem, have fixed number of sections containing all posible section, only change the mPositionsIndexedBySection and mSectionsIndexedByPosition on data change.
Edit:
Check the link below on how to properly implements SectionIndexer
http://androidopentutorials.com/android-listview-fastscroll/
http://responsiveandroid.com/2013/04/13/android-sectionindexer-with-alphabet.html

Data couldn't be retrieved from an internet

I want to retrieve the data from particular website( "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore ),
however, I couldn't managed to retrieve it.
I think there is something wrong with my code but I not sure which part gone wrong.
Could anyone help me out?
This is my coding.
It contains of the spinner date filtering as well.
public class AndroidXMLParsingActivity extends ListActivity implements OnItemSelectedListener {
List<String> browseby = new ArrayList<String>();
Date d = new Date();
String[] dates = { "Today", "Tomorrow", "This Week",
};
ArrayList<String> browse = new ArrayList<String>();
ArrayList<String> mPostingData = new ArrayList<String>();
Spinner s1;
ListView listview;
CustomAdapter cus;
// All static variables
static final String URL = "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore";
// XML node keys
static final String KEY_EVENT = "event"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_START_TIME = "start_time";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_EVENT);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_TITLE,KEY_START_TIME }, new int[] {
R.id.title,
R.id.startTime });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
startActivity(in);
}
});
listview = (ListView) findViewById(R.id.listView1);
s1 = (Spinner) findViewById(R.id.spinner1);
for (int i = 0; i < browseby.size(); i++) {
browse.add(browseby.get(i));
}
// aa = new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category);
s1.setOnItemSelectedListener(this);
mPostingData = browse;
for (int i = 0; i < mPostingData.size(); i++) {
if (mPostingData.size() > 0)
Log.i("Datas", mPostingData.get(i));
}
cus = new CustomAdapter(this, 0);
setListAdapter(cus);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dates);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// listview.setFilterText(Category[position]);
String Text = s1.getSelectedItem().toString();
cus.getFilter().filter(Text);
cus.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> parent) {
// listview.setFilterText("");
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(this, "You have selected " + mPostingData.get(position),
Toast.LENGTH_SHORT).show();
}
class CustomAdapter extends ArrayAdapter<String> {
public void setData(ArrayList<String> mPpst) {
mPostingData = mPpst;// contains class items data.
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected void publishResults(CharSequence constraint,
FilterResults start_time) {
if (start_time != null && start_time.count >= 0) {
setData((ArrayList<String>) start_time.values);
} else {
setData(browse);// set original values
}
notifyDataSetInvalidated();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if(constraint=="Today") {
constraint = constraint.toString();
CharSequence s = DateFormat.format("yyyy-MM-dd ", d.getTime());
ArrayList<String> foundItems = new ArrayList<String>();
if (browse != null) {
for (int i = 0; i < browse.size(); i++) {
if (browse.get(i).contains(s)){
System.out.println("My datas" + browse.get(i));
foundItems.add(browse.get(i));
} else {
}
}
}
result.count = foundItems.size();// search results found
// return count
result.values = foundItems;// return values
} else {
result.count = -1;// no search results found
}
return result;
}
};
}
LayoutInflater mInflater;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
vh.t1 = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(vh);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
vh = (ViewHolder) convertView.getTag();
}
if (mPostingData.size() > 0)
vh.t1.setText(mPostingData.get(position));
return convertView;
}
}
static class ViewHolder {
TextView t1;
}
}
have you added this permission in your manifest file
<uses-permission
android:name="android.permission.INTERNET"
></uses-permission>

Categories

Resources