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;
}
}
Related
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;
}
}
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;
}
}
I have created a Custom listview and set data by parsing a link and sorted them inside the list. Now when I am going to make a click and get the value of the individual object of a row I can't get the object of clicked row.
public class MainActivity extends Activity implements OnChildClickListener,
OnItemClickListener {
private ExpandableListView mExpandableListView;
private List<GroupEntity> mGroupCollection;
String URL;
ArrayList<EventParsingClass> EventObject_Collection = new ArrayList<EventParsingClass>();
ArrayList<Date> DateArray = new ArrayList<Date>();
ArrayList<ArrayList<EventParsingClass>> arrayOfEventDescription = new ArrayList<ArrayList<EventParsingClass>>();
MyListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_mainactivity);
prepareResource();
initPage();
URL = "http://..............";
ParsingWithURL(URL);
}
private void ParsingWithURL(String uRL2) {
// TODO Auto-generated method stub
new JSONPARSINGFOREVENTSTREAM().execute(URL);
}
private class JSONPARSINGFOREVENTSTREAM extends
AsyncTask<String, Void, String> {
private final String TAG_ID = "id";
private final String TAG_Title = "title";
private final String TAG_Description = "description";
private final String TAG_StartDate = "start_datetime";
private final String TAG_EndDate = "end_datetime";
private final String TAG_City = "place_city";
private final String TAG_Club = "place_club";
private final String TAG_AgeLimit = "event_agelimit";
private static final String TAG_Event_streamable = "data";
EventParsingClass EPC;
JSONArray streamable = null;
ProgressDialog pDialog;
#SuppressLint("SimpleDateFormat")
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Log.d("************PARAMS", arg0[0]);
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(arg0[0]);
try {
streamable = json.getJSONArray(TAG_Event_streamable);
for (int i = 0; i < streamable.length(); i++) {
EPC = new EventParsingClass();
JSONObject c = streamable.getJSONObject(i);
EPC.setId(c.getString(TAG_ID));
EPC.setPlace_city(c.getString(TAG_City));
EPC.setPlace_club(c.getString(TAG_Club));
EPC.setTitle(c.getString(TAG_Title));
EPC.setDescription(c.getString(TAG_Description));
EPC.setSratdate_time(c.getString(TAG_StartDate));
EPC.setEnddate_time(c.getString(TAG_EndDate));
EPC.setEvent_agelimit(c.getString(TAG_AgeLimit));
long difference = EPC.geEnddate_time_date().getTime()
- EPC.getSratdate_time_date().getTime();
int day_difference = (int) (difference / (1000 * 3600 * 24));
// Log.d("Difference", "" + day_difference);
if (day_difference == 0) {
AddDay(EPC.getSratdate_time_date());
} else {
if (DateArray.size() == 0) {
DateArray.add(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
DateArray.add(Constructed_value);
}
} else {
AddDay(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
AddDay(Constructed_value);
}
}
}
EventObject_Collection.add(EPC);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private void AddDay(Date value) {
// TODO Auto-generated method stub
if (DateArray.size() == 0) {
DateArray.add(value);
} else {
boolean b = true;
for (Date s : DateArray) {
if (s.equals(value)) {
b = false;
break;
}
}
if (b) {
DateArray.add(value);
}
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("+++++++++++++++++++++++number of Items in List", ""
+ DateArray.size());
AddDetailedItemToListView();
AddHeaderItemsToListView();
pDialog.dismiss();
}
private void AddDetailedItemToListView() {
// TODO Auto-generated method stub
for (Date s : DateArray) {
ArrayList<EventParsingClass> constructed_arrayfor_items = new ArrayList<EventParsingClass>();
for (int g = 0; g < EventObject_Collection.size(); g++) {
EventParsingClass EVPC = EventObject_Collection.get(g);
long new_startdate = EVPC.getSratdate_time_date().getTime();
long new_endtdate = EVPC.geEnddate_time_date().getTime();
long date = s.getTime();
if (date >= new_startdate && date <= new_endtdate) {
Log.d("^^^^^^^^^^^ Value Of Date ", "" + s);
Log.d("^^^^^^^^^^^ Value Of StartDay ",
"" + EVPC.getSratdate_time_date());
Log.d("^^^^^^^^^^^ Value Of EndDay ",
"" + EVPC.geEnddate_time_date());
constructed_arrayfor_items.add(EVPC);
}
}
arrayOfEventDescription.add(constructed_arrayfor_items);
Log.d("^^^^^^^^^^^^^^^^^^^arrayOfEventDescription", ""
+ arrayOfEventDescription);
}
}
private void AddHeaderItemsToListView() {
// TODO Auto-generated method stub
ListView lv = (ListView) findViewById(R.id.list_evevnt);
LayoutInflater i = LayoutInflater.from(MainActivity.this);
List<Item> items = new ArrayList<Item>();
int length_of_datearray = DateArray.size();
Log.d("!!!!!!!!!!!!!!!", "" + DateArray.size());
Log.d("EEEEEEEEEEEEEEEEEEEE", "" + arrayOfEventDescription.size());
for (ArrayList<EventParsingClass> It : arrayOfEventDescription) {
Log.d("", "" + It.size());
for (EventParsingClass oETC : It) {
Log.d("*******" + oETC.getTitle(),
"" + oETC.getSratdate_time_date());
}
}
for (int m = 0; m < length_of_datearray; m++) {
String day_of_header = (String) android.text.format.DateFormat
.format("EEEE", DateArray.get(m));
String month_of_header = (String) android.text.format.DateFormat
.format("MMM", DateArray.get(m));
String date_of_header = (String) android.text.format.DateFormat
.format("dd", DateArray.get(m));
String total_header = day_of_header + " " + month_of_header
+ " " + date_of_header;
items.add(new Header(i, "" + total_header));
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(m);
for (int h = 0; h < Arraylist_for_loop.size(); h++) {
String description = Arraylist_for_loop.get(h).getId();
String title = Arraylist_for_loop.get(h).getTitle();
String place_city = Arraylist_for_loop.get(h)
.getPlace_city();
String age_limit = Arraylist_for_loop.get(h)
.getEvent_agelimit();
String dayOfTheWeek = (String) android.text.format.DateFormat
.format("EEEE", Arraylist_for_loop.get(h)
.getSratdate_time_date());
String DayofWeek = dayOfTheWeek;
if (!(dayOfTheWeek == day_of_header)) {
DayofWeek = day_of_header;
}
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String Today = sdf.format(d);
String Value_of_today = "";
if (Today.contentEquals(DayofWeek)) {
Value_of_today = "Today";
}
items.add(new EventItem(i, Value_of_today, DayofWeek,
"12:00", title, description, place_city, "10",
age_limit));
}
}
MyListAdapter adapter = new MyListAdapter(MainActivity.this, items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
}
private void prepareResource() {
mGroupCollection = new ArrayList<GroupEntity>();
for (int i = 1; i < 3; i++) {
GroupEntity ge = new GroupEntity();
ge.Name = "City " + i;
for (int j = 1; j < 4; j++) {
GroupItemEntity gi = ge.new GroupItemEntity();
gi.Name = "Venu" + j;
ge.GroupItemCollection.add(gi);
}
mGroupCollection.add(ge);
}
}
private void initPage() {
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
ExpandableListAdapter adapter = new ExpandableListAdapter(this,
mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(getApplicationContext(), childPosition + "Clicked",
Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
EventParsingClass obj = (EventParsingClass) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), obj.getPlace_city() + "Clicked",Toast.LENGTH_LONG).show();
}
}
How can I proceed in these two scenarios?
EventParsingClass EPSP= ??? and
EPSP.getid= ??
fetch[0]="XXX"
fetch[1]="YYY"
fetch[2]="ZZZ"
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), fetch[position] + "Clicked",
Toast.LENGTH_LONG).show();
}
just declare fetch[position] to get the value of clicked item. hope this will give you some solution.
Use int position to find out values from your data list (array list or what ever you used).
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), EPSP.getid(position) + "Clicked",Toast.LENGTH_LONG).show();
}
EventItem item = (EventItem) parent.getItemAtPosition(position);
Now you have a hold of EventItem. So you can start using the get methods of your EventItem class in order to get whatever you want from it.
I got the solution:
EventParsingClass new_method(int value) {
int item_count = 0;
for (int i = 0; i < arrayOfEventDescription.size(); i++) {
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(i);
item_count++;
for (int j = 0; j < Arraylist_for_loop.size(); j++) {
if (value == item_count) {
return Arraylist_for_loop.get(j);
}
item_count++;
}
}
return null;
}
And call it from here:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
EventParsingClass newObject = new_method(arg2);
if (newObject == null) {
} else {
Log.d("Generated Value Id : ", "" + newObject.getId());
Toast.makeText(getApplicationContext(),
"Item Clicked" + arg2 + "-----" + newObject.getTitle(),
Toast.LENGTH_LONG).show();
}
}
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