Declaring float value, get float value - java

I would like to ask
If I've problem trying to change my code for lat and lng into float,
can anyone guide me with it.
previously, it is in string, but now i would like to decalre it as float.
I've done some, but I not sure if it is correctly done.
public class AndroidXMLParsingActivity extends ListActivity {
static final String KEY = "weatherFilter";
String URL = "";
// XML node keys
static final String KEY_EVENT = "event"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_URL = "url";
static final String KEY_DESC = "description";
static final String KEY_START_TIME = "start_time";
static final String KEY_STOP_TIME = "stop_time";
static final String KEY_VENUE_NAME = "venue_name";
static final String KEY_COUNTRY_NAME = "country_name";
static final String KEY_VENUE_ADDRESS = "venue_address";
static final String KEY_VENUE = "venue";
static final float KEY_LATITUDE = "latitude";
static final float KEY_LONGITUDE = "longitude";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent in = getIntent();
URL = in.getStringExtra(KEY);
final 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_EVENT);
// 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_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_URL, parser.getValue(e, KEY_URL));
map.put(KEY_DESC, "Description: " + parser.getValue(e, KEY_DESC));
map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
map.put(KEY_STOP_TIME, parser.getValue(e, KEY_STOP_TIME));
map.put(KEY_VENUE_NAME, parser.getValue(e, KEY_VENUE_NAME));
map.put(KEY_COUNTRY_NAME, parser.getValue(e, KEY_COUNTRY_NAME));
map.put(KEY_VENUE_ADDRESS, parser.getValue(e, KEY_VENUE_ADDRESS));
float lat=Float.parseFloat(KEY_LATITUDE);
float lng=Float.parseFloat(KEY_LONGITUDE);
map.put(KEY_VENUE, parser.getValue(e, KEY_VENUE_NAME) + ", " + parser.getValue(e, KEY_VENUE_ADDRESS));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_TITLE, KEY_DESC, KEY_COUNTRY_NAME,
KEY_VENUE , KEY_LATITUDE,KEY_LONGITUDE, KEY_START_TIME, }, new int[] {
R.id.title, R.id.description, R.id.countryName, R.id.venueName, R.id.lat,R.id.lng,
R.id.startTime });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.description))
.getText().toString();
String venue = ((TextView) view.findViewById(R.id.venueName))
.getText().toString();
String lat = ((TextView) view.findViewById(R.id.lat))
.getText().toString();
String lng = ((TextView) view.findViewById(R.id.lng ))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_VENUE, venue);
in.putExtra(KEY_LATITUDE, lat);
in.putExtra(KEY_LONGITUDE, lng);
startActivity(in);
}
});
}
}

Since you've cluttered your problem with all of your code it's not easy to identify all of the problems with your code, however this seems obvious:
You will need to replace
float lat=Float.parseFloat(KEY_LATITUDE);
with
float lat=Float.parseFloat((String) map.get(KEY_LATITUDE));

You seem to be quite confused. You need to parse the values into floats from the XML parser. Change this:
float lat=Float.parseFloat(KEY_LATITUDE);
float lng=Float.parseFloat(KEY_LONGITUDE);
To:
float lat=Float.parseFloat(parser.getValue(KEY_LATITUDE));
float lng=Float.parseFloat(parser.getValue(KEY_LONGITUDE));
Otherwise you're just parsing "longitude" and "latitude" into floats which obviously won't work.

Related

setOnScrollListener(...) in AbsListView not applicable for (new Runnable(){}) when trying to automatically load new items into ListView after scroll

I want to display first 10 item continue to upload to 10 item when they reach the end of the list. The error: "The method setOnScrollListener(AbsListView.OnScrollListener) in the type AbsListView is not applicable for the arguments (new Runnable(){})" in line list=getListView().setOnScrollListener(this);. How to fix?
public class CustomizedListView extends ListActivity implements OnScrollListener{
private ProgressDialog pDialog;
// All static variables
static final String URL = "https://api.api2cart.com/v1.0/product.list.xml?api_key=6aed775211e8c3d556db063d12125d2d&store_key=ed58a22dfecb405a50ea3ea56979360d&start=0&count=19&params=id,u_model,name,price,images,short_description";
// XML node keys
static final String KEY_SONG = "product"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "u_model";
static final String KEY_ARTIST = "name";
static final String KEY_DURATION = "price";
static final String KEY_THUMB_URL = "http_path";
static final String KEY_SHORT_DESCRIPTION = "short_description";
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> songsList;
//#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songsList = new ArrayList<HashMap<String, String>>();
new LoadCatalog().execute();
}
public void onScroll(AbsListView view, int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = /* maybe add a padding */
firstVisible + visibleCount >= totalCount;
if(loadMore) {
adapter.count += visibleCount; // or any other amount
adapter.notifyDataSetChanged();
}
}
public void onScrollStateChanged(AbsListView v, int s) { }
class LoadCatalog extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CustomizedListView.this);
pDialog.setMessage("Загрузка каталога ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_SHORT_DESCRIPTION, parser.getValue(e, KEY_SHORT_DESCRIPTION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
return null;
}
public void onScroll(AbsListView view, int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = /* maybe add a padding */
firstVisible + visibleCount >= totalCount;
if(loadMore) {
adapter.count += visibleCount; // or any other amount
adapter.notifyDataSetChanged();
}
}
public void onScrollStateChanged(AbsListView v, int s) { }
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
list=getListView().setOnScrollListener(this);
adapter=new LazyAdapter(CustomizedListView.this, songsList);
list.setAdapter(adapter);
}
});
} }}
Change "this" for CustomizedListView.this, with "this" you are actually refering to the Runnable Object you created inside the parameters of runOnUiThread method, you should point to the class that implements the Scroll Listener by using "CustomizedListView.this" (in case CustomizedListView implements the Scroll Listener interface)
Hope this Helps.
Regards
#Override
public void onStart() {
super.onStart();
getListView().setOnScrollListener(this);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}

New activity when click on ListView

I treat XML and deduce which category parent_id = 0. Each line in the list has a unique id. How to display the list of strings that Activity belong to this line? (eg string has id = 1. When you click on this line you want to display a string in which the parent_id = 1). Need to use the new Activity or can use CatalogActivity.java?
CatalogActivity.java
public class CatalogActivity extends ListActivity {
private ProgressDialog pDialog;
static final String URL = "https://api.api2cart.com/v1.0/category.list.xml?api_key=6aed775211e8c3d556db063d12125d2d&store_key=ed58a22dfecb405a50ea3ea56979360d&start=0&count=38&params=id,name,parent_id,images";
static final String KEY_ITEM = "category";
static final String KEY_ID = "id";
static final String KEY_PARENT_ID = "parent_id";
static final String KEY_TITLE = "name";<br>
static final String KEY_THUMB_URL = "http_path";
String Parend_id;
int id_parent;
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> catalogList;
//#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
catalogList= new ArrayList<HashMap<String, String>>();
new LoadCatalog().execute();
}
class LoadCatalog extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CatalogActivity.this);
pDialog.setMessage("Загрузка каталога ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all song nodes <song>
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);
Parend_id=parser.getValue(e, KEY_PARENT_ID);
if(Parend_id.equals("0")) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
catalogList.add(map);
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
list=getListView();
adapter=new LazyAdapter(CatalogActivity.this, catalogList);
list.setAdapter(adapter);
}
});
// list=(ListView)findViewById(R.id,list);
// Getting adapter by passing xml data ArrayList
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent showInfo = new Intent(getApplicationContext(), CatalogActivity.class);
startActivity(showInfo);
}
});
}
}
}
example XML file (XML rendered as a PNG)
When I click on Components in ListView put Mac as id Components = parent_id Mac

Listview becomes empty after giving the keyword in search bar in android

Currently i'm working on How to find the items from the listview when given the keyword for the item in edittext, the listview becomes empty and the output is displaying in toast message, can anybody help like how to make the found "item" to display it in listivew?
public class Home extends ListActivity {
//how many to load on reaching the bottom
int itemsPerPage = 15;
boolean loadingMore = false;
ArrayList<String> songsList;
ListView list;
LazyAdapter adapter, adapter1;
JSONArray posts;
//ArrayList thats going to hold the search results
ArrayList<HashMap<String, String>> searchResults;
LayoutInflater inflater;
// All static variables
static final String URL = "http://abc.net/ads/?json=get_recent_posts";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
private static final String DEBUGTAG = null;
protected static final String TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText searchBox=(EditText) findViewById(R.id.search);
final ListView list=(ListView)findViewById(android.R.id.list);
//get the LayoutInflater for inflating the customomView
//this will be used in the custom adapter
inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
//searchResults=OriginalValues initially
searchResults=new ArrayList<HashMap<String, String>>(songsList);
// Getting adapter by passing json data ArrayList
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
String searchString = searchBox.getText().toString();
int textLength = searchString.length();
//clear the initial data set
searchResults.clear();
for (int i = 0; i < songsList.size(); i++) {
String playerName = songsList.get(i).get("title").toString();
if (textLength <= playerName.length()) {
//compare the String in EditText with Names in the ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(0, textLength)))
Toast.makeText(getApplicationContext(), playerName, 1).show();
Home.this.adapter.getFilter();
searchResults.add(songsList.get(i));
Log.d(TAG, "title");
}
}
adapter.notifyDataSetChanged();
list.setAdapter(new ArrayAdapter<String>
(Home.this,
R.layout.activity_home));
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
Home.this.adapter.getFilter();
}
});
adapter.notifyDataSetChanged();
list.setAdapter(new ArrayAdapter<String>(Home.this, R.layout.activity_home));
You are not giving any data set to populate the ListView.
Just like you initially populated the ListView with songsList data
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
use:
adapter = new LazyAdapter(this, searchResults);
list.setAdapter(adapter);
try this,
edittext code for search
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter1.getFilter().filter(s.toString());
}
........
add arraylist to listview to display
adapter1 = new MyAdapter(MainActivity.this, mProductArrayList);
lvProducts.setAdapter(adapter1);
Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
private ArrayList<Product> mOriginalValues; // Original Values
private ArrayList<Product> mDisplayedValues; // Values to be displayed
LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<Product> mProductArrayList) {
this.mOriginalValues = mProductArrayList;
this.mDisplayedValues = mProductArrayList;
inflater = LayoutInflater.from(context);
}
..........
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.llContainer = (LinearLayout)convertView.findViewById(R.id.llContainer1);
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
holder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setText(mDisplayedValues.get(position).name);
holder.tvPrice.setText(mDisplayedValues.get(position).price+"");
holder.llContainer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(MainActivity.this, mDisplayedValues.get(position).price.toString() , Toast.LENGTH_SHORT).show();
}
});
return convertView;
}

add selected product to cart in android

I have developed one android list view app using xml parsing.this is done for my first page.
After i have to click any product from list means am getting the detailed product description in displayed on next activity.it is also done.
Here i have to implement one part.
the detailed order page have one button add to cart.here i have to click this button means the selected product is added on my cart.how can i implement this.please help me.
This is my first activity(list view using xml parsing):
public class CustomizedListView extends Activity {
// All static variables
static final String URL = "http://192.168.1.168/tbc/watches.xml";
// XML node keys
static final String KEY_SONG = "Product"; // parent node
static final String KEY_ID = "productid";
static final String KEY_TITLE = "Name";
static final String KEY_ARTIST = "ProductURL";
static final String KEY_DURATION = "Price";
static final String KEY_THUMB_URL = "Image";
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, songsList);
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 title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String duration = ((TextView) view.findViewById(R.id.duration)).getText().toString();
String artist = ((TextView) view.findViewById(R.id.artist)).getText().toString();
String thumb_image = ((ImageView) view.findViewById(R.id.list_image)).getImageMatrix().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_DURATION, duration);
in.putExtra(KEY_ARTIST, artist);
in.putExtra(KEY_THUMB_URL, thumb_image);
startActivity(in);
}
});
}
}
This is detailed description activity:
public class SingleMenuItemActivity extends Activity {
Button cart;
// XML node keys
static final String KEY_TITLE = "Name";
static final String KEY_DURATION = "Price";
static final String KEY_ARTIST = "ProductURL";
static final String KEY_THUMB_URL = "Image";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
int productIndex = getIntent().getExtras().getInt(CustomizedListView.URL);
//final CustomizedListView selectedProduct = songsList.getInt(productIndex);
cart = (Button)findViewById(R.id.cart);
cart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//cart.add(selectedProduct);
finish();
}
});
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String title = in.getStringExtra(KEY_TITLE);
String duration = in.getStringExtra(KEY_DURATION);
String artist = in.getStringExtra(KEY_ARTIST);
final String thumb_image = in.getStringExtra(KEY_THUMB_URL);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.cost_label);
TextView lblDesc = (TextView) findViewById(R.id.description_label);
ImageView imgv = (ImageView) findViewById(R.id.image_label);
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
lblName.setText(title);
lblCost.setText(duration);
lblDesc.setText(artist);
imageLoader.DisplayImage(thumb_image, imgv);
}
}
I have to add add to cart button in these 2nd activity.what condition i have to put here for selected product item is add to cart .please give me solution for some useful coding wise.please help me.

Android listview sorting using xml parsing

I am having a bit of trouble with android. I have a sorted listview of items retrieved from a database using xml parsing.
i have to display the product on list view with sorted by price
This is my xml feed:
<Feed>
<category>
<Product>
<Name>New Masters of Flash</Name>
<Price>79.99</Price>
</Product>
<Product>
<Name>Professional Java Server Programming</Name>
<Price>63.99</Price>
</Product>
<Product>
<Name>Designing Web Usability</Name>
<Price>80.00</Price>
</Product>
</category>
</Feed>
This is my android code:
public class Catalogue extends Activity {
// static String URL = "https://dl.dropbox.com/u/48258247/catalogue.json";
static final String URL = "http://192.168.1.168/xcart432pro/internet.xml";
static String KEY_CATEGORY = "Product";
static final String KEY_TITLE = "Name";
static final String KEY_DESCRIPTION = "Description";
static final String KEY_COST = "Price";
static final String KEY_THUMB_URL = "Image";
ListView list;
ListAdapter adapter;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_CATEGORY);
// looping through all song nodes <song>
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_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_DESCRIPTION, parser.getValue(e, KEY_DESCRIPTION));
map.put(KEY_COST, parser.getValue(e, KEY_COST));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
list=(ListView)findViewById(R.id.listView1);
// Getting adapter by passing xml data ArrayList
adapter=new ListAdapter(this, songsList);
list.setAdapter(adapter);
// Bundle bundle = getIntent().getExtras();
// KEY_CATEGORY=bundle.getString(KEY_SUBCATE);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent(
Catalogue.this,
com.ssmobileproductions.catalogue.SingleMenuItem.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_DESCRIPTION, map.get(KEY_DESCRIPTION));
in.putExtra(KEY_THUMB_URL, map.get(KEY_THUMB_URL));
in.putExtra(KEY_COST, map.get(KEY_COST));
startActivity(in);
}
});
Here i have to display the product on list view with sorted by price.How can i do.please help me programmatically in android.
Edit:
I have added some code like below:
Button btninsert = (Button) findViewById(R.id.sort);
btninsert.setOnClickListener(new View.OnClickListener() {
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
public void onClick(View v) {
Collections.sort(songsList, new PriceComparator());
}
});
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_CATEGORY);
create one class and wrote the code below:
public class PriceComparator implements Comparator<HashMap<String, String>> {
static final String KEY_COST = "Price";
public PriceComparator() {
// TODO Auto-generated constructor stub
}
public int compare(HashMap<String, String> map1, HashMap<String, String> map2) {
return map1.get(KEY_COST).compareTo(map2.get(KEY_COST));
}
Now i have to run the app and click the button means nothing is happened????
But i have to display product list is sorted by price.
I believe you need to use a custom Comparator:
Comparator<HashMap<String, String>> comparator = new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> map1, HashMap<String, String> map2) {
return map1.get(KEY_COST).compareTo(map2.get(KEY_COST));
}
};
And then sort your list before creating your adapter with:
Collections.sort(songsList, comparator);
Addition
You need to do make a few small changes.
Make songsList a field variable, like list and adapter:
ListView list;
ListAdapter adapter;
ArrayList<HashMap<String, String>> songsList; // Add me!
Update how you initialize songsList:
songsList = new ArrayList<HashMap<String, String>>(); // Shorten me!
Change your onClick method:
public void onClick(View v) {
Collections.sort(songsList, comparator);
adapter.notifyDataSetChanged(); // Add me!
}
display the product on list view with sorted by price
=> As you are having ArrayList>, you need to create custom Comparator to make comparison.
For example:
public class PriceComparator implements Comparator<HashMap<String, String>> {
public PriceComparator() {
// TODO Auto-generated constructor stub
}
public int compare(HashMap<String, String> map1, HashMap<String, String> map2) {
return map1.get(KEY_COST).compareTo(map2.get(KEY_COST));
}
}
And to apply this custom comparator to your ArrayList>, do like:
Collections.sort(mylist, new PriceComparator());
Use Hashtable and sort the keys like following:
Here hashTable will contain name and price, and keys will contain the price, so sorting keys and then addind the sorted elements in sortedItems Vector will return you the sorted elements.
Hashtable hash = new Hashtable();
Vector<String> sortedItems = new Vector<String>();
Enumeration enumeration = hash .keys();
Vector keySet = new Vector();
while (enumeration.hasMoreElements()) {
keySet.add(enumeration.nextElement());
}
Collections.sort(keySet);
Iterator i = keySet.iterator();
String str;
while (i.hasNext()) {
str = (String) i.next();
sortedItems.addElement(hash .get(str));
Log.e("", (str + ":" + hash .get(str)));
}

Categories

Resources