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.
Related
i have an app where in a form show the list view. the user can click one of the list view and when clicking the app will move to another activity and it's activity will show some data based on "code" that sent from the list view form. my app is success to move in another activity but doesn't show the data. please help me.
Thank you.
This is my code in list view form :
final ListView lv = (ListView)findViewById(R.id.lv);
String url = "http://192.168.43.244/wewash/listview.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("nama", c.getString("nama"));
map.put("tanggal_keluar", c.getString("tanggal_keluar"));
MyArrList.add(map);
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(halaman_utama.this, MyArrList, R.layout.listview,
new String[] {"nama", "tanggal_keluar","id", ""}, new int[] {R.id.tsnama, R.id.tstglk, R.id.kode, R.id.tsspasi});
lv.setAdapter(sAdap);
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String kode = ((TextView) findViewById(R.id.kode)).getText().toString();
Intent in = new Intent(halaman_utama.this, p_daftar_pakaian.class);
//menampilkan value dari item yg diklik
in.putExtra("id", kode);
startActivity(in);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and it's my code in new activity :
Intent intent = getIntent();
String kode = intent.getStringExtra("id");
String url = "http://192.168.43.244/wewash/listview_detail.php?id="+kode;
try {
JSONArray data = new JSONArray(getJSONUrl(url));
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
String idpk = c.getString("id");
String namapk = c.getString("nama");
String paketpk = c.getString("paket");
String cbiasapk = c.getString("cbiasa");
String ckhususpk = c.getString("ckhusus");
String tglantarpk = c.getString("tanggal_keluar");
String totalpk = c.getString("total");
// String nomorpk = c.getString("no_hp");
atasnama.setText(namapk);
ereview.setText("Id Pelanggan : " +idpk+
"\nNama Pelanggan : "+namapk+
"\nPaket : "+paketpk+
"\nCucian Biasa : "+cbiasapk+" kg"+
"\nCucian Khusus : "+ckhususpk+" item"+
"\nTotal : "+totalpk+" rupiah"+
"\nTanggal Antar : "+tglantarpk);
// enomer.setText(nomorpk);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
and it's the php file
<?php
mysql_connect("localhost","root","");
mysql_select_db("wewash");
$kode=$_GET["id"];
$sql=mysql_query("select * from pakaian where id='$kode'");
$arrayId=array();
if($sql === FALSE) {
die(mysql_error());
}
while($row=mysql_fetch_array($sql)){
$arrayId["id"]=$row["id"];
$arrayId["nama"]=$row["nama"];
$arrayId["tanggal_keluar"]=$row["tanggal_keluar"];
$arrayId["paket"]=$row["paket"];
$arrayId["cbiasa"]=$row["cbiasa"];
$arrayId["ckhusus"]=$row["ckhusus"];
$arrayId["total"]=$row["total"];
}
echo json_encode($arrayId);
?>
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 an app that is showing data in listview ,but i want first row to be inflated by diferent layout , and i did that but since there is gona be a big number of listitems , i want to optimize listview and there is issue. i cant optimize listview when iam filling listview on that way , so how can i put content that should go in fist row inside listview header witch is inflated by some layout ,here is the code of Adapter
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
refLayout.setVisibility(View.GONE);
mBtnNaslovnica = (Button) findViewById(R.id.mBtnNaslovnica);
mBtnNaslovnica.setSelected(true);
TextView txtView=(TextView) findViewById(R.id.scroller);
txtView.setSelected(true);
loadPage();
ImageButton mBtnRefresh = (ImageButton) findViewById(R.id.btnRefresh);
mBtnRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new LoadingTask().execute(URL);
}
});
}
public void loadPage(){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(getIntent().getStringExtra("json"));
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void reloadPage(String jsonstring){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(jsonstring);
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void startNewActivity(){
}
public class LoadingTask extends AsyncTask<String, Object, Object>{
XMLParser parser = new XMLParser();
JSONParser jParser = new JSONParser();
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
protected void onPreExecute(){
content.setClickable(false);
refLayout.setVisibility(View.VISIBLE);
}
#Override
protected Object doInBackground(String... params) {
// TODO Auto-generated method stub
String URL = params[0];
JSONObject json = jParser.getJSONFromUrl(URL);
//String xml = parser.getXmlFromUrl(URL); // getting XML from URL
// getting DOM element
return json;
}
protected void onPostExecute(Object result){
String json;
json = result.toString();
reloadPage(json);
refLayout.setVisibility(View.GONE);
}
}
}
If I got your point - you can go with 2 approaches:
Add headerView to the list. That is just easy as inflate your View and pass it to
addHeaderView(View) of your List. Note: you must add this view before setting the adapter, or it will throw the exception.
However, as your 'header' is representing the same data as all other items, but has different layout - I suggest not to use Header here. Instead, try to implement getItemViewType() in your adapter. http://developer.android.com/reference/android/widget/BaseAdapter.html#getItemViewType(int)
If you'll do - you'll have ability to check which type of layout to return in getView() method. And Android will take care of optimizing and reusing your inflated Views for you, so you can be sure that convertView, passed to your getView will be of the right type and layout.
Please let me know if I should explain with more details.
You can do it like this:
...
convertView.setOnClickListener(new OnItemClick(position));
...
public class OnItemClick implements OnClickListener {
private final int index;
public OnItemClick(int _index) {
this.index = _index;
}
#Override
public void onClick(View v) {
//dosomething
}
}
I am trying to display data from xml file in to grid view in android, but this page is showing one error,can any one please make me clear.....
GridviewSample.java
public class GridviewSample extends Activity
{
// All static variables
static final String URL = "http://54.251.60.177/StudentWebService/StudentDetail.asmx/GetTMSOrders";
// XML node keys
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_CUST = "Cust_Name";
static final String KEY_ORDER = "Order_No";
static final String KEY_FREIGHT = "Freight_Rate";
static final String KEY_STATION1 = "Station_Name";
static final String KEY_STATION2 = "Station_Name1";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gv = (GridView)findViewById(R.id.gridView1);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++)
{
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_CUST, parser.getValue(e, KEY_CUST));
map.put(KEY_ORDER, parser.getValue(e, KEY_ORDER));
map.put(KEY_FREIGHT, parser.getValue(e, KEY_FREIGHT));
map.put(KEY_STATION1, parser.getValue(e, KEY_STATION1));
map.put(KEY_STATION2, parser.getValue(e, KEY_STATION2));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
SimpleAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.grid_item,
new String[] { KEY_CUST, KEY_ORDER, KEY_FREIGHT,KEY_STATION1,KEY_STATION2 }, new int[]
{
R.id.cust, R.id.order, R.id.freight,R.id.statio1,R.id.station2 });
gv.setAdapter(adapter);
gv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> Table, View v,int position, long id)
{
// getting values from selected GridItem
String cust = ((TextView) v.findViewById(R.id.cust)).getText().toString();
String order = ((TextView) v.findViewById(R.id.order)).getText().toString();
String freight = ((TextView) v.findViewById(R.id.freight)).getText().toString();
String station1 = ((TextView) v.findViewById(R.id.statio1)).getText().toString();
String station2 = ((TextView) v.findViewById(R.id.station2)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), Single_gridview_item.class);
in.putExtra(KEY_CUST, cust);
in.putExtra(KEY_ORDER, order);
in.putExtra(KEY_FREIGHT, freight);
in.putExtra(KEY_STATION1, station1);
in.putExtra(KEY_STATION2, station2);
startActivity(in);
}
});
}}
Thanks for you time!..
You should use an AsyncTask to perform the connection because otherwise the main thread can get stuck and Android will exit your application.