How to add search functionality in custom listview - android

I have a problem to add search function in a listview in my simple android app. I was followed this article [https://workspaces.codeproject.com/vatsag/customized-android-listview-with-image-and-text][1], but i can't figure how to add search functionality.
This is xparser.java:
public class XParser extends DefaultHandler {
ArrayList<String> idlist = new ArrayList<String>();
ArrayList<String> namalist = new ArrayList<String>();
ArrayList<String> menulist = new ArrayList<String>();
ArrayList<String> alamatlist = new ArrayList<String>();
ArrayList<String> iconlist = new ArrayList<String>();
//temp variable to store the data chunk read while parsing
private String tempStore = null;
public XParser() {
// TODO Auto-generated constructor stub
}
/*
* Clears the tempStore variable on every start of the element
* notification
*
* */
public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equalsIgnoreCase("id")) {
tempStore = "";
} else if (localName.equalsIgnoreCase("nama")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("menu")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("alamat")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("icon")) {
tempStore = "";
}
else {
tempStore = "";
}
}
/*
* updates the value of the tempStore variable into
* corresponding list on receiving end of the element
* notification
* */
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if (localName.equalsIgnoreCase("id")) {
idlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("nama")) {
namalist.add(tempStore);
}
else if (localName.equalsIgnoreCase("menu")) {
menulist.add(tempStore);
}
else if (localName.equalsIgnoreCase("alamat")) {
alamatlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("icon")) {
iconlist.add(tempStore);
}
tempStore = "";
}
/*
* adds the incoming data chunk of character data to the
* temp data variable - tempStore
*
* */
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
tempStore += new String(ch, start, length);
}
}
This is BinderData.java
public class BinderData extends BaseAdapter {
// XML node keys
static final String KEY_TAG = "rmdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAMA = "nama";
static final String KEY_MENU = "menu";
static final String KEY_ALAMAT = "alamat";
static final String KEY_ICON = "icon";
LayoutInflater inflater;
ImageView thumb_image;
List<HashMap<String,String>> rmDataCollection;
ViewHolder holder;
public BinderData() {
// TODO Auto-generated constructor stub
}
public BinderData(Activity act, List<HashMap<String,String>> map) {
this.rmDataCollection = map;
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
return idlist.size();
return rmDataCollection.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null){
vi = inflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.tvNama = (TextView)vi.findViewById(R.id.tvNama); // city name
holder.tvMenu = (TextView)vi.findViewById(R.id.tvMenu); // city weather overview
holder.tvRMImage =(ImageView)vi.findViewById(R.id.list_image); // thumb image
vi.setTag(holder);
}
else{
holder = (ViewHolder)vi.getTag();
}
// Setting all values in listview
holder.tvNama.setText(rmDataCollection.get(position).get(KEY_NAMA));
holder.tvMenu.setText(rmDataCollection.get(position).get(KEY_MENU));
//Setting an image
String uri = "drawable/"+ rmDataCollection.get(position).get(KEY_ICON);
int imageResource = vi.getContext().getApplicationContext().getResources().getIdentifier(uri, null, vi.getContext().getApplicationContext().getPackageName());
Drawable image = vi.getContext().getResources().getDrawable(imageResource);
holder.tvRMImage.setImageDrawable(image);
return vi;
}
/*
*
* */
static class ViewHolder{
TextView tvNama;
TextView tvMenu;
ImageView tvRMImage;
}
}
This is WeatherActiviy.java:
public class WeatherActivity extends Activity implements OnQueryTextListener {
// XML node keys
static final String KEY_TAG = "rmdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAMA = "nama";
static final String KEY_MENU = "menu";
static final String KEY_ALAMAT = "alamat";
static final String KEY_ICON = "icon";
// List items
ListView list;
EditText inputSearch;
BinderData adapter = null;
List<HashMap<String,String>> rmDataCollection;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (getAssets().open("weatherdata.xml"));
rmDataCollection = new ArrayList<HashMap<String,String>>();
// normalize text representation
doc.getDocumentElement ().normalize ();
NodeList weatherList = doc.getElementsByTagName("rmdata");
HashMap<String,String> map = null;
for (int i = 0; i < weatherList.getLength(); i++) {
map = new HashMap<String,String>();
Node firstWeatherNode = weatherList.item(i);
if(firstWeatherNode.getNodeType() == Node.ELEMENT_NODE){
Element firstWeatherElement = (Element)firstWeatherNode;
//-------
NodeList idList = firstWeatherElement.getElementsByTagName(KEY_ID);
Element firstIdElement = (Element)idList.item(0);
NodeList textIdList = firstIdElement.getChildNodes();
//--id
map.put(KEY_ID, ((Node)textIdList.item(0)).getNodeValue().trim());
//2.-------
NodeList cityList = firstWeatherElement.getElementsByTagName(KEY_NAMA);
Element firstCityElement = (Element)cityList.item(0);
NodeList textCityList = firstCityElement.getChildNodes();
//--city
map.put(KEY_NAMA, ((Node)textCityList.item(0)).getNodeValue().trim());
//3.-------
NodeList tempList = firstWeatherElement.getElementsByTagName(KEY_MENU);
Element firstTempElement = (Element)tempList.item(0);
NodeList textTempList = firstTempElement.getChildNodes();
//--city
map.put(KEY_MENU, ((Node)textTempList.item(0)).getNodeValue().trim());
/*
//4.-------
NodeList condList = firstWeatherElement.getElementsByTagName(KEY_ALAMAT);
Element firstCondElement = (Element)condList.item(0);
NodeList textCondList = firstCondElement.getChildNodes();
//--city
map.put(KEY_ALAMAT, ((Node)textCondList.item(0)).getNodeValue().trim());
//5.-------
NodeList speedList = firstWeatherElement.getElementsByTagName(KEY_SPEED);
Element firstSpeedElement = (Element)speedList.item(0);
NodeList textSpeedList = firstSpeedElement.getChildNodes();
//--city
map.put(KEY_SPEED, ((Node)textSpeedList.item(0)).getNodeValue().trim());
*/
//6.-------
NodeList iconList = firstWeatherElement.getElementsByTagName(KEY_ICON);
Element firstIconElement = (Element)iconList.item(0);
NodeList textIconList = firstIconElement.getChildNodes();
//--city
map.put(KEY_ICON, ((Node)textIconList.item(0)).getNodeValue().trim());
//Add to the Arraylist
rmDataCollection.add(map);
}
}
BinderData bindingData = new BinderData(this,rmDataCollection);
list = (ListView) findViewById(R.id.list);
Log.i("BEFORE", "<<------------- Before SetAdapter-------------->>");
list.setAdapter(bindingData);
Log.i("AFTER", "<<------------- After SetAdapter-------------->>");
list.setTextFilterEnabled(true);
// search
inputSearch = (EditText) findViewById (R.id.inputSearch);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
((Filterable) WeatherActivity.this.rmDataCollection).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
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
}
});
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent();
i.setClass(WeatherActivity.this, SampleActivity.class);
// parameters
i.putExtra("position", String.valueOf(position + 1));
/* selected item parameters
* 1. City name
* 2. Weather
* 3. Wind speed
* 4. Temperature
* 5. Weather icon
*/
i.putExtra("city", rmDataCollection.get(position).get(KEY_NAMA));
i.putExtra("weather", rmDataCollection.get(position).get(KEY_MENU));
i.putExtra("windspeed", rmDataCollection.get(position).get(KEY_ALAMAT));
i.putExtra("icon", rmDataCollection.get(position).get(KEY_ICON));
// start the sample activity
startActivity(i);
}
});
}
catch (IOException ex) {
Log.e("Error", ex.getMessage());
}
catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextChange(String newText)
{
// this is your adapter that will be filtered
if (TextUtils.isEmpty(newText))
{
list.clearTextFilter();
}
else
{
list.setFilterText(newText.toString());
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
}

Related

Trying to put a search functionality in my application

Hi, guys! First of all, I'm newbie! I'm trying to create a search functionality (Search BY CITY) in my application. But something is wrong! It don't work!
The error message is: 'The method filter(String) is undefined for the type BinderData'
adapter.filter(text);
Could someone help me in details? I included the "TextWatcher" function in my main activity (WeatherActivity).
This is my code:
WeatherActivity
public class WeatherActivity extends Activity {
// XML node keys
static final String KEY_TAG = "weatherdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_CITY = "city";
static final String KEY_TEMP_C = "tempc";
static final String KEY_TEMP_F = "tempf";
static final String KEY_CONDN = "condition";
static final String KEY_SPEED = "windspeed";
static final String KEY_ICON = "icon";
EditText editsearch;
// List items
ListView list;
BinderData adapter = null;
List<HashMap<String,String>> weatherDataCollection;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (getAssets().open("weatherdata.xml"));
weatherDataCollection = new ArrayList<HashMap<String,String>>();
// normalize text representation
doc.getDocumentElement ().normalize ();
NodeList weatherList = doc.getElementsByTagName("weatherdata");
HashMap<String,String> map = null;
for (int i = 0; i < weatherList.getLength(); i++) {
map = new HashMap<String,String>();
Node firstWeatherNode = weatherList.item(i);
if(firstWeatherNode.getNodeType() == Node.ELEMENT_NODE){
Element firstWeatherElement = (Element)firstWeatherNode;
//-------
NodeList idList = firstWeatherElement.getElementsByTagName(KEY_ID);
Element firstIdElement = (Element)idList.item(0);
NodeList textIdList = firstIdElement.getChildNodes();
//--id
map.put(KEY_ID, ((Node)textIdList.item(0)).getNodeValue().trim());
//2.-------
NodeList cityList = firstWeatherElement.getElementsByTagName(KEY_CITY);
Element firstCityElement = (Element)cityList.item(0);
NodeList textCityList = firstCityElement.getChildNodes();
//--city
map.put(KEY_CITY, ((Node)textCityList.item(0)).getNodeValue().trim());
//3.-------
NodeList tempList = firstWeatherElement.getElementsByTagName(KEY_TEMP_C);
Element firstTempElement = (Element)tempList.item(0);
NodeList textTempList = firstTempElement.getChildNodes();
//--city
map.put(KEY_TEMP_C, ((Node)textTempList.item(0)).getNodeValue().trim());
//4.-------
NodeList condList = firstWeatherElement.getElementsByTagName(KEY_CONDN);
Element firstCondElement = (Element)condList.item(0);
NodeList textCondList = firstCondElement.getChildNodes();
//--city
map.put(KEY_CONDN, ((Node)textCondList.item(0)).getNodeValue().trim());
//5.-------
NodeList speedList = firstWeatherElement.getElementsByTagName(KEY_SPEED);
Element firstSpeedElement = (Element)speedList.item(0);
NodeList textSpeedList = firstSpeedElement.getChildNodes();
//--city
map.put(KEY_SPEED, ((Node)textSpeedList.item(0)).getNodeValue().trim());
//6.-------
NodeList iconList = firstWeatherElement.getElementsByTagName(KEY_ICON);
Element firstIconElement = (Element)iconList.item(0);
NodeList textIconList = firstIconElement.getChildNodes();
//--city
map.put(KEY_ICON, ((Node)textIconList.item(0)).getNodeValue().trim());
//Add to the Arraylist
weatherDataCollection.add(map);
}
}
BinderData bindingData = new BinderData(this,weatherDataCollection);
list = (ListView) findViewById(R.id.list);
adapter = new BinderData(WeatherActivity.this,
weatherDataCollection);
editsearch = (EditText) findViewById(R.id.search);
editsearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(text);
}
});
Log.i("BEFORE", "<<------------- Before SetAdapter-------------->>");
list.setAdapter(bindingData);
Log.i("AFTER", "<<------------- After SetAdapter-------------->>");
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent();
i.setClass(WeatherActivity.this, SampleActivity.class);
// parameters
i.putExtra("position", String.valueOf(position + 1));
/* selected item parameters
* 1. City name
* 2. Weather
* 3. Wind speed
* 4. Temperature
* 5. Weather icon
*/
i.putExtra("city", weatherDataCollection.get(position).get(KEY_CITY));
i.putExtra("weather", weatherDataCollection.get(position).get(KEY_CONDN));
i.putExtra("windspeed", weatherDataCollection.get(position).get(KEY_SPEED));
i.putExtra("temperature", weatherDataCollection.get(position).get(KEY_TEMP_C));
i.putExtra("icon", weatherDataCollection.get(position).get(KEY_ICON));
// start the sample activity
startActivity(i);
}
});
}
catch (IOException ex) {
Log.e("Error", ex.getMessage());
}
catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
BlinderData
public class BinderData extends BaseAdapter {
// XML node keys
static final String KEY_TAG = "weatherdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_CITY = "city";
static final String KEY_TEMP_C = "tempc";
static final String KEY_TEMP_F = "tempf";
static final String KEY_CONDN = "condition";
static final String KEY_SPEED = "windspeed";
static final String KEY_ICON = "icon";
LayoutInflater inflater;
ImageView thumb_image;
List<HashMap<String,String>> weatherDataCollection;
ViewHolder holder;
public BinderData() {
// TODO Auto-generated constructor stub
}
public BinderData(Activity act, List<HashMap<String,String>> map) {
this.weatherDataCollection = map;
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
// return idlist.size();
return weatherDataCollection.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null){
vi = inflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.tvCity = (TextView)vi.findViewById(R.id.tvCity); // city name
holder.tvWeather = (TextView)vi.findViewById(R.id.tvCondition); // city weather overview
holder.tvTemperature = (TextView)vi.findViewById(R.id.tvTemp); // city temperature
holder.tvWeatherImage =(ImageView)vi.findViewById(R.id.list_image); // thumb image
vi.setTag(holder);
}
else{
holder = (ViewHolder)vi.getTag();
}
// Setting all values in listview
holder.tvCity.setText(weatherDataCollection.get(position).get(KEY_CITY));
holder.tvWeather.setText(weatherDataCollection.get(position).get(KEY_CONDN));
holder.tvTemperature.setText(weatherDataCollection.get(position).get(KEY_TEMP_C));
//Setting an image
String uri = "drawable/"+ weatherDataCollection.get(position).get(KEY_ICON);
int imageResource = vi.getContext().getApplicationContext().getResources().getIdentifier(uri, null, vi.getContext().getApplicationContext().getPackageName());
Drawable image = vi.getContext().getResources().getDrawable(imageResource);
holder.tvWeatherImage.setImageDrawable(image);
return vi;
}
/*
*
* */
static class ViewHolder{
TextView tvCity;
TextView tvTemperature;
TextView tvWeather;
ImageView tvWeatherImage;
}
}
SampleActivity
public class SampleActivity extends Activity {
String position = "1";
String city = "";
String weather = "";
String temperature = "";
String windSpeed = "";
String iconfile = "";
ImageButton imgWeatherIcon;
TextView tvcity;
TextView tvtemp;
TextView tvwindspeed;
TextView tvCondition;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailpage);
try {
//handle for the UI elements
imgWeatherIcon = (ImageButton) findViewById(R.id.imageButtonAlpha);
//Text fields
tvcity = (TextView) findViewById(R.id.textViewCity);
tvtemp = (TextView) findViewById(R.id.textViewTemperature);
tvwindspeed = (TextView) findViewById(R.id.textViewWindSpeed);
tvCondition = (TextView) findViewById(R.id.textViewCondition);
// Get position to display
Intent i = getIntent();
this.position = i.getStringExtra("position");
this.city = i.getStringExtra("city");
this.weather= i.getStringExtra("weather");
this.temperature = i.getStringExtra("temperature");
this.windSpeed = i.getStringExtra("windspeed");
this.iconfile = i.getStringExtra("icon");
String uri = "drawable/"+ "d" + iconfile;
int imageBtnResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable dimgbutton = getResources().getDrawable(imageBtnResource);
//text elements
tvcity.setText(city);
tvtemp.setText(temperature);
tvwindspeed.setText(windSpeed);
tvCondition.setText(weather);
//thumb_image.setImageDrawable(image);
imgWeatherIcon.setImageDrawable(dimgbutton);
}
catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
XParser
public class XParser extends DefaultHandler {
ArrayList<String> idlist = new ArrayList<String>();
ArrayList<String> citylist = new ArrayList<String>();
ArrayList<String> condilist = new ArrayList<String>();
ArrayList<String> templist = new ArrayList<String>();
ArrayList<String> speedlist = new ArrayList<String>();
ArrayList<String> iconlist = new ArrayList<String>();
//temp variable to store the data chunk read while parsing
private String tempStore = null;
public XParser() {
// TODO Auto-generated constructor stub
}
/*
* Clears the tempStore variable on every start of the element
* notification
*
* */
public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equalsIgnoreCase("id")) {
tempStore = "";
} else if (localName.equalsIgnoreCase("city")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("tempc")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("condition")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("windspeed")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("icon")) {
tempStore = "";
}
else {
tempStore = "";
}
}
/*
* updates the value of the tempStore variable into
* corresponding list on receiving end of the element
* notification
* */
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if (localName.equalsIgnoreCase("id")) {
idlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("city")) {
citylist.add(tempStore);
}
else if (localName.equalsIgnoreCase("tempc")) {
templist.add(tempStore);
}
else if (localName.equalsIgnoreCase("condition")) {
condilist.add(tempStore);
}
else if (localName.equalsIgnoreCase("windspeed")) {
speedlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("icon")) {
iconlist.add(tempStore);
}
tempStore = "";
}
/*
* adds the incoming data chunk of character data to the
* temp data variable - tempStore
*
* */
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
tempStore += new String(ch, start, length);
}
}``
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Filter ListView data

I am working on an App where data is read from XML, then based on the data, It creates an ListView and clicking on any item in ListView it opens another activity with details. I am trying to implement search functionality in the ListView, below is my code, I don't know how ti implement Search, I tried many ways but none of them worked. Any help is highly appreciated. Thanks in advance.
public class BrowseActors extends Activity {
private static final String TAG = "QuizListActivity";
private ImageView bannerImageView; // displays a Image
// Search EditText
private EditText inputSearch;
// XML node keys
static final String KEY_TAG = "ActorData"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_ICON = "icon";
String position;
String sourceFile;
// List items
ListView list;
//BinderActorData adapter = null;
List<HashMap<String, String>> actorDataCollection;
ArrayAdapter<HashMap<String, String>> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Remove title
setContentView(R.layout.browse_actor);
bannerImageView = (ImageView) findViewById(R.id.topImageView);
try {
// Get Category to filter
Intent in = getIntent();
this.position = in.getStringExtra("position");
sourceFile="BaseData.xml"
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(getAssets().open(sourceFile));
actorDataCollection = new ArrayList<HashMap<String, String>>();
// normalize text representation
doc.getDocumentElement().normalize();
NodeList quizList = doc.getElementsByTagName("ActorData");
HashMap<String, String> map = null;
for (int i = 0; i < quizList.getLength(); i++) {
map = new HashMap<String, String>();
Node firstQuestionNode = quizList.item(i);
if (firstQuestionNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstAircraftElement = (Element) firstQuestionNode;
// 1.-------
NodeList idList = firstAircraftElement
.getElementsByTagName(KEY_ID);
Element firstIdElement = (Element) idList.item(0);
NodeList textIdList = firstIdElement.getChildNodes();
// --id
map.put(KEY_ID, textIdList.item(0).getNodeValue()
.trim());
// 2.-------
NodeList nameList = firstAircraftElement
.getElementsByTagName(KEY_NAME);
Element firstNameElement = (Element) nameList.item(0);
NodeList textNameList = firstNameElement
.getChildNodes();
// --name
map.put(KEY_NAME, textNameList.item(0).getNodeValue()
.trim());
// 3.-------
NodeList iconList = firstAircraftElement
.getElementsByTagName(KEY_ICON);
Element firstIconElement = (Element) iconList.item(0);
NodeList textIconList = firstIconElement
.getChildNodes();
// -- Image Icon
map.put(KEY_ICON, textIconList.item(0).getNodeValue()
.trim());
// Add to the Arraylist
actorDataCollection.add(map);
}
}
BinderActorData bindingData = new BinderActorData(this,
actorDataCollection);
// Adding items to listview
list = (ListView) findViewById(R.id.list);
// Adding items to listview
inputSearch = (EditText) findViewById(R.id.inputSearch);
list.setAdapter(bindingData);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
//BrowseActors.this.bindingData.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
}
});
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent();
i.setClass(BrowseActors.this, ViewActor.class);
// parameters
i.putExtra("position", String.valueOf(position + 1));
/*
* selected item parameters
*/
i.putExtra("name",
actorDataCollection.get(position).get(KEY_NAME));
i.putExtra("icon",
actorDataCollection.get(position).get(KEY_ICON));
// start the sample activity
startActivity(i);
}
});
}
catch (IOException ex) {
Log.e("Error", ex.getMessage());
} catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
}
Search will be implemented on original data source, it could be XML/JSON/database or anything else.
You're using "position" parameter for search, I think you can use the View view parameter.
Just keep a hidden field in the ListView row, and map it with some sort of primary key.
When OnClick event occurs, you can then get the row layout from view and do a findViewByID() call to get your hidden control. From the value of that control, you can call a back-end web service or run an x-path query or anything you want.

Insert new data in Custom Adapter and update list

I have an list with an custom adapter, and upon refresh I want to add new data to be displayed(if any available).
But the list isn't being update. I tried all the methods with notifyDataSetChanged for the adapter but it's not updated.
Please help. I lost so much time with this and I feel like I'm loosing my mind with this one.
Here is the code:
NewsFeedArrayAdapter
public class NewsFeedArrayAdapter extends ArrayAdapter<FeedItem> {
private final String TAG_DEBUG = this.getClass().getName();
private LayoutInflater inflator;
public final static String PREFS_NAME = "shared_pref_eid";
ImageLoader imageLoader;
Utils utils;
public NewsFeedArrayAdapter(Activity context) {
super(context, R.layout.feed_story_content);
this.utils = new Utils(context);
inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = ImageLoader.getInstance(context);
}
/**
* Static Inner class.
*
* Makes the ListView more efficient since Android recycles views in a ListView.
*/
public static class ViewHolder {
public ImageView profilePicture, image;
public TextView author, timePast, message, likes, comments;
public LinearLayout like, comment, share, likesCommentsCounter;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = null;
FeedItem feedItem = FeedItemParser.FEEDS.get(position);
ViewHolder holder = null;
if (convertView == null) {
rowView = inflator.inflate(R.layout.feed_story_content, parent, false);
holder = new ViewHolder();
holder.profilePicture = (ImageView) rowView.findViewById(R.id.feed_story_profile_picture);
holder.author = (TextView) rowView.findViewById(R.id.feed_story_author);
holder.timePast = (TextView) rowView.findViewById(R.id.feed_story_time_past);
holder.message = (TextView) rowView.findViewById(R.id.feed_story_message);
holder.image = (ImageView) rowView.findViewById(R.id.feed_story_image);
holder.like = (LinearLayout) rowView.findViewById(R.id.feed_feedback_like_container);
holder.comment = (LinearLayout) rowView.findViewById(R.id.feed_feedback_comment_container);
holder.share = (LinearLayout) rowView.findViewById(R.id.feed_feedback_share_container);
holder.likes = (TextView) rowView.findViewById(R.id.feed_story_likes);
holder.comments = (TextView) rowView.findViewById(R.id.feed_story_comments);
rowView.setTag(holder);
} else {
rowView = convertView;
holder = ((ViewHolder) rowView.getTag());
}
Log.i(TAG_DEBUG, "feedItem = " + feedItem);
if (feedItem != null) {
if (!TextUtils.isEmpty(feedItem.feed_story_from_name)) {
holder.author.setText(feedItem.feed_story_from_name);
} else {
holder.author.setText("Unknown");
}
if (!TextUtils.isEmpty(feedItem.feed_story_created_time)) {
// Convert the date to calendar date
Calendar calendarDate = null;
try {
calendarDate = ISO8601.toCalendar(feedItem.feed_story_created_time);
} catch (ParseException e) {
e.printStackTrace();
}
CharSequence relativeTimeSpan = DateUtils.getRelativeTimeSpanString(
calendarDate.getTimeInMillis(),
System.currentTimeMillis(),
DateUtils.SECOND_IN_MILLIS);
holder.timePast.setText(relativeTimeSpan);
} else {
holder.timePast.setText("Unknown");
}
Log.i(TAG_DEBUG, "feedItem.feed_story_message = " + feedItem.feed_story_message);
if (!TextUtils.isEmpty(feedItem.feed_story_message)) {
holder.message.setText(feedItem.feed_story_message);
} else {
holder.message.setText("Unkown");
// holder.message.setVisibility(View.GONE);
}
// Display the icon of the feed
int defaultResourceIcon = R.drawable.no_avatar;
if (feedItem.feed_story_from_id != null) {
String iconUrl = "https://graph.facebook.com/" + feedItem.feed_story_from_id + "/picture?type=normal";
if (Session.getActiveSession() != null &&
Session.getActiveSession().getAccessToken() != null) {
iconUrl += "&access_token=" + Session.getActiveSession().getAccessToken();
}
Log.i(TAG_DEBUG, "iconUrl = " + iconUrl);
imageLoader.displayImage(iconUrl, holder.profilePicture, 70, defaultResourceIcon);
} else {
imageLoader.cancelDisplayTaskFor(holder.profilePicture);
holder.profilePicture.setImageResource(defaultResourceIcon);
}
// Display the picture of the feed
int defaultResourcePicture = R.drawable.empty;
if (!TextUtils.isEmpty(feedItem.feed_story_picture)) {
holder.image.setVisibility(View.VISIBLE);
Log.i(TAG_DEBUG, "feed_picture = " + feedItem.feed_story_picture + "\nfeed_picture_height = " + feedItem.feed_story_picture_height);
imageLoader.displayImage(feedItem.feed_story_picture, holder.image, -1, defaultResourcePicture);
} else {
imageLoader.cancelDisplayTaskFor(holder.image);
// holder.image.setImageResource(defaultResourcePicture);
holder.image.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(feedItem.feed_story_likes)) {
holder.likes.setVisibility(View.VISIBLE);
String likes = feedItem.feed_story_likes + " like";
if (!feedItem.feed_story_likes.contentEquals("1")) {
likes += "s";
}
holder.likes.setText(likes);
} else {
holder.likes.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(feedItem.feed_story_comments)) {
holder.comments.setVisibility(View.VISIBLE);
String comments = feedItem.feed_story_comments + " comment";
if (!feedItem.feed_story_comments.contentEquals("1")) {
comments += "s";
}
holder.comments.setText(comments);
} else {
holder.comments.setVisibility(View.GONE);
}
holder.like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Like content - TBA");
}
});
holder.comment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Comment section - TBA");
}
});
holder.share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Sharing content - TBA");
}
});
}
return rowView;
}
#Override
public int getCount() {
return FeedItemParser.FEEDS.size();
}
}
The adapter on the list is set after the first request, when I get my first results, like this:
ListView actualListView = mPullRefreshListView.getRefreshableView();
// Need to use the Actual ListView when registering for Context Menu
registerForContextMenu(actualListView);
// Sort the list before displaying
Collections.sort(FeedItemParser.FEEDS, Comparators.CREATED_TIME);
// Set the custom adapter
customAddapter = new NewsFeedArrayAdapter(activity);
// Populate the fragment with the data from JSON
actualListView.setAdapter(customAddapter);
FeedItemParser is an custom class where I store my custom objects:
public class FeedItemParser {
// JSON Node names
public static final String
TAG_DATA = "data", // Array
TAG_ID = "id", // String
TAG_FROM = "from", // Object
TAG_FROM_ID = "id", // String
TAG_FROM_CATEGORY = "category", // String
TAG_FROM_NAME = "name", // String
TAG_TO = "to", // Object
TAG_TO_DATA = "data", // Array
TAG_TO_DATA_ID = "id", // String
TAG_TO_DATA_NAME = "name", // String
TAG_MESSAGE = "message", // String
TAG_PICTURE = "picture", // String
TAG_ACTIONS = "actions", // Array
TAG_ACTIONS_NAME = "name", // String
TAG_ACTIONS_LINK = "link", // String
TAG_PRIVACY = "privacy", // Object
TAG_PRIVACY_VALUE = "value", // String
TAG_TYPE = "type", // String
TAG_STATUS_TYPE = "status_type", // String
TAG_CREATED_TIME = "created_time", // String
TAG_UPDATED_TIME = "updated_time", // String
TAG_LIKES = "likes", // Object
TAG_LIKES_COUNT = "count", // String
TAG_COMMENTS = "comments", // Object
TAG_COMMENTS_DATA = "data", // Array
TAG_PAGING = "paging", // Object
TAG_PAGING_PREVIOUS = "previous",// String
TAG_PAGING_NEXT = "next"; // String
/**
* An array of Shelter items.
*/
public static List<FeedItem> FEEDS = new ArrayList<FeedItem>();
/**
* A map of Array items, by ID.
*/
public static Map<String, FeedItem> FEED_MAP = new HashMap<String, FeedItem>();
public static void addItem(FeedItem item) {
FEEDS.add(FEEDS.size(), item);
FEED_MAP.put(item.feed_story_id, item);
}
public static void addPicture (String feed_story_id, String picture, String height) {
FeedItem feedItem = FEED_MAP.get(feed_story_id);
feedItem.feed_story_picture = picture;
feedItem.feed_story_picture_height = height;
}
public static class FeedItem {
public String feed_story_id, feed_story_from_id, feed_story_from_category,
feed_story_from_name, feed_story_message, feed_story_picture, feed_story_picture_height,
feed_story_privacy, feed_story_type, feed_story_status_type, feed_story_created_time,
feed_story_updated_time, feed_story_likes, feed_story_comments;
/**
* #param feed_story_id
* #param feed_story_from_id
* #param feed_story_from_category
* #param feed_story_from_name
* #param feed_story_message
* #param feed_story_picture
* #param feed_story_privacy
* #param feed_story_type
* #param feed_story_status_type
* #param feed_story_created_time
* #param feed_story_updated_time
*/
public FeedItem(String feed_story_id, String feed_story_from_id, String feed_story_from_category,
String feed_story_from_name, String feed_story_message, String feed_story_picture,
String feed_story_picture_height, String feed_story_privacy, String feed_story_type,
String feed_story_status_type, String feed_story_created_time, String feed_story_updated_time,
String feed_story_likes, String feed_story_comments) {
this.feed_story_id = feed_story_id;
this.feed_story_from_id = feed_story_from_id;
this.feed_story_from_category = feed_story_from_category;
this.feed_story_from_name = feed_story_from_name;
this.feed_story_message = feed_story_message;
this.feed_story_picture = feed_story_picture;
this.feed_story_picture_height = feed_story_picture_height;
this.feed_story_privacy = feed_story_privacy;
this.feed_story_type = feed_story_type;
this.feed_story_status_type = feed_story_status_type;
this.feed_story_created_time = feed_story_created_time;
this.feed_story_updated_time = feed_story_updated_time;
this.feed_story_likes = feed_story_likes;
this.feed_story_comments = feed_story_comments;
}
#Override
public String toString() {
return feed_story_message;
}
}
}
When I request new data(refresh), I add the new data in my object (the same way I do the first time):
FeedItemParser.addItem(new FeedItem(
id,
from_id,
from_category,
from_name,
message,
null, // Will be gotten through another request
null,
privacy_value,
type,
status_type,
created_time,
updated_time,
likes,
comments));
After that I call
ListView actualListView = mPullRefreshListView.getRefreshableView();
// Need to use the Actual ListView when registering for Context Menu
registerForContextMenu(actualListView);
// Sort the list before displaying
Collections.sort(FeedItemParser.FEEDS, Comparators.CREATED_TIME);
// Notify list adapter to update the list
customAddapter.notifyDataSetChanged();
SOLUTION
Based on the recommendations of #Selvin I have managed to update my list after adding more data. Basically I changed my adapter(I'm not using an filtered list anymore, but I'm directly using my custom objects). And after I add new Object, I update the list by calling notifyDataSetChanged() on the existing adapter.
I have also update my code, maybe it will help someone else that is stuck is this situation.
Thanks again #Selvin.

Getting only the last item data from hashmap arraylist

I have parsed json data in which there is a main json array and it contains sub json array. But the main json array not containing the sub json array in every item. So i have parsed all the data accroding to it. and i am getting perfect data from it. But the problem is that the main json array data is displaying in listview and after click on list view item the sub json array is display accroding to main json array item but its only get the last element of sub json array from hash map array list. So i can't get proper way to display so please find out some standard solution.
Here is My Code
public class MainCategories extends Fragment {
WebserviceClass wservice = new WebserviceClass();
Context c;
View v;
String data = "";
String User_id, countryid;
JSONObject jobj;
JSONArray datas;
int currentpage = 1;
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// testAdapter adapter
ArrayList<Allcategories> listing = new ArrayList<Allcategories>();;
public static ArrayList<subCateData> subList = new ArrayList<subCateData>();
int limit = 3, id;
Button bt1, bt2, bt3;
String img, img1;
String name, count;
String subname, subcount, subCategoryId;
View fragmentview;
ListView lv1, lv2, lv3;
JSONObject ca;
MainTest test;
String url, main, subnameData, subCountData, subID, cateGoryID;
LinearLayout ll;
ProgressDialog pDialog;
HashMap<String, String> map;
JSONArray dataa;
// SimpleAdapter adp;
Button b1, b2, b3;
public MainCategories(Context mainActivity, int id) {
// TODO Auto-generated constructor stub
this.c = mainActivity;
this.id = id;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
SharedPreferences sp = c.getSharedPreferences("key", 0);
User_id = sp.getString("userid=", User_id);
countryid = sp.getString("countryid", countryid);
v = inflater.inflate(R.layout.categories_tab, container, false);
lv2 = (ListView) v.findViewById(android.R.id.list);
if (FirstTab.adp == null) {
new CategoryTest().execute();
} else {
lv2.setAdapter(FirstTab.adp);
}
lv2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
for (int i = 0; i < subList.size(); i++) {
subID = subList.get(i).getsubcatId();
subnameData = subList.get(i).getsubcatname();
subCountData = subList.get(i).getsubcatcount();
Log.v("ALLDATA", subnameData + "/" + "/" + "/"
+ subCountData);
}
String catid = listing.get(position).getCategoryid();
int mycatID = Integer.parseInt(catid);
Log.v("CAtegory ID", mycatID + "");
addfragment(new CategoriesListClick(c, subID, mycatID,
subnameData, subCountData, position), true,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
});
return v;
}
public class CategoryTest extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
url = String.format(Common.view_main_category + "country_id=%s",
countryid);
Log.v("CateGory URL:", url);
jobj = wservice.getjson(url);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONObject jdata = jobj.getJSONObject("data");
datas = jdata.getJSONArray("allcategories");
for (int i = 0; i < datas.length(); i++) {
Log.e("length", "" + datas.length());
ca = datas.getJSONObject(i);
cateGoryID = ca.getString("categoryid");
name = ca.getString("categoryname");
count = ca.getString("categorystorecount");
// map = new HashMap<String, String>();
// map.put("categoryname", name);
// map.put("categorystorecount", "(" + count + ")");
// String countc=c.getString("categoryid");
Log.e(name, count);
if (ca.has("subcategories")) {
dataa = ca.getJSONArray("subcategories");
for (int j = 0; j < dataa.length(); j++) {
JSONObject d = dataa.getJSONObject(j);
// subList = new ArrayList<subCateData>();
subCategoryId = d.getString("subcategoryid");
subname = d.getString("subcategoryname");
subcount = d.getString("subcategorystorecount");
// map.put("subcategoryid", subCategoryId);
// map.put("subcategoryname", subname);
// map.put("subcategorystorecount", "(" + subcount
// + ")");
subList.add(new subCateData(subCategoryId, subname,
subcount));
/*
* Log.v("This is Data for Sub:",
* map.get("subcategoryname").toString());
*/
}
} else {
System.out.println("JSONArray is null");
}
listing.add(new Allcategories(cateGoryID, name, count));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.v("Size", listing.size() + "");
FirstTab.adp = new MyCustom(c, listing);
lv2.setAdapter(FirstTab.adp);
}
}
void addfragment(Fragment fragment, boolean addBacktoStack, int transition) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addBacktoStack)
ft.addToBackStack(null);
ft.commit();
}
class MyCustom extends BaseAdapter {
Context Mcontext;
ArrayList<Allcategories> thisCatList;
LayoutInflater inflater;
public MyCustom(Context c, ArrayList<Allcategories> listing) {
// TODO Auto-generated constructor stub
this.Mcontext = c;
this.thisCatList = listing;
inflater = LayoutInflater.from(Mcontext);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return thisCatList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
if (v == null) {
v = inflater.inflate(R.layout.list_categories, parent, false);
TextView catName = (TextView) v.findViewById(R.id.txtcname);
TextView catCount = (TextView) v.findViewById(R.id.txtccount);
catName.setText(thisCatList.get(position).getCategoryname());
catCount.setText("(" + ""
+ thisCatList.get(position).getCategorystorecount()
+ "" + ")");
Log.v("CatCount", catCount.getText().toString());
}
// TODO Auto-generated method stub
return v;
}
}
class AllCategories Data:
public class Allcategories {
private String arabicname;
private String categoryid;
private String categoryname;
private String categorystorecount;
private String fatherid;
private String order;
private String status;
// private List subcategories;
public Allcategories(String name, String count) {
// TODO Auto-generated constructor stub
this.categoryname = name;
this.categorystorecount = count;
}
public String getCategoryname() {
return this.categoryname;
}
public void setCategoryname(String categoryname) {
this.categoryname = categoryname;
}
public String getCategorystorecount() {
return this.categorystorecount;
}
public void setCategorystorecount(String categorystorecount) {
this.categorystorecount = categorystorecount;
}
SubCategory Data Class:
public class subCateData {
String subcatId, subcategoryname, subcategorystorecount;
public subCateData(String id, String name, String count) {
// TODO Auto-generated constructor stub
this.subcatId = id;
this.subcategoryname = name;
this.subcategorystorecount = count;
}
public String getsubcatId() {
return this.subcatId;
}
public void setsubcatId(String subID) {
this.subcatId = subID;
}
public String getsubcatname() {
return this.subcategoryname;
}
public void setsubcatname(String name) {
this.subcategoryname = name;
}
public String getsubcatcount() {
return this.subcategorystorecount;
}
public void setsubcatcount(String count) {
this.subcategorystorecount = count;
}
This is My Json parsing URL:
http://www.sevenstarinfotech.com/projects/demo/okaz/API/view_categories.php?country_id=4
Stack Trace:
06-27 12:23:34.361: V/ALLDATA(8533): High School///0
06-27 12:24:02.001: I/Adreno200-EGLSUB(8533): <ConfigWindowMatch:2218>: Format RGBA_8888.
06-27 12:24:02.011: D/memalloc(8533): /dev/pmem: Mapped buffer base:0x53153000 size:1536000 offset:0 fd:74
06-27 12:24:02.041: D/memalloc(8533): /dev/pmem: Mapped buffer base:0x54048000 size:15683584 offset:14147584 fd:80
06-27 12:24:02.091: D/OpenGLRenderer(8533): Flushing caches (mode 0)
06-27 12:24:02.111: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x51b26000 size:3072000 offset:1536000
06-27 12:24:02.121: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x552a2000 size:9093120 offset:7557120
06-27 12:24:02.121: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x55b4e000 size:17219584 offset:15683584
06-27 12:24:03.081: D/CLIPBOARD(8533): Hide Clipboard dialog at Starting input: finished by someone else... !
06-27 12:24:03.141: D/OpenGLRenderer(8533): Flushing caches (mode 0)
06-27 12:24:03.141: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x53153000 size:1536000 offset:0
06-27 12:24:03.141: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x54048000 size:15683584 offset:14147584
06-27 12:24:03.441: D/OpenGLRenderer(8533): Flushing caches (mode 2)
you should have to put new HashMap inside your current HasHMap so you can get subcategories items for particular index.
see this for how to use nested HashMap? and use it in subcategories loop.
i am using ArrayList of getter setter class to bind the data. so if you can convert your code into arraylist and edit the question that will be a great..
and see below code
import java.util.ArrayList;
public class MainCategories extends Fragment {
WebserviceClass wservice = new WebserviceClass();
Context c;
View v;
String data = "";
String User_id, countryid;
JSONObject jobj;
JSONArray datas;
int currentpage = 1;
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// testAdapter adapter
ArrayList<Allcategories> listing = new ArrayList<Allcategories>();;
public static ArrayList<subCateData> subList = new ArrayList<subCateData>();
int limit = 3, id;
Button bt1, bt2, bt3;
String img, img1;
String name, count;
String subname, subcount, subCategoryId;
View fragmentview;
ListView lv1, lv2, lv3;
JSONObject ca;
MainTest test;
String url, main, subnameData, subCountData, subID, cateGoryID;
LinearLayout ll;
ProgressDialog pDialog;
HashMap<String, String> map;
JSONArray dataa;
// SimpleAdapter adp;
Button b1, b2, b3;
/// sanket
ArrayList<Allcategories> list = new ArrayList<Allcategories>();
public MainCategories(Context mainActivity, int id) {
// TODO Auto-generated constructor stub
this.c = mainActivity;
this.id = id;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
SharedPreferences sp = c.getSharedPreferences("key", 0);
User_id = sp.getString("userid=", User_id);
countryid = sp.getString("countryid", countryid);
v = inflater.inflate(R.layout.categories_tab, container, false);
lv2 = (ListView) v.findViewById(android.R.id.list);
if (FirstTab.adp == null) {
new CategoryTest().execute();
} else {
lv2.setAdapter(FirstTab.adp);
}
lv2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
for (int i = 0; i < subList.size(); i++) {
subID = list.get(position).get(i).getList().getsubcatId();
subnameData = list.get(position).get(i).getList().getsubcatname();
subCountData = list.get(position).get(i).getList().getsubcatcount();
Log.v("ALLDATA", subnameData + "/" + "/" + "/"
+ subCountData);
}
String catid = listing.get(position).getCategoryid();
int mycatID = Integer.parseInt(catid);
Log.v("CAtegory ID", mycatID + "");
addfragment(new CategoriesListClick(c, subID, mycatID,
subnameData, subCountData, position), true,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
});
return v;
}
public class CategoryTest extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
url = String.format(Common.view_main_category + "country_id=%s",
countryid);
Log.v("CateGory URL:", url);
jobj = wservice.getjson(url);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONObject jdata = jobj.getJSONObject("data");
datas = jdata.getJSONArray("allcategories");
for (int i = 0; i < datas.length(); i++) {
// sanket
Allcategories binAll = new Allcategories();
Log.e("length", "" + datas.length());
ca = datas.getJSONObject(i);
cateGoryID = ca.getString("categoryid");
name = ca.getString("categoryname");
count = ca.getString("categorystorecount");
// map = new HashMap<String, String>();
// map.put("categoryname", name);
// map.put("categorystorecount", "(" + count + ")");
// String countc=c.getString("categoryid");
//sanket
binAll.setcategoryid(cateGoryID);
binAll.setcategoryname(name);
binAll.setcategorystorecount(count);
Log.e(name, count);
if (ca.has("subcategories")) {
dataa = ca.getJSONArray("subcategories");
for (int j = 0; j < dataa.length(); j++) {
JSONObject d = dataa.getJSONObject(j);
// subList = new ArrayList<subCateData>();
subCategoryId = d.getString("subcategoryid");
subname = d.getString("subcategoryname");
subcount = d.getString("subcategorystorecount");
// map.put("subcategoryid", subCategoryId);
// map.put("subcategoryname", subname);
// map.put("subcategorystorecount", "(" + subcount
// + ")");
//// sanket
ArrayList<subCateData> sublist = new ArrayList<subCateData>();
subCateData binSub = new subCateData();
binSub.setsubcatId(subCategoryId);
binSub.setsubcatname(subname);
binSub.setsubcatcount(subcount);
subList.add(new subCateData(subCategoryId, subname,
subcount));
/*
* Log.v("This is Data for Sub:",
* map.get("subcategoryname").toString());
*/
sublist.add(binSub);
}
/// sanket note : make arraylist of subdata in Allcategories class and generate getter and settter
binAll.setList(sublist);
} else {
System.out.println("JSONArray is null");
}
listing.add(new Allcategories(cateGoryID, name, count));
list.add(binAll);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.v("Size", listing.size() + "");
FirstTab.adp = new MyCustom(c, listing);
lv2.setAdapter(FirstTab.adp);
}
}
void addfragment(Fragment fragment, boolean addBacktoStack, int transition) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addBacktoStack)
ft.addToBackStack(null);
ft.commit();
}
class MyCustom extends BaseAdapter {
Context Mcontext;
ArrayList<Allcategories> thisCatList;
LayoutInflater inflater;
public MyCustom(Context c, ArrayList<Allcategories> listing) {
// TODO Auto-generated constructor stub
this.Mcontext = c;
this.thisCatList = listing;
inflater = LayoutInflater.from(Mcontext);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return thisCatList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
if (v == null) {
v = inflater.inflate(R.layout.list_categories, parent, false);
TextView catName = (TextView) v.findViewById(R.id.txtcname);
TextView catCount = (TextView) v.findViewById(R.id.txtccount);
catName.setText(thisCatList.get(position).getCategoryname());
catCount.setText("(" + ""
+ thisCatList.get(position).getCategorystorecount()
+ "" + ")");
Log.v("CatCount", catCount.getText().toString());
}
// TODO Auto-generated method stub
return v;
}
}

Missing data in Section list view in Android?

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.");
}
}
}
}

Categories

Resources