I have a ListView of over 1000 items, this list is filterable by a Search function in my Adapter, when clicking on an item it replace the current fragment (The one with the list(A)) with a detail fragment (B). Upon the user pressing back or returning to the previous fragment (B) there are duplicate list items.
Any ideas??
public class HallsInStateAdapter extends BaseAdapter implements Filterable {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private ArrayList<HashMap<String, String>> orginalData;
private static LayoutInflater inflater=null;
private Filter hallFilter;
public HallsInStateAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
setData(d);
this.orginalData = d;
}
public int getCount() {
return getData().size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.hall_list_view, null);
TextView hallName = (TextView)vi.findViewById(R.id.hallName);
TextView hallSuburb = (TextView)vi.findViewById(R.id.hallAddress);
ImageView hallFavIcon = (ImageView)vi.findViewById(R.id.hallFavouriteIcon);
HashMap<String, String> listData = new HashMap<String, String>();
listData = getData().get(position);
String address = listData.get(HallsInStateFragment.KEY_HALL_ADDRESS);
String suburb = listData.get(HallsInStateFragment.KEY_SUBURB);
String state = listData.get(HallsInStateFragment.KEY_STATE);
String objectID = listData.get(HallsInStateFragment.KEY_OBJECTID);
hallName.setText(address);
hallSuburb.setText(suburb + ", " + state);
hallFavIcon.setVisibility(View.INVISIBLE);
boolean isFavourite = false;
DatabaseHandler db = new DatabaseHandler(activity);
List<Favourite> favs = db.getAllFavourites();
for (int i = 0; i < favs.size(); i++){
if(favs.get(i).getObjectId().equals(objectID)){
isFavourite = true;
break;
}
else {
isFavourite = false;
}
}
db.close();
if (isFavourite == true){
hallFavIcon.setVisibility(View.VISIBLE);
}
return vi;
}
public android.widget.Filter getFilter() {
if (hallFilter == null)
hallFilter = new HallFilter();
return hallFilter;
}
public ArrayList<HashMap<String, String>> getData() {
return data;
}
public void setData(ArrayList<HashMap<String, String>> data) {
this.data = data;
}
private class HallFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// We implement here the filter logic
if (constraint == null || constraint.length() == 0) {
// No filter implemented we return all the list
results.values = orginalData;
results.count = orginalData.size();
}
else {
// We perform filtering operation
final ArrayList<HashMap<String, String>> filteredLocations = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < orginalData.size(); i ++) {
HashMap<String, String> halls = new HashMap<String, String>();
halls.put(HallsInStateFragment.KEY_OBJECTID, orginalData.get(i).get(HallsInStateFragment.KEY_OBJECTID));
String name = orginalData.get(i).get(HallsInStateFragment.KEY_NAME);
String prefix = orginalData.get(i).get(HallsInStateFragment.KEY_PREFIX);
String address = null;
if(prefix == null || prefix.length() == 0){
address = name;
}
else {
address = prefix + " " + name;
}
halls.put(HallsInStateFragment.KEY_NAME, name);
halls.put(HallsInStateFragment.KEY_PREFIX, prefix);
halls.put(HallsInStateFragment.KEY_HALL_ADDRESS, address);
halls.put(HallsInStateFragment.KEY_STREET, orginalData.get(i).get(HallsInStateFragment.KEY_STREET));
halls.put(HallsInStateFragment.KEY_SUBURB, orginalData.get(i).get(HallsInStateFragment.KEY_SUBURB));
halls.put(HallsInStateFragment.KEY_STATE, orginalData.get(i).get(HallsInStateFragment.KEY_STATE));
halls.put(HallsInStateFragment.KEY_POSTCODE, orginalData.get(i).get(HallsInStateFragment.KEY_POSTCODE));
halls.put(HallsInStateFragment.KEY_LATITUDE, orginalData.get(i).get(HallsInStateFragment.KEY_LATITUDE));
halls.put(HallsInStateFragment.KEY_LONGITUDE, orginalData.get(i).get(HallsInStateFragment.KEY_LONGITUDE));
halls.put(HallsInStateFragment.KEY_TYPE, orginalData.get(i).get(HallsInStateFragment.KEY_TYPE));
String query = constraint.toString().toLowerCase();
String suburb = orginalData.get(i).get(HallsInStateFragment.KEY_SUBURB);
if(name == null || name.length() == 0){
Log.e("SGL", "NULL");
}
else {
if (name.toLowerCase().contains(query) || suburb.toLowerCase().contains(query)) {
Log.i("SGL-QUERY", query);
filteredLocations.add(halls);
}
}
results.values = filteredLocations;
results.count = filteredLocations.size();
}
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//Now we have to inform the adapter about the new list filtered
if (results.count == 0)
notifyDataSetInvalidated();
else {
setData((ArrayList<HashMap<String, String>>) results.values);
notifyDataSetChanged();
}
}
}
}
Yes, before filling your list array, clear your arraylist so last added data will be void and eveytime it will load new data in your arraylist.
Note: An arraylist which you filling before passing to adapter to fill your listview. Hope it make sense
Related
I have AutoCompletTextView and i want do apply some customize filetring to it for this i have this code
public class ATCAdapter extends ArrayAdapter<String> implements Filterable {
ArrayList<String> _items = new ArrayList<String>();
ArrayList<String> orig = new ArrayList<String>();
public ATCAdapter(Context context, int resource, ArrayList<String> items) {
super(context, resource, items);
for (int i = 0; i < items.size(); i++) {
orig.add(items.get(i));
}
}
#Override
public int getCount() {
if (_items != null)
return _items.size();
else
return 0;
}
#Override
public String getItem(int arg0) {
return _items.get(arg0);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if(constraint != null) {
Log.d("Constraints", constraint.toString());
}
FilterResults oReturn = new FilterResults();
/* if (orig == null){
for (int i = 0; i < items.size(); i++) {
orig.add(items.get(i));
}
}*/
String temp;
int counters = 0;
if (constraint != null){
_items.clear();
if (orig != null && orig.size() > 0) {
for(int i=0; i<orig.size(); i++)
{
temp = orig.get(i).toUpperCase();
if(temp.startsWith(constraint.toString().toUpperCase()))
{
_items.add(orig.get(i));
counters++;
}
}
}
Log.d("REsult size:" , String.valueOf(_items.size()));
if(counters != 0)
{
_items.clear();
_items = orig;
}
oReturn.values = _items;
oReturn.count = _items.size();
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if(results != null && results.count > 0) {
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
and this is how i am setting adapter for
AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
ArrayAdapter adapter = new ATCAdapter(this, android.R.layout.simple_list_item_1, new ArrayList<>(Arrays.asList(languages)));
autoCompleteTextView.setThreshold(1);
autoCompleteTextView.setAdapter(adapter);
Now the problem is i always get null parameter in performFiletring(), Any reason why it's happening ?
IHMO, your code has a problem at
if(counters != 0)
{
_items.clear();
_items = orig;
}
I suggest you update your code as the following:
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
Log.d("Constraints", constraint.toString());
}
FilterResults oReturn = new FilterResults();
String temp;
int counters = 0;
if (constraint != null && constraint.length() > 0) {
_items.clear();
if (orig != null && orig.size() > 0) {
for (int i = 0; i < orig.size(); i++) {
temp = orig.get(i).toUpperCase();
if (temp.startsWith(constraint.toString().toUpperCase())) {
_items.add(orig.get(i));
counters++;
}
}
}
Log.d("Result size:", String.valueOf(_items.size()));
if (counters == 0) {
_items = new ArrayList<>(orig);
}
oReturn.values = _items;
oReturn.count = _items.size();
} else {
_items = new ArrayList<>(orig);
oReturn.values = _items;
oReturn.count = _items.size();
}
return oReturn;
}
and the constructor:
public ATCAdapter(Context context, int resource, ArrayList<String> items) {
super(context, resource, items);
for (int i = 0; i < items.size(); i++) {
orig.add(items.get(i));
}
_items = new ArrayList<>(orig); // ADD THIS LINE
}
I Have a doubt in my autocomplete textview. Here i am trying to filter the listview based on the text that is typed in the autocomplete textview. I am getting the values from json parsing. The auto complete textview shows all its values correctly in the drop down list. But in the listview i see no changes in it.
Below is my adapter code for the listview:
public class EventListAdapter extends BaseAdapter implements Filterable {
public static LayoutInflater inflator = null;
private ArrayList<EventsBean> mOriginalvalues = new ArrayList<EventsBean>();
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 EventListAdapter( ArrayList<EventsBean> mEventarraylist,Activity activity) {
super();
//this.context = context;
this.mOriginalvalues = mEventarraylist;
inflator =(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageloader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mOriginalvalues.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return 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
View holder;
holder = inflator.inflate(R.layout.activity_list_items, parent, false);
TextView txt_name = (TextView)holder.findViewById(R.id.textname);
TextView txt_owner_name = (TextView)holder.findViewById(R.id.ownername);
TextView txt_time = (TextView)holder.findViewById(R.id.date);
TextView txt_date = (TextView)holder.findViewById(R.id.txt_date_value);
TextView txt_month = (TextView)holder.findViewById(R.id.txt_month_value);
TextView txt_year = (TextView)holder.findViewById(R.id.txt_year_value);
ImageView userimg = (ImageView)holder.findViewById(R.id.imageView1);
txt_name.setText(mOriginalvalues.get(position).getName());
txt_owner_name.setText(mOriginalvalues.get(position).getOwner_name());
String url = mOriginalvalues.get(position).getSource();
date_text_value = mOriginalvalues.get(position).getStart_time();
parseDateFromString(date_text_value);
txt_date.setText(String.valueOf(date_text));
txt_month.setText(month);
txt_year.setText(String.valueOf(year));
Log.i("TEST", "Date:" + date_text_value);
Log.i("TAG", "Country:" + mOriginalvalues.get(position).getCountry());
imageloader.DisplayImage(url, userimg);
txt_time.setText(timenew);
//userimg.getFitsSystemWindows();
return holder;
}
#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;
}
#SuppressLint("DefaultLocale")
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// TODO Auto-generated method stub
mOriginalvalues = (ArrayList<EventsBean>) results.values; // has the filtered values
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<EventsBean> FilteredArrList = new ArrayList<EventsBean>();
if (mDisplayvalues == null) {
mDisplayvalues = new ArrayList<EventsBean>(mOriginalvalues); // saves the original data in mOriginalValues
System.out.println("Display Value:" + mDisplayvalues.size());
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mDisplayvalues.size();
results.values = mDisplayvalues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mDisplayvalues.size(); i++) {
EventsBean data = mDisplayvalues.get(i);
System.out.println("Display Value 2:" + mDisplayvalues.size());
if (data.getLocation_city().toLowerCase().startsWith(constraint.toString())
|| data.getLocation_country().toLowerCase().startsWith(constraint.toString())
|| data.getLocation_state().toLowerCase().startsWith(constraint.toString()))
{
FilteredArrList.add(new EventsBean(mDisplayvalues.get(i).getLocation_city(),mDisplayvalues.get(i).getLocation_country(),
mDisplayvalues.get(i).getLocation_state()));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
I am getting a nullpointer error everytime i try to write some text in my autocomplete textview in my getCount() of my adapter. I have 3 different values in my autocomplete textview state,country and city which are stored in the arraylist.
I have seen lot of examples on net but they all have autocomplete textview values having only one value but i have three how do i filter the listview with them??
Pleae help me in solving up my nullpointer error.
I could solve my problem by making the changes in the getView(). I was getting NullPointer due to wrong getView() contents. but it works fine now.
I was searching on google and stackover could not find the exact solution.
My problem is that, I have a ArrayList<String> adapter and it has
Gatewick London England
Ory Paris France
Heathrow London England
If user enters "Lon" into AutoCompleteTextView then I have to display line number 1 and 3. Because these have London string.
I tried this link and i pasted code here but it gives warning on line #57
String prefix = constraint.toString().toLowerCase();
PkmnAdapter
public class PkmnAdapter extends ArrayAdapter<String> {
private ArrayList<Pkmn> original;
private ArrayList<Pkmn> fitems;
private Filter filter;
public PkmnAdapter(Context context, int textViewResourceId,
ArrayList<Pkmn> items) {
super(context, textViewResourceId);
this.original = new ArrayList<Pkmn>(items);
this.fitems = new ArrayList<Pkmn>(items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Pkmn pkmn = fitems.get(position);
if (pkmn != null) {
TextView tt = (TextView) v.findViewById(R.id.RlabPName);
if (tt != null) {
tt.setText(pkmn.getNAME());
}
}
return v;
}
#Override
public Filter getFilter() {
if (filter == null)
filter = new PkmnNameFilter();
return filter;
}
private class PkmnNameFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String prefix = constraint.toString().toLowerCase();
if (prefix == null || prefix.length() == 0) {
ArrayList<Pkmn> list = new ArrayList<Pkmn>(original);
results.values = list;
results.count = list.size();
} else {
final ArrayList<Pkmn> list = new ArrayList<Pkmn>(original);
final ArrayList<Pkmn> nlist = new ArrayList<Pkmn>();
int count = list.size();
for (int i = 0; i < count; i++) {
final Pkmn pkmn = list.get(i);
final String value = pkmn.getNAME().toLowerCase();
if (value.startsWith(prefix)) {
nlist.add(pkmn);
}
}
results.values = nlist;
results.count = nlist.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
fitems = (ArrayList<Pkmn>) results.values;
clear();
if (fitems != null) {
int count = fitems.size();
for (int i = 0; i < count; i++) {
Pkmn pkmn = (Pkmn) fitems.get(i);
fitems.add(pkmn);
}
}
}
}
}
MainActivity.java to put adapter
Pkmn[] item = new Pkmn[4];
item[0] = new Pkmn("Gatewick London England");
item[1] = new Pkmn("Ory Paris France");
item[2] = new Pkmn("Heathrow London England");
item[3] = new Pkmn("Ataturk Istanbul Turkey");
ArrayList<Pkmn> list = new ArrayList<Pkmn>(Arrays.asList(item));
MultiAutoCompleteTextView auto = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView1);
PkmnAdapter adap = new PkmnAdapter(this,android.R.layout.simple_list_item_1, list);
First of all, if you enter "Lon" you should not check if the elements start with "Lon". Probably you need to switch the if statement to:
if (value.contains(prefix)) {
nlist.add(pkmn);
}
Before you perform any filtering in your performFiltering() method check if the constraint is null (Hint: use TextUtils class). If so, then return original data. Therefore you are avoiding NPE. You also need to pay attention to critical points where NPE can be thrown like this one:
if (prefix == null || prefix.length() == 0) { }
Cheers,
I am working with Section list view in Android to show Call details according to date.
Means under a particular date number of call details. But when I get 2 calls under the same date, the last date is visible only and the list does not show the rest of the calls of that date.
Calls under different dates are shown correctly but calls under same date are not shown correctly, only the last call is shown.
I am using the below code:
public String response = "{ \"Message\":\"Success\", "
+ "\"Data\":[ { \"ACCOUNT\":\"000014532497\", "
+ "\"DATE\":\"8/6/2006\", \"TIME\":\"15:37:14\", "
+ "\"CH_ITEM\":\"341T\", \"ITEM\":\"TIMEUSED\", "
+ "\"DESCRIPTION\":\"FROM3103475779\", \"DETAIL\":"
+ "\"UnitedKingdom011441980849463\", \"QUANTITY\":84, "
+ "\"RATE\":0.025, \"AMOUNT\":2.1, \"ACTUAL\":83.2, "
+ "\"NODE_NAME\":\"TNT02\", \"USER_NAME\":\"Shailesh Sharma\""
+ ", \"MODULE_NAME\":\"DEBIT\", \"ANI\":\"3103475779\", "
+ "\"DNIS\":\"3103210104\", \"ACCOUNT_GROUP\":\"WEBCC\", "
+ "\"SALES_REP\":\"sascha_d\", \"SALES_REP2\":\"\", \"SALES_REP3"
+ "\":\"\", \"IN_PORT\":\"I10\", \"EXTRA1\":\"RATE\", \"EXTRA2\":"
+ "\"44\", \"EXTRA3\":\"UnitedKingdom\", \"OUT_PORT\":\"I70\", "
+ "\"CRN\":\"WEBCC\", \"CallId\":null, \"ID\":4517734, \"PhoneNumber"
+ "\":\"011441980849463\" }, {\"ACCOUNT\":\"000014532497\",\"DATE\":"
+ "\"8/6/2006\",\"TIME\":\"09:22:57\",\"CH_ITEM\":\"541T\",\"ITEM\":"
+ "\"TIMEUSED\",\"DESCRIPTION\":\"FROM3103475779\",\"DETAIL\":"
+ "\"UnitedKingdom011447914422787\",\"QUANTITY\":1,\"RATE\":0.29,"
+ "\"AMOUNT\":0.29,\"ACTUAL\":0.5,\"NODE_NAME\":\"TNT02\",\"USER_NAME"
+ "\":\"Tusshar\",\"MODULE_NAME\":\"DEBIT\",\"ANI\":\"3103475779\",\"DNIS"
+ "\":\"6173950047\",\"ACCOUNT_GROUP\":\"WEBCC\",\"SALES_REP\":\"sascha_d"
+ "\",\"SALES_REP2\":\"\",\"SALES_REP3\":\"\",\"IN_PORT\":\"I30\",\"EXTRA1"
+ "\":\"RATE\",\"EXTRA2\":\"44\",\"EXTRA3\":\"UnitedKingdom-Special\","
+ "\"OUT_PORT\":\"I90\",\"CRN\":\"WEBCC\",\"CallId\":null,\"ID\":4535675,"
+ "\"PhoneNumber\":\"011447914422787\"}, ], \"NumberOfContacts\":2, "
+ "\"TotalCharges\":4.830000000000001 }";
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if (message != null && message.equalsIgnoreCase("Success")) {
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
for (int i = 0; i < dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
_date = history.getString("DATE");
String updatedDate = createDateFormat(_date);
// notes =new ArrayList<String>();
itemList = new ArrayList<Object>();
// ADDING DATE IN THE ARRAYLIST<String>
days.add(updatedDate);
_username = history.getString("USER_NAME");
_number = history.getString("PhoneNumber");
_time = history.getString("TIME");
_amount = history.getString("AMOUNT");
_duration = history.getString("QUANTITY");
/*
* notes.add(_username); notes.add(_number);
* notes.add(_time);
*/
AddObjectToList(_username, _number, _time, _amount,
_duration);
// listadapter = new <String>(this, R.layout.list_item,
// notes);
listadapter = new ListViewCustomAdapter(this, itemList);
adapter.addSection(days.get(i), listadapter);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SeparatedListAdapter extends BaseAdapter {
/*
* public final Map<String, Adapter> sections = new
* LinkedHashMap<String, Adapter>();
*/
public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
public final ArrayAdapter<String> headers;
public final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public void addSection(String section, Adapter adapter) {
this.headers.add(section);
this.sections.put(section, adapter);
}
public Object getItem(int position) {
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return section;
if (position < size)
return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : this.sections.values())
total += adapter.getCount() + 1;
return total;
}
#Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : this.sections.values())
total += adapter.getViewTypeCount();
return total;
}
#Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return TYPE_SECTION_HEADER;
if (position < size)
return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
public boolean areAllItemsSelectable() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return headers.getView(sectionnum, convertView, parent);
if (position < size)
return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
#Override
public long getItemId(int position) {
return position;
}
}
This is my actual requirement:
This is what is happening right now.
SectionListExampleActivity is my Main class in which I am getting RESPONSE from JSON web service. In getJSONResposne method I am calling the EntryAdaptor.
There are two separate geter setter classes for SECTION HEADER and ITEM ENTRY for each header.
public class SectionListExampleActivity extends Activity implements OnClickListener, OnItemSelectedListener, IServerResponse {
/** Called when the activity is first created. */
private ArrayList<Item> items = new ArrayList<Item>();
boolean firstTime = true;
private Spinner _spinner=null;
private ArrayAdapter _amountAdaptor = null;
private ArrayList<String> _monthList =new ArrayList<String>();
private ListView _list=null;
private Button _monthButton=null;
private ImageButton _backImageButton=null;
private ImageButton _headerImageButton=null;
private String _token;
private String _account;
private Point p=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_history);
String response = this.getIntent().getExtras().getString("history_resp");
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
_list = (ListView)findViewById(R.id.listview);
getJSON_Response(response,Constant.PID_ACCOUNT_HISTORY);
EntryAdapter adapter = new EntryAdapter(this, items);
_list.setAdapter(adapter);
_monthList.add("Months");
_monthList.add("January");
_monthList.add("February");
_monthList.add("March");
_monthList.add("April");
_monthList.add("May");
_monthList.add("June");
_monthList.add("July");
_monthList.add("August");
_monthList.add("September");
_monthList.add("October");
_monthList.add("November");
_monthList.add("December");
_spinner = (Spinner)findViewById(R.id.month_spinner);
_amountAdaptor = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
_monthList);
_spinner.setAdapter(_amountAdaptor);
_spinner.setOnItemSelectedListener(this);
_monthButton = (Button)findViewById(R.id.monthSpinner_button);
_monthButton.setOnClickListener(this);
_backImageButton = (ImageButton)findViewById(R.id.back_ImageButton);
_backImageButton.setOnClickListener(this);
_headerImageButton =(ImageButton)findViewById(R.id.header_ImageButton);
_headerImageButton.setOnClickListener(this);
}
private void getJSON_Response(String response,int pid) {
switch (pid) {
case Constant.PID_ACCOUNT_HISTORY:
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if(message!=null && message.equalsIgnoreCase("Success")){
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
String lastAddedDate = null;
for (int i = 0; i <dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
String date = history.getString("DATE");
if(firstTime || !(date.equalsIgnoreCase(lastAddedDate))){
firstTime=false;
lastAddedDate = date;
items.add(new SectionItem(date));
}
String username= history.getString("USER_NAME");
String number = history.getString("PhoneNumber");
String time = history.getString("TIME");
String amount=history.getString("AMOUNT");
String duration =history.getString("QUANTITY");
items.add(new EntryItem(username,duration,amount,number,time));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
#Override
public void onClick(View v) {
if(v==_monthButton){
_spinner.performClick();
}else if(v==_backImageButton){
SectionListExampleActivity.this.finish();
}else if(v== _headerImageButton){
if (p != null)
showPopup(SectionListExampleActivity.this, p);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long arg3) {
if(position!=0){
switch (parent.getId()) {
case R.id.month_spinner:
String selectedItem = _spinner.getSelectedItem().toString();
_monthButton.setBackgroundResource(R.drawable.month_blank);
_monthButton.setText(selectedItem);
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String _historyURL = Constant.prodORdevUrl + "GetAccountHistory?token="+_token+"&account="+_account+"&month="+month+"&year="+year;
getHistory(_historyURL,true);
break;
default:
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class EntryAdapter extends ArrayAdapter<Item> implements IServerResponse {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
private String _token;
private String _account;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
String date =createDateFormat(si.getTitle());
sectionView.setText(date);
}else{
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final RelativeLayout relay = (RelativeLayout)v.findViewById(R.id.account_history_item_relay);
final TextView username = (TextView)v.findViewById(R.id.user_name_textview);
final TextView amount = (TextView)v.findViewById(R.id.amount_textview);
final TextView duration = (TextView)v.findViewById(R.id.duration_textview);
final TextView phone = (TextView)v.findViewById(R.id.phone_no_textview);
final TextView time = (TextView)v.findViewById(R.id.time_textview);
relay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phone.getText().toString());
}
});
if (username != null)
username.setText(ei.username);
if(amount != null)
amount.setText(ei.duration + "min");
if(duration != null)
duration.setText("$"+ ei.amount);
if(phone != null)
phone.setText(ei.number);
if(time != null)
time.setText(ei.time);
}
}
return v;
}
void makeCall(String destination) {
if(_token!=null && _account!=null){
if(destination!=null && !destination.equals("")){
String phoneNumber = Constant.getPhoneNumber(this.context.getApplicationContext());
if(phoneNumber!=null && phoneNumber.length()>0){
String callURL =WebService.WEB_SERVICE_URL+"PlaceLongDistanceCall?token="+_token +
"&phonenumber="+phoneNumber+"&destinationNumber="+destination+"&authtoken="+_token;
getCall(callURL,true);
}else{
Constant.showToast(this.context, Constant.INSERT_SIM);
}
}else{
Constant.showToast(this.context, "In valid destination number.");
}
}
}
}
I had query title column from database and want to set it in TextView in GridView.
How?
CafeDatasource
public List<Model_Insert> findTblCafe(){
List<Model_Insert> model_Inserts = new ArrayList<Model_Insert>();
Cursor cursor = database.query(CafeDbOpenHelper.TABLE_CAFE, rtv_tbl_Cafe,
null, null, null, null, null);
Log.i("number", "return" + cursor.getCount()+ " rows");
if(cursor.getCount() > 0){
while (cursor.moveToNext()) {
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_ID)));
model_Insert.setCafe_Title(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_TITLE)));
model_Insert.setCafe_Been(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_BEEN)));
model_Insert.setCafe_Want(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_WANT)));
model_Insert.setCafe_Address(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_ADDRESS)));
model_Insert.setCafe_Thumb(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_THUMB)));
model_Insert.setCafe_Description(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_DESCRIPTION)));
model_Insert.setCafe_WifiRate(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_WIFI_RATE)));
model_Insert.setCafe_CoffeeRate(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_COFFEE_RATE)));
model_Insert.setCafe_Latitude(cursor.getDouble(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_LATITUDE)));
model_Insert.setCafe_Longitude(cursor.getDouble(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_LONGITUDE)));
model_Inserts.add(model_Insert);
}
}
return model_Inserts;
}
MainActivity
public ArrayList<HashMap<String, String>> placeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
===============================================================
dataSource = new CafeDataSource(this);
dataSource.open();
List<Model_Insert> model_Inserts = dataSource.findTblCafe();// query database (findTblCafe)
if(model_Inserts.size() == 0){
new DownloadImageTask().execute();
model_Inserts = dataSource.findTblCafe();
}
===============================================================
} // End onCreate
public void ShowAllContent() {
GridView gridView1 = (GridView) findViewById(R.id.grid_all);
gridView1.setAdapter(new ImageAdapter(TopActivity.this, placeList));
}
public class DownloadImageTask extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
placeList = new ArrayList<HashMap<String,String>>();
JSONParser jParser = new JSONParser();
JSONObject jsonO = jParser.getJSONUrl(url);
try {
places = jsonO.getJSONArray("place");
for (int i = 0; i < places.length(); i++) {
JSONObject jobj = places.getJSONObject(i);
int cafe_id = jobj.getInt(TAG_CAFE_ID);
String cafe_title = jobj.getString(TAG_CAFE_TITLE);
int cafe_been = jobj.getInt(TAG_CAFE_BEEN);
int cafe_want = jobj.getInt(TAG_CAFE_WANT);
String cafe_address = jobj.getString(TAG_CAFE_ADDRESS);
String cafe_thumb = jobj.getString(TAG_CAFE_THUMB);
String cafe_description = jobj.getString(TAG_CAFE_DESCRIPTION);
int cafe_wifi_rate = jobj.getInt(TAG_CAFE_WIFI_RATE);
int cafe_coffee_rate = jobj.getInt(TAG_CAFE_COFFEE_RATE);
double cafe_latitude = jobj.getDouble(TAG_CAFE_LATITUDE);
double cafe_longitude = jobj.getDouble(TAG_CAFE_LONGITUDE);
// Table Save
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setCafe_Been(cafe_been);
model_Insert.setCafe_Want(cafe_want);
model_Insert = dataSource.createTableCafeSave(model_Insert);
Log.i("data", " ID " + model_Insert.getCafe_Id());
// Table Cafe
model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setCafe_Title(cafe_title);
model_Insert.setCafe_Been(cafe_been);
model_Insert.setCafe_Want(cafe_want);
model_Insert.setCafe_Address(cafe_address);
model_Insert.setCafe_Thumb(cafe_thumb);
model_Insert.setCafe_Description(cafe_description);
model_Insert.setCafe_WifiRate(cafe_wifi_rate);
model_Insert.setCafe_CoffeeRate(cafe_coffee_rate);
model_Insert.setCafe_Latitude(cafe_latitude);
model_Insert.setCafe_Longitude(cafe_longitude);
model_Insert = dataSource.createTableCafe(model_Insert);
Log.i("data", " Picture " + model_Insert.getCafe_Id());
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_CAFE_TITLE, cafe_title);
placeList.add(map);
}
// for " piture " Object in json
pictures = jsonO.getJSONArray("pictures");
for (int i = 0; i < pictures.length(); i++) {
JSONObject jObj = pictures.getJSONObject(i);
int cafe_id = jObj.getInt(TAG_CAFE_ID);
String picture_url = jObj.getString(TAG_PICTURE_URL);
// Table Picture
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setPitureUrl(picture_url);
model_Insert = dataSource.createTablePicture(model_Insert);
Log.i("pic", " Picture " + model_Insert.getPitureurl());
HashMap<String, String> map = new HashMap<String, String>();
placeList.add(map);
}
} catch (JSONException e) {
// TODO: handle exception
}
return null;
}
protected void onPostExecute(Void unused) {
ShowAllContent(); // When Finish Show Content
}
}
private static class ViewHolder {
public ImageView imageview;
public TextView txtTitle;
}
public class ImageAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String,String>>();
public ImageAdapter(Context c, ArrayList<HashMap<String, String>> myArrayList){
context = c;
MyArr = myArrayList;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View converView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(converView == null){
converView = inflater.inflate(R.layout.grid_item, null);
}
viewHolder.imageview = (ImageView) converView.findViewById(R.id.imv_card_cafe);
viewHolder.txtTitle = (TextView) converView.findViewById(R.id.txt_title);
/* String str = "frute : juse text";
Integer len;
len = str.length();
if(len > 20){
String result = str.substring(0, 15);
viewHolder.txtTitle.setText(result);
}
else {
viewHolder.txtTitle.setText(str);
} */
=============================================================================
viewHolder.txtTitle.setText(...............................?);
=============================================================================
viewHolder.imageview.setImageResource(mThumb[position]);
return converView;
}
}
because you are getting all titles inside model_Inserts List you will need to pass this List to Custom BaseAdapter for showing in TextView as :
Change ShowAllContent() method as:
public void ShowAllContent() {
GridView gridView1 = (GridView) findViewById(R.id.grid_all);
gridView1.setAdapter(new ImageAdapter(TopActivity.this, placeList,model_Inserts));
}
and ImageAdapter constructor as :
public class ImageAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> MyArr =
new ArrayList<HashMap<String,String>>();
List<Model_Insert> model_Inserts=null;
public ImageAdapter(Context c,
ArrayList<HashMap<String, String>> myArrayList,
List<Model_Insert> model_Inserts){
context = c;
MyArr = myArrayList;
this.model_Inserts=model_Inserts;
}
///your code here...
now use model_Inserts for getting Title to show inside getView