My listView is attached to an editText to allow the user to search through the listView. The problem is, the data filling my listView only shows after the user enters text into the editText and I would like the results to show before the user even types anything.
public class Search extends Activity {
EditText editText;
ListView listview;
int textlength = 0;
int width;
Button list;
Button filter;
CustomAdapter adapter;
Location userLoc;
private ArrayList<String> brand;
private ArrayList<String> size;
private ArrayList<String> price;
private ArrayList<Integer> percent;
private ArrayList<String> objID;
private ArrayList<String> store;
private ArrayList<String> address;
private ArrayList<Integer> distance;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<String> size_sort = new ArrayList<String>();
ArrayList<String> price_sort = new ArrayList<String>();
ArrayList<Integer> percent_sort = new ArrayList<Integer>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
ArrayList<String> id_sort = new ArrayList<String>();
ArrayList<String> store_sort = new ArrayList<String>();
ArrayList<String> address_sort = new ArrayList<String>();
ArrayList<Integer> distance_sort = new ArrayList<Integer>();
Integer longitude;
Integer latitude;
ParseObject dealsObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_page);
Parse.initialize(this, "vUz23Z6zdIL1jbxbVWeLpsSdu1ClTu3YiG30zTWY",
"4BTyoq1QQKows8qVJV7lvU3ZokSRrLFyOCPzffwJ");
listview = (ListView) findViewById(R.id.listView1);
editText = (EditText) findViewById(R.id.editText1);
brand = new ArrayList<String>();
size = new ArrayList<String>();
price = new ArrayList<String>();
percent = new ArrayList<Integer>();
objID = new ArrayList<String>();
store = new ArrayList<String>();
address = new ArrayList<String>();
distance = new ArrayList<Integer>();
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
userLoc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = (int) userLoc.getLongitude();
latitude = (int) userLoc.getLatitude();
userLoc.setLatitude(latitude);
userLoc.setLongitude(longitude);
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
getDeals();
adapter = new CustomAdapter(brand, size, price, percent, objID, store,
address, distance);
listview.setAdapter(adapter);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength = editText.getText().length();
text_sort.clear();
size_sort.clear();
price_sort.clear();
percent_sort.clear();
image_sort.clear();
id_sort.clear();
store_sort.clear();
address_sort.clear();
distance_sort.clear();
for (int i = 0; i < brand.size(); i++) {
if (textlength <= brand.get(i).length()) {
if (editText
.getText()
.toString()
.equalsIgnoreCase(
(String) brand.get(i).subSequence(0,
textlength))) {
text_sort.add(brand.get(i));
size_sort.add(size.get(i));
price_sort.add(price.get(i));
percent_sort.add(percent.get(i));
id_sort.add(objID.get(i));
store_sort.add(store.get(i));
address_sort.add(address.get(i));
distance_sort.add(distance.get(i));
listview.setAdapter(new CustomAdapter(text_sort,
size_sort, price_sort, percent_sort,
id_sort, store_sort, address_sort,
distance_sort));
// Register onClickListener to Handle Click Events
// on Each Item
listview.setOnItemClickListener(new OnItemClickListener() {
//
// Argument position gives the index of item
// which is clicked
#Override
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
String brand = (String) text_sort
.get(position);
String size = (String) size_sort
.get(position);
String price = (String) price_sort
.get(position);
String objID = (String) id_sort
.get(position);
String store = (String) store_sort
.get(position);
String address = (String) address_sort
.get(position);
int percent = (int) percent_sort
.get(position);
Integer distance = distance_sort
.get(position);
Intent intent = new Intent(
"com.alpha.dealtap.DEALPAGE");
intent.putExtra("Brand", brand);
intent.putExtra("Size", size);
intent.putExtra("Price", price);
intent.putExtra("Percent", percent);
intent.putExtra("ID", objID);
intent.putExtra("Store", store);
intent.putExtra("Address", address);
intent.putExtra("Distance", distance);
System.out.println("My Selection: "
+ intent.toString());
startActivity(intent);
}
});
}
}
}
}
});
list = (Button) findViewById(R.id.sort);
Button map = (Button) findViewById(R.id.map);
filter = (Button) findViewById(R.id.filter);
list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PopupMenu popup = new PopupMenu(Search.this, list);
popup.getMenuInflater().inflate(R.menu.sortmenu,
popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if (item.getOrder() == 1) {
brand.clear();
size.clear();
price.clear();
percent.clear();
objID.clear();
store.clear();
address.clear();
distance.clear();
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
getDealsPrice();
System.out.println(price);
} else if (item.getOrder() == 2) {
brand.clear();
size.clear();
price.clear();
percent.clear();
objID.clear();
store.clear();
address.clear();
distance.clear();
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
getDealsPercent();
System.out.println(price);
} else if (item.getOrder() == 3) {
brand.clear();
size.clear();
price.clear();
percent.clear();
address.clear();
distance.clear();
objID.clear();
store.clear();
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
getDealsName();
System.out.println(brand);
} else {
System.out.println("Shit....Item is: "
+ item.getTitle());
}
Toast.makeText(Search.this,
"You Clicked : " + item.getTitle(),
Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
});
filter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PopupMenu popupTwo = new PopupMenu(Search.this, filter);
popupTwo.getMenuInflater().inflate(R.menu.filtermenu,
popupTwo.getMenu());
popupTwo.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if (item.getOrder() == 1) {
brand.clear();
size.clear();
price.clear();
percent.clear();
objID.clear();
address.clear();
distance.clear();
store.clear();
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
getDealsName();
} else {
Intent intent = new Intent(
"com.alpha.dealtap.STORESEARCH");
startActivity(intent);
}
return true;
}
});
popupTwo.show();
}
});
map.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("com.alpha.dealtap.MAP"));
}
});
}
private void getDeals() {
// TODO Auto-generated method stub
ParseQuery query = new ParseQuery("Deals");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject dealsObject : objects) {
brand.add(dealsObject.getString("Brand"));
size.add(dealsObject.getString("Size"));
price.add("$" + dealsObject.getString("Price"));
percent.add(dealsObject.getInt("Percentage"));
objID.add(dealsObject.getObjectId());
store.add(dealsObject.getString("Store"));
address.add(dealsObject.getString("Address"));
Location location = new Location("");
location.setLatitude(dealsObject.getInt("Latitude"));
location.setLongitude(dealsObject.getInt("Longitude"));
distance.add((int) ((userLoc.distanceTo(location))/1609.34));
}
} else {
Log.v("Brand", "Error: " + e.getMessage());
}
}
});
}
private void getDealsPrice() {
// TODO Auto-generated method stub
ParseQuery query = new ParseQuery("Deals");
query.addDescendingOrder("Price");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject dealsObject : objects) {
brand.add(dealsObject.getString("Brand"));
size.add(dealsObject.getString("Size"));
price.add("$" + dealsObject.getString("Price"));
percent.add(dealsObject.getInt("Percentage"));
objID.add(dealsObject.getObjectId());
store.add(dealsObject.getString("Store"));
address.add(dealsObject.getString("Address"));
Location location = new Location("");
location.setLatitude(dealsObject.getInt("Latitude"));
location.setLongitude(dealsObject.getInt("Longitude"));
distance.add((int) ((userLoc.distanceTo(location))/1609.34));
}
} else {
Log.v("Brand", "Error: " + e.getMessage());
}
}
});
}
private void getDealsPercent() {
// TODO Auto-generated method stub
ParseQuery query = new ParseQuery("Deals");
query.addDescendingOrder("Percentage");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject dealsObject : objects) {
brand.add(dealsObject.getString("Brand"));
size.add(dealsObject.getString("Size"));
price.add("$" + dealsObject.getString("Price"));
percent.add(dealsObject.getInt("Percentage"));
objID.add(dealsObject.getObjectId());
store.add(dealsObject.getString("Store"));
address.add(dealsObject.getString("Address"));
Location location = new Location("");
location.setLatitude(dealsObject.getInt("Latitude"));
location.setLongitude(dealsObject.getInt("Longitude"));
distance.add((int) ((userLoc.distanceTo(location))/1609.34));
}
} else {
Log.v("Brand", "Error: " + e.getMessage());
}
}
});
}
private void getDealsName() {
// TODO Auto-generated method stub
ParseQuery query = new ParseQuery("Deals");
query.addAscendingOrder("Brand");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject dealsObject : objects) {
brand.add(dealsObject.getString("Brand"));
size.add(dealsObject.getString("Size"));
price.add("$" + dealsObject.getString("Price"));
percent.add(dealsObject.getInt("Percentage"));
objID.add(dealsObject.getObjectId());
store.add(dealsObject.getString("Store"));
address.add(dealsObject.getString("Address"));
Location location = new Location("");
location.setLatitude(dealsObject.getInt("Latitude"));
location.setLongitude(dealsObject.getInt("Longitude"));
distance.add((int) ((userLoc.distanceTo(location))/1609.34));
}
} else {
Log.v("Brand", "Error: " + e.getMessage());
}
}
});
}
class CustomAdapter extends BaseAdapter {
String[] data_text;
String[] size_text;
String[] price_text;
String[] id_text;
String[] store_text;
String[] address_text;
Integer[] percent_text;
Integer[] distance_text;
CustomAdapter(String[] text, String[] size, String[] price,
Integer[] percent, String[] id, String[] store,
String[] address, Integer[] distance) {
data_text = text;
size_text = size;
price_text = price;
percent_text = percent;
store_text = store;
address_text = address;
id_text = id;
distance_text = distance;
}
CustomAdapter(ArrayList<String> text, ArrayList<String> drinkSize,
ArrayList<String> price, ArrayList<Integer> percent,
ArrayList<String> objID, ArrayList<String> store,
ArrayList<String> address, ArrayList<Integer> distance) {
data_text = new String[text.size()];
size_text = new String[drinkSize.size()];
price_text = new String[price.size()];
percent_text = new Integer[percent.size()];
id_text = new String[objID.size()];
store_text = new String[store.size()];
address_text = new String[address.size()];
distance_text = new Integer[distance.size()];
for (int i = 0; i < text.size(); i++) {
data_text[i] = text.get(i);
size_text[i] = drinkSize.get(i);
price_text[i] = price.get(i);
percent_text[i] = percent.get(i);
id_text[i] = objID.get(i);
store_text[i] = store.get(i);
address_text[i] = address.get(i);
distance_text[i] = distance.get(i);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data_text.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.my_custom_dropdown, parent, false);
TextView textview = (TextView) row
.findViewById(R.id.textView_MainStore);
TextView size = (TextView) row.findViewById(R.id.textView_Size);
TextView price = (TextView) row.findViewById(R.id.textView_Price);
TextView percent = (TextView) row
.findViewById(R.id.textView_dist);
TextView store = (TextView) row
.findViewById(R.id.textView_Location);
textview.setText(data_text[position]);
size.setText(size_text[position]);
price.setText(price_text[position]);
percent.setText(String.valueOf(percent_text[position]) + "%");
store.setText(store_text[position]);
// Changes the color of the percent integer based on it's
// number...green if higher...red if lower
if (percent_text[position] >= 85)
percent.setTextColor(getResources().getColor(R.color.green));
else if (percent_text[position] >= 70
&& percent_text[position] <= 85)
percent.setTextColor(getResources().getColor(R.color.yellow));
else if (percent_text[position] >= 0
&& percent_text[position] <= 70)
percent.setTextColor(getResources().getColor(R.color.red));
return (row);
}
}
}
Sorry for the large block of code, but I've been stuck on this for a while.
Thank you!
Have you tried
adapter = new CustomAdapter(this, R.layout.listview, items);
setListAdapter(adapter);
rather than
listview.setAdapter(adapter);
? This worked for me when extending ArrayAdapter, rather than BaseAdapter which I had nothing but problems with. This tut helped immensely.
Related
I am trying to obtain some data from Parse.com through an AsyncTaskRunner. ANd then I intend to show them in a ListView. My custom adapter code is attached below :
public class ParseObjectAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mInflater;
List<ParseObject> parseArray;
DBShoppingHelper mydb2;
public ParseObjectAdapter(Context context, LayoutInflater inflater) {
mContext = context;
mInflater = inflater;
parseArray = new ArrayList<>();
}
#Override
public int getCount() {
try {
return parseArray.size();
}
catch (Exception e){
return 0;
}
}
#Override
public ParseObject getItem(int position) { return parseArray.get(position); }
#Override
public long getItemId(int position) {
return position;
}
public String getObjectId(int position){
return getItem(position).getObjectId();
}
public void sortByExpiry()
{
Comparator<ParseObject> comparator = new Comparator<ParseObject>() {
#Override
public int compare(ParseObject lhs, ParseObject rhs) {
return ((Integer) lhs.getInt("expiresIn")).compareTo(rhs.getInt("expiresIn"));
}
};
Collections.sort(parseArray, comparator);
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder;
// Inflate the custom row layout from your XML.
convertView = mInflater.inflate(R.layout.list_item, null);
// create a new "Holder" with subviews
holder = new ViewHolder();
holder.itemNameView = (TextView) convertView.findViewById(R.id.item_name);
holder.itemExpiryView = (TextView) convertView.findViewById(R.id.item_expiry);
// Taking care of the buttons
holder.editButton = (Button) convertView.findViewById(R.id.button_edit);
holder.deleteButton = (Button) convertView.findViewById(R.id.button_delete);
holder.shoppingListButton = (Button) convertView.findViewById(R.id.button_shopping);
// hang onto this holder for future recycling
convertView.setTag(holder);
int expiry = getItem(position).getInt("expiresIn");
if (expiry <= 0) {
holder.itemExpiryView.setTextColor(Color.rgb(255,80,54));
}
// Set listener on the buttons
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Edit Button CLicked", Toast.LENGTH_SHORT).show();
ParseObject p = getItem(position);
Intent goToAddItem = new Intent(mContext,ItemAddPage.class);
goToAddItem.putExtra("catg_passed", p.getString("category"));
goToAddItem.putExtra("update_flag", "YES");
goToAddItem.putExtra("name passed", p.getString("itemName"));
goToAddItem.putExtra("expires_in_passed", p.getString("expiresIn"));
goToAddItem.putExtra("price_passed", p.getString("itemPrice"));
mContext.startActivity(goToAddItem);
}
});
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseObject p = getItem(position);
String android_id = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
ParseQuery itemToBeDeleted = new ParseQuery("Items");
itemToBeDeleted.whereEqualTo("ACL", p.getACL());
itemToBeDeleted.whereEqualTo("objectId", p.getObjectId());
final Date deletionDate = new Date();
itemToBeDeleted.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> Items, com.parse.ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + Items.size() + " scores");
if (Items.size() == 1) {
ParseObject itemToDelete = Items.get(0);
itemToDelete.put("deleted", true);
itemToDelete.put("deletedOn", deletionDate);
itemToDelete.saveEventually();
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
parseArray.remove(p);
sortByExpiry();
notifyDataSetChanged();
Toast.makeText(mContext, "Item deleted", Toast.LENGTH_SHORT).show();
}
});
holder.shoppingListButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
ParseObject p = getItem(position);
String add_to_list = p.getString("itemName");
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
String add_date = sdf.format(new Date());
System.out.println(add_date);
mydb2.insertItem(add_to_list, add_date);
Toast.makeText(mContext, "Item added to shopping list", Toast.LENGTH_SHORT).show();
}
});
ParseObject p = getItem(position);
String name2 = p.getString("itemName");
Integer ex = p.getInt("expiresIn");
String days_s ="";
if (ex == 0) {
days_s = "Expires today" ;
}
else if (ex == -1) {
days_s = "Expired yesterday";
}
else if (ex < 0) {
days_s = "Expired " + Math.abs(ex) + " days ago";
}
else if (ex == 1) {
days_s = "Expires tomorrow";
}
else {
days_s = "Expires in " + ex + " days";
}
holder.itemNameView.setText(name2);
holder.itemExpiryView.setText(days_s);
return convertView;
}
public void onClick(View v)
{
Intent viewItem = new Intent(v.getContext(), ItemAddPage.class);
v.getContext().startActivity(viewItem);
}
private static class ViewHolder {
public TextView itemNameView;
public TextView itemExpiryView;
public Button editButton;
public Button deleteButton;
public Button shoppingListButton;
}
public void updateData(List<ParseObject> arrayPassed) {
// update the adapter's data set
parseArray = arrayPassed;
notifyDataSetChanged();
}
}
This is the method from which I am calling it..
public class WelcomeParse extends Activity {
ListView currentListView;
List<ParseObject> currentList;
ParseObjectAdapter itemAdder;
String catg;
DBShoppingHelper mydb2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.left_in, R.anim.right_out);
setTheme(android.R.style.Theme_Holo_Light_DarkActionBar);
setContentView(R.layout.activity_main);
itemAdder = new ParseObjectAdapter(this, getLayoutInflater());
mydb2 = new DBShoppingHelper(this);
AsyncTaskAllItems runner = new AsyncTaskAllItems();
runner.execute();
// itemAdder.notifyDataSetChanged();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
public class AsyncTaskAllItems extends AsyncTask<String, String, String> {
private String resp;
private Integer numItems = 0;
#Override
protected String doInBackground(String... params) {
try {
ParseQuery itemsAll = new ParseQuery("Items");
itemsAll.whereEqualTo("owner", ParseUser.getCurrentUser().getUsername());
// itemsByCategory.whereEqualTo("category", catg);
itemsAll.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> Items, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + Items.size() + " scores");
Log.d("owner", ParseUser.getCurrentUser().getUsername());
// HERE SIZE is 0 then 'No Data Found!'
numItems = Items.size();
if (numItems > 0) {
currentList = Items;
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
resp = "Done";
}
// catch (InterruptedException e) {
// e.printStackTrace();
// resp = e.getMessage();
// }
catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
currentListView.setAdapter(itemAdder);
// onWindowFocusChanged(true);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
}
I do not get any error and the log correctly shows the number of items that should be retrieved. But the view does not get updated with the relevant data.
COuld anyone please show me where I am wrong? Anything else you need, just let me know. Much appreciated.
Try after replacing
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
currentListView.setAdapter(itemAdder);
// onWindowFocusChanged(true);
}
With
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
currentListView.setAdapter(itemAdder);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
}
I am trying to write a program to select multiple items in the listview i populate. but I am having difficulty of selecting multiple items. Please let me know how to do it. Bellow is how i have populate the Arraylist and i have a custom row with checkbox. i need to get the selected items (name, number) on the button click event. Thank you in advance. I have tried to understand the other posts, but since i was unable to relate them to my code, i am not sure of how to do.
public class Contactselect extends Activity {
ListView lv;
EditText et;
int count;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
String phoneNumber;
String name;
String Name = "Contact";
String Phone = "Phonenumber";
TextWatcher search;
SimpleAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
listcontacts();
lv = (ListView) findViewById(R.id.contactlist);
lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE);
lv.setTextFilterEnabled(true);
adapter = new SimpleAdapter(this, list, R.layout.row, new String[] {
Name, Phone }, new int[] { R.id.names, R.id.numbers });
lv.setAdapter(adapter);
Button b = (Button) findViewById(R.id.done);
b.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
String selected = "";
int cntChoice = lv.getCount();
SparseBooleanArray sparseBooleanArray = lv
.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (sparseBooleanArray.get(i)) {
selected += lv.getItemAtPosition(i).toString() + "\n";
}
}
Toast.makeText(Contactselect.this, selected, Toast.LENGTH_LONG)
.show();
}
});
et = (EditText) findViewById(R.id.search);
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
Contactselect.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
private ArrayList<HashMap<String, String>> listcontacts() {
// TODO Auto-generated method stub
FileInputStream fis = null;
try {
fis = openFileInput("contacts.xml");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
XmlPullParserFactory factory;
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new InputStreamReader(fis));
int eventType = parser.getEventType();
int o = 0;
while (eventType != XmlPullParser.END_DOCUMENT) {
HashMap<String, String> map = new HashMap<String, String>();
// set flags for main tags.
if (eventType == XmlPullParser.START_DOCUMENT) {
} else if (eventType == XmlPullParser.START_TAG) {
String tag_name = parser.getName();
if (tag_name.contains("contacts")) {
// Log.i("tag",
// "name"
// + String.valueOf(parser
// .getAttributeValue(0))
// + "......................"
// + "number"
// + String.valueOf(parser
// .getAttributeValue(1)));
name = String.valueOf(parser.getAttributeValue(0));
phoneNumber = String.valueOf(parser
.getAttributeValue(1));
Log.i(name, phoneNumber);
map.put(Name, name);
map.put(Phone, phoneNumber);
list.add(map);
count++;
}
}
try {
eventType = parser.next();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.i("End document", "Ended" + count);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}
Try this way,hope this will help you to solve your problem.
public class Contactselect extends Activity {
private ListView lv;
private EditText et;
private Button b;
private int count;
private String Name = "Contact";
private String Phone = "Phonenumber";
private String IsSelected = "isSelected";
private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
private ContactAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.contactlist);
lv.setTextFilterEnabled(true);
et = (EditText) findViewById(R.id.search);
b = (Button) findViewById(R.id.done);
listcontacts();
adapter = new ContactAdapter(this,list);
lv.setAdapter(adapter);
b.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
String selected = "";
for (HashMap<String,String> row : list){
if(row.get(IsSelected).equals("true")){
selected += row.get(Name) + "\n";
}
}
Toast.makeText(Contactselect.this, selected, Toast.LENGTH_LONG)
.show();
}
});
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,int arg3) {
adapter.filter(cs.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
}
private void listcontacts() {
FileInputStream fis = null;
try {
fis = openFileInput("contacts.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
XmlPullParserFactory factory;
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new InputStreamReader(fis));
int eventType = parser.getEventType();
int o = 0;
while (eventType != XmlPullParser.END_DOCUMENT) {
HashMap<String, String> map = new HashMap<String, String>();
// set flags for main tags.
if (eventType == XmlPullParser.START_DOCUMENT) {
} else if (eventType == XmlPullParser.START_TAG) {
String tag_name = parser.getName();
if (tag_name.contains("contacts")) {
// Log.i("tag",
// "name"
// + String.valueOf(parser
// .getAttributeValue(0))
// + "......................"
// + "number"
// + String.valueOf(parser
// .getAttributeValue(1)));
Log.i(name, phoneNumber);
map.put(Name, String.valueOf(parser.getAttributeValue(0)));
map.put(Phone, String.valueOf(parser
.getAttributeValue(1)));
map.put(IsSelected,"false");
list.add(map);
count++;
}
}
try {
eventType = parser.next();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("End document", "Ended" + count);
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
class ContactAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> contacts;
public ContactAdapter(Context context,ArrayList<HashMap<String,String>> contacts) {
this.context =context;
this.contacts =new ArrayList<HashMap<String, String>>();
this.contacts.addAll(contacts);
}
#Override
public int getCount() {
return contacts.size();
}
#Override
public Object getItem(int position) {
return contacts.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.row, null);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.numbers = (TextView) convertView.findViewById(R.id.numbers);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(contacts.get(position).get(Name));
holder.numbers.setText(contacts.get(position).get(Phone));
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton ButtonView, boolean isChecked) {
contacts.get(position).put(IsSelected, "" + isChecked);
for (HashMap<String,String> data : list){
if(data.get(Name).equals(contacts.get(position).get(Name))){
data.put(IsSelected,contacts.get(position).get(IsSelected));
break;
}
}
notifyDataSetChanged();
}
});
if (contacts.get(position).get(IsSelected).toString().equals("false")) {
holder.checkbox.setChecked(false);
} else {
holder.checkbox.setChecked(true);
}
return convertView;
}
public void filter(String charText) {
contacts.clear();
if (charText.length() == 0) {
contacts.addAll(list);
} else {
for (HashMap<String,String> contact : list) {
if (contact.get(Name).toLowerCase().contains(charText.toLowerCase())) {
contacts.add(contact);
}
}
}
notifyDataSetChanged();
}
class ViewHolder {
TextView name;
TextView number;
CheckBox checkbox;
}
}
}
I am trying to use Endless listview adapter in application code but some how i am just not able to see any values in the listview. My code is running perfectly fine when using normal listview adapter. I an trying to use CWAC- endless adpater. I can get how to run it with my asynctask as it gives me blank screen after loding.
Below is my code for the some.
public class EndlessAdapterExample extends ListActivity {
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
static int LIST_SIZE;
private int mLastOffset = 0;
static final int BATCH_SIZE = 10;
ArrayList<EventsBean> countriesSub = new ArrayList<EventsBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try {
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
{
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "mu Url"
}
} catch (NullPointerException e) {
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
init();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
// TODO Auto-generated method stub
// Fetching the position from the listview which has been selected.
}
});
}
private void init() {
new FetchEventValues().execute();
}
private void setLastOffset(int i) {
mLastOffset = i;
}
private int getLastOffset(){
return mLastOffset;
}
private void displayList(ArrayList<EventsBean> countriesSub) {
setListAdapter(new DemoAdapter());
}
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Void, ArrayList<EventsBean>, ArrayList<EventsBean>>
{
ProgressDialog progressdialog = new ProgressDialog(EndlessAdapterExample.this);
ArrayList<EventsBean> merge = new ArrayList<EventsBean>();
ArrayList<EventsBean> localList;
public EventsBean eventsbean;
#SuppressLint("SimpleDateFormat")
#SuppressWarnings("unchecked")
#Override
protected ArrayList<EventsBean> doInBackground(Void... params) {
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try{
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
{
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
{
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
{
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
}
}
}
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
// #SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
}
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
}
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray){
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
cal = Calendar.getInstance();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
{
if (alldates.compareTo(today) > 0)
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
{
JSONObject jsonobjname = jsonArray.getJSONObject(i);
eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
{
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
}
if(!jsonobjname.isNull(Constants.COVER))
{
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
}
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
{
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
}
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
{
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
{
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
}
else
{
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
}
}
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
}
}
}
}catch(Exception e){
localList=null;
Log.e(TAG , "Exception Occured:" + e.getMessage());
}
return arrayEventsBeans;
}
class CompareDate implements Comparator<DateBean>{
#Override
public int compare(DateBean d1, DateBean d2) {
return d1.getDate().compareTo(d2.getDate());
}
}
#Override
protected void onPostExecute(ArrayList<EventsBean> result) {
super.onPostExecute(result);
if(this.progressdialog.isShowing())
{
this.progressdialog.dismiss();
}
// adapter = new SAmpleAdapter(EndlessAdapterExample.this,0, arrayEventsBeans);
//listview.setAdapter(adapter);
//displayList(arrayEventsBeans);
LIST_SIZE = arrayEventsBeans.size();
for (int i = 0; i <= BATCH_SIZE; i++) {
countriesSub.add(arrayEventsBeans.get(i));
}
setLastOffset(BATCH_SIZE);
displayList(countriesSub);
Log.i(TAG, "country list:" + countriesSub.size());
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
}
}
public class SAmpleAdapter extends ArrayAdapter<EventsBean> {
Context context;
public ArrayList<EventsBean> mOriginalvalues;
private ArrayList<EventsBean> mDisplayvalues;
ImageLoader imageloader;
public String datenew,datetime,date_text_value,timenew;
public int date_text,year;
public String time,month,description;
public LayoutInflater inflator = null;
public SAmpleAdapter(Context context, int resource, ArrayList<EventsBean> mEventarraylist) {
super(context, resource , mEventarraylist);
// TODO Auto-generated constructor stub
this.mOriginalvalues = mEventarraylist;
this.mDisplayvalues = mEventarraylist;
inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageloader=new ImageLoader(context.getApplicationContext());
getFilter();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mOriginalvalues.size();
}
#Override
public EventsBean getItem(int position) {
// TODO Auto-generated method stub
return mOriginalvalues.get(position);
}
#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
Holder viewHolder;
if(convertView == null)
{
viewHolder=new Holder();
convertView = inflator.inflate(R.layout.activity_list_items, parent, false);
viewHolder.txt_name = (TextView)convertView.findViewById(R.id.textname);
viewHolder.txt_owner_name = (TextView)convertView.findViewById(R.id.ownername);
viewHolder.txt_time = (TextView)convertView.findViewById(R.id.date);
viewHolder.txt_date = (TextView)convertView.findViewById(R.id.txt_date_value);
viewHolder.txt_month = (TextView)convertView.findViewById(R.id.txt_month_value);
viewHolder.txt_year = (TextView)convertView.findViewById(R.id.txt_year_value);
viewHolder.userimg = (ImageView)convertView.findViewById(R.id.imageView1);
convertView.setTag(viewHolder);
}
else
{
viewHolder=(Holder)convertView.getTag();
}
viewHolder.txt_name.setText(mOriginalvalues.get(position).getName());
viewHolder.txt_owner_name.setText(mOriginalvalues.get(position).getOwner_name());
String url = mOriginalvalues.get(position).getSource();
date_text_value = mOriginalvalues.get(position).getStart_time();
try {
parseDateFromString(date_text_value);
} catch (Exception e) {
Log.i("Adapter TAG", "Date Exception" + e.getMessage());
}
viewHolder.txt_date.setText(String.valueOf(date_text));
viewHolder.txt_month.setText(month);
viewHolder.txt_year.setText(String.valueOf(year));
Log.i("TEST", "Date:" + date_text_value);
imageloader.DisplayImage(url, viewHolder.userimg);
viewHolder.txt_time.setText(timenew);
return convertView;
}
public void resetData() {
mOriginalvalues = mDisplayvalues;
}
#SuppressLint("SimpleDateFormat")
public Date parseDateFromString(String aDateString){
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar c = Calendar.getInstance();
Date date= new Date();
try {
date= inputFormat.parse(aDateString);
System.out.println(date);
SimpleDateFormat day = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat time = new SimpleDateFormat("hh:mm a", Locale.getDefault());
SimpleDateFormat month_date = new SimpleDateFormat("MMM");
c.setTime(inputFormat.parse(aDateString));
System.out.println(day.format(date));
datenew = day.format(date).toString();
date_text = c.get(Calendar.DAY_OF_MONTH);
month = month_date.format(c.getTime());
year = c.get(Calendar.YEAR);
System.out.println("Year = " + c.get(Calendar.YEAR));
System.out.println("Month = " + month);
System.out.println("Day = " + date_text);
System.out.println(time.format(date));
timenew = time.format(date).toString();
} catch (ParseException e) {
Log.i("TAG", "DateFormat Pasring Error:" + e.getMessage());
}
return date;
}
private class Holder{
TextView txt_name;
TextView txt_owner_name ;
TextView txt_time;
TextView txt_date;
TextView txt_month;
TextView txt_year;
ImageView userimg;
}
}
class DemoAdapter extends EndlessAdapter {
private RotateAnimation rotate=null;
ArrayList<EventsBean> tempList = new ArrayList<EventsBean>();
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DemoAdapter() {
super(new SAmpleAdapter(EndlessAdapterExample.this,R.layout.sample_endless,countriesSub));
inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rotate=new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
#Override
protected View getPendingView(ViewGroup parent) {
View row=getLayoutInflater().inflate(R.layout.row, null);
View child=row.findViewById(R.id.textview1);
child.setVisibility(View.GONE);
child=row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return(row);
}
#Override
protected boolean cacheInBackground() {
tempList.clear();
int lastOffset = getLastOffset();
if(lastOffset < LIST_SIZE){
int limit = lastOffset + BATCH_SIZE;
for(int i=(lastOffset+1); (i<=limit && i<LIST_SIZE); i++){
tempList.add(arrayEventsBeans.get(i));
}
setLastOffset(limit);
if(limit<LIST_SIZE){
return true;
} else {
return false;
}
} else {
return false;
}
}
#SuppressLint("NewApi")
#Override
protected void appendCachedData() {
#SuppressWarnings("unchecked")
ArrayAdapter<EventsBean> arrAdapterNew = (ArrayAdapter<EventsBean>)getWrappedAdapter();
int listLen = tempList.size();
for(int i=0; i<listLen; i++){
arrAdapterNew.addAll(tempList.get(i));
}
}
}
}
I have updated my code. I guess my problem now is with the custom adapter as it gives me multiple values after it reaches the end of the listview. Initially i do get 10 values but after the update it gets same 10 values again but the count reaches to 121.
Replace your init() as below,
private void init() {
new FetchEventValues().execute();
}
and replace onPostExecute() with below,
#Override
protected void onPostExecute(ArrayList<EventsBean> result) {
super.onPostExecute(result);
if (this.progressdialog.isShowing()) {
this.progressdialog.dismiss();
}
// adapter = new SAmpleAdapter(EndlessAdapterExample.this,0,
// arrayEventsBeans);
// listview.setAdapter(adapter);
LIST_SIZE = arrayEventsBeans.size();
for (int i = 0; i <= BATCH_SIZE; i++) {
countriesSub.add(arrayEventsBeans.get(i));
}
setLastOffset(BATCH_SIZE);
displayList(countriesSub);
}
I am expirience wierd situation because my list view updates only once.
The idia is following, i want to download posts from web, which are located on page 3 and page 5 and show both of them on listview. However, List view shows posts only from page 3. MEanwhile, log shows that all poast are downloded and stored in addList.
So the problem - objects from second itteration are not shown in listview. Help me please to fix this issue.
public class MyAddActivateActivity extends ErrorActivity implements
AddActivateInterface {
// All static variables
// XML node keys
View footer;
public static final String KEY_ID = "not_id";
public static final String KEY_TITLE = "not_title";
Context context;
public static final String KEY_PHOTO = "not_photo";
public final static String KEY_PRICE = "not_price";
public final static String KEY_DATE = "not_date";
public final static String KEY_DATE_TILL = "not_date_till";
private int not_source = 3;
JSONObject test = null;
ListView list;
MyAddActivateAdapter adapter;
ArrayList<HashMap<String, String>> addList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.aadd_my_add_list_to_activate);
footer = getLayoutInflater().inflate(R.layout.loading_view, null);
addList = new ArrayList<HashMap<String, String>>();
ImageView back_button = (ImageView) findViewById(R.id.imageView3);
back_button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(i);
finish();
}
});
Intent intent = this.getIntent();
// if (intent != null) {
// not_source = intent.getExtras().getInt("not_source");
// }
GAdds g = new GAdds();
g.execute(1, not_source);
list = (ListView) findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new MyAddActivateAdapter(this, addList);
list.addFooterView(footer);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String add_id = ((TextView) view
.findViewById(R.id.tv_my_add_id)).getText().toString();
add_id = add_id.substring(4);
Log.d("ADD_ID", add_id);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(),
AddToCheckActivity.class);
// sending data to new activity
UILApplication.advert.setId(add_id);
startActivity(i);
finish();
}
});
}
private void emptyAlertSender() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Ничего не найдено");
alertDialog.setMessage("У вас нет неактивных объявлений.");
alertDialog.setButton("на главную",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(intent);
finish();
}
});
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
}
class GAdds extends AsyncTask<Integer, Void, JSONObject> {
#Override
protected JSONObject doInBackground(Integer... params) {
// addList.clear();
Log.d("backgraund", "backgraund");
UserFunctions u = new UserFunctions();
return u.getAdds(params[0] + "", params[1] + "");
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
Log.d("postexecute", "postexecute");
footer.setVisibility(View.GONE);
JSONArray tArr = null;
if (result != null) {
try {
tArr = result.getJSONArray("notices");
for (int i = 0; i < tArr.length(); i++) {
JSONObject a = null;
HashMap<String, String> map = new HashMap<String, String>();
a = (JSONObject) tArr.get(i);
if (a.getInt("not_status") == 0) {
int premium = a.getInt("not_premium");
int up = a.getInt("not_up");
if (premium == 1 && up == 1) {
map.put("status", R.drawable.vip + "");
} else if (premium == 1) {
map.put("status", R.drawable.prem + "");
} else if (premium != 1 && up == 1) {
map.put("status", R.drawable.up + "");
} else {
map.put("status", 0 + "");
}
map.put(KEY_ID, "ID: " + a.getString(KEY_ID));
map.put(KEY_TITLE, a.getString(KEY_TITLE));
map.put(KEY_PRICE,
"Цена: " + a.getString(KEY_PRICE) + " грн.");
map.put(KEY_PHOTO, a.getString(KEY_PHOTO));
map.put(KEY_DATE,
"Создано: " + a.getString(KEY_DATE));
map.put(KEY_DATE_TILL,
"Действительно до: "
+ a.getString(KEY_DATE_TILL));
map.put("check", "false");
Log.d("MyAddList", "map was populated");
}
if (map.size() > 0)
{
addList.add(map);
Log.d("MyAddList", "addlist was populated");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (UILApplication.login != 2) {
UILApplication.login = 3;
}
onCreateDialog(LOST_CONNECTION).show();
}
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
if (not_source == 3) {
not_source = 5;
GAdds task = new GAdds();
task.execute(1, 5);
}
if (not_source == 5) {
Log.d("ID", m.get(KEY_ID));
if (addList.size() == 0) {
emptyAlertSender();
}
}
}
}
#SuppressWarnings("unchecked")
public void addAct(View v) {
AddActivate aAct = new AddActivate(this);
aAct.execute(addList);
}
#Override
public void onAddActivate(JSONObject result) {
if (result != null) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
}
adapter
public class MyAddActivateAdapter extends BaseAdapter {
private List<Row> rows;
private ArrayList<HashMap<String, String>> data;
private Activity activity;
public MyAddActivateAdapter(Activity activity,
ArrayList<HashMap<String, String>> data) {
Log.d("mediaadapter", "listcreation: " + data.size());
rows = new ArrayList<Row>();// member variable
this.data = data;
this.activity = activity;
}
#Override
public int getViewTypeCount() {
return RowType.values().length;
}
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
}
#Override
public int getItemViewType(int position) {
return rows.get(position).getViewType();
}
public int getCount() {
return rows.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
return rows.get(position).getView(convertView);
}
}
I think the problem is you aren't calling the super class of notifyDataSetChanged(), maybe try
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
super.notifyDataSetChanged();
}
My code is following ...
public class NameListActivity extends Activity implements TextWatcher {
private Button add = null;
private AutoCompleteTextView editAuto = null;
private Button chfrlist = null;
private ImageView im = null;
String access_token = new String();
private ImageView infobtn = null;
private PopupWindow popupWindow;
private View view;
private ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_name_list);
access_token = MainService.readToken();
add = (Button) findViewById(R.id.add_button);
editAuto = (AutoCompleteTextView) findViewById(R.id.editAuto);
chfrlist = (Button) findViewById(R.id.chfrlistbutton);
im = (ImageView) findViewById(R.id.helpact);
im.setOnClickListener(new ImageListener());
infobtn = (ImageView) findViewById(R.id.informbtn);
initPopupWindow();
infobtn.setOnClickListener(new infobtnListener());
editAuto.addTextChangedListener(this);
add.setOnClickListener(new addListener());
chfrlist.setOnClickListener(new ChfrListListener());
}
public class addListener implements OnClickListener {
public void onClick(View v) {
addTask task = new addTask();
task.execute();
editAuto.setText("");
}
}
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
onTextChangedTask task = new onTextChangedTask();
task.execute();
}
public class onTextChangedTask extends AsyncTask<Void, Void, Void> {
ArrayAdapter<String> adapter = null;
String[] userName = null;
String q = null;
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;
ArrayList<String> userNameArrayList = new ArrayList<String>();
Weibo weibo = new Weibo();
#Override
protected void onPreExecute() {
weibo.setToken(access_token);
q = editAuto.getText().toString();
System.out.println("start onTextChanged");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (q.length() != 0) {
System.out.println("q is " + q);
String s1 = "https://api.weibo.com/search/suggestions/users.json";
try {
jsonArray = Weibo.client.get(s1,
new PostParameter[] { new PostParameter("q", q) })
.asJSONArray();
} catch (Throwable e) {
System.out.println("这里有个神马异常呢 。。。" + e);
}
System.out.println("return length is " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
try {
jsonObject = jsonArray.getJSONObject(i);
String sname = jsonObject.getString("screen_name");
userNameArrayList.add(sname);
} catch (JSONException e) {
e.printStackTrace();
}
}
userName = (String[]) userNameArrayList
.toArray(new String[userNameArrayList.size()]);
adapter = new ArrayAdapter<String>(NameListActivity.this,
android.R.layout.simple_dropdown_item_1line, userName);
}
return null;
}
#Override
protected void onPostExecute(Void v) {
System.out.println("post");
editAuto.setAdapter(adapter);
}
}
void showToast(String s) {
Toast toast = Toast.makeText(getApplicationContext(), s,
Toast.LENGTH_LONG);
toast.show();
}
public class addTask extends AsyncTask<Void, Void, Void> {
String s = null;
boolean flag = false;
User user = null;
Weibo weibo = new Weibo();
String screen_name = null;
protected void onPreExecute() {
Toast tt = Toast.makeText(getApplicationContext(), "正在将用户添加到备份名单",
Toast.LENGTH_LONG);
tt.setGravity(Gravity.CENTER, 0, 0);
tt.show();
weibo.setToken(access_token);
screen_name = editAuto.getText().toString();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (screen_name.length() != 0) {
Users um = new Users();
try {
user = new User(Weibo.client.get(
"https://api.weibo.com/users/show.json",
new PostParameter[] { new PostParameter(
"screen_name", screen_name) })
.asJSONObject());
} catch (Throwable e) {
e.printStackTrace();
flag = true;
s = new String("您输入的这个用户好像不存在唉");
}
if (user != null) {
ContentValues values = new ContentValues();
values.put("uid", user.getId());
values.put("user_name", user.getName());
SQLiteDatabase db = null;
try {
db = MainService.getDatabase();
} catch (Exception e) {
System.out.println("db error");
finish();
}
Cursor result = db.query("users", new String[] { "uid",
"user_name" }, "uid=?",
new String[] { user.getId() }, null, null, null);
if (result.getCount() == 0)
db.insert("users", null, values);
} else {
flag = true;
s = new String("网络存在问题,检查一下吧");
}
} else {
flag = true;
s = new String("框里输入点东西才能添加啊");
}
return null;
}
#Override
protected void onPostExecute(Void v) {
if (flag == true) {
System.out.println("要打印的是" + s);
showToast(s);
}
}
}
public class infobtnListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("点击了图片");
ColorDrawable cd = new ColorDrawable(-0000);
popupWindow.setBackgroundDrawable(cd);
// popupWindow.showAsDropDown(v);
popupWindow.showAtLocation(findViewById(R.id.informbtn),
Gravity.LEFT | Gravity.BOTTOM, 0, 100);
}
}
public class ImageListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent t = new Intent(NameListActivity.this,
// GridLayoutActivity.class);
// startActivity(t);
finish();
}
}
public class ChfrListListener implements OnClickListener {
public void onClick(View v) {
if ((haveInternet() == true)
&& (GridLayoutActivity.hasAccessToken() == true)) {
// TODO Auto-generated method stub
pd = ProgressDialog.show(NameListActivity.this, "",
"正在从服务器上获取数据,可能需要较长时间,请耐心等待 ...");
/* 开启一个新线程,在新线程里执行耗时的方法 */
new Thread(new Runnable() {
public void run() {
Intent t = new Intent(NameListActivity.this,
ChooseFromListActivity.class);
startActivity(t);
finish();
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
}).start();
} else {
Intent t = new Intent(NameListActivity.this,
WebViewActivity.class);
startActivity(t);
finish();
}
}
}
private void initPopupWindow() {
view = getLayoutInflater().inflate(R.layout.namewindow, null);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// 这里设置显示PopuWindow之后在外面点击是否有效。如果为false的话,那么点击PopuWindow外面并不会关闭PopuWindow。
popupWindow.setOutsideTouchable(true);// 不能在没有焦点的时候使用
}
private boolean haveInternet() {
NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return true;
}
return true;
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
pd.dismiss();// 关闭ProgressDialog
}
};
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_name_list, menu);
return true;
}
}
My question is : when I input words in the EditText, nothing happened. But when I press backspace did the AutoCompleteTextView show the suggestion list ... the problem is in the editAuto.setAdapter(adapter);
What is wrong?
make the following changes in your code
1) Instead of
private AutoCompleteTextView editAuto = null; JUST WRITE private AutoCompleteTextView editAuto;
2) Add this line to onCrate()
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, <your array name here>);
and remove this line from onTextChangedTask()
ArrayList<String> userNameArrayList = new ArrayList<String>();
3) Add this line to onCrate()
editAuto.setAdapter(adapter);
I know this is way late but for those who face similar problems here is the solution to show the autoCompleteTextView's drop down whenever you want i.e on button click or onTextChanged. After you set the ArrayAdapter for the autoCompleteTextView just put the following line.
autoCompleteTextView.showDropDown();