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.
Related
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¶ms=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
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.
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// 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_NAME, name);
map.put(TAG_EMAIL, email);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL },
new int[] { R.id.name, R.id.email });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
startActivity(in);
}
});
}
}
Using this Class am able to print data after Parsing In Listview name and email .
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_NAME = "name";
Button next;
Button Previous;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
Previous = (Button) findViewById(R.id.button1);
next = (Button) findViewById(R.id.button2);
Previous.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
// getting intent data
getdata();
}
public void getdata() {
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
lblName.setText(name);
}
}
I have apply # button On For Next and another for previous if click on Next it should display Next id name in SingleMenuItemActivity Class if click on Previous it should display Previous id Name in SingleMenuItemActivity . please tell me how i ll do this . i have tried and doing First time BUt not able to do i don't know how i will call all Ids and create function so that it should work
I have applied # button On For Next and another for previous if click
on Next it should display Next id name in SingleMenuItemActivity Class
if click on Previous it should display Previous id Name in
SingleMenuItemActivity . please tell me how I Will do this.
=> You can fetch previous/next records by doing ++/-- id field, once you have that particular record in terms of Cursor, you can fetch and display particular field value and display the same in particular view.
Or
Second solution is to get all the records at a time and fetch previous/next record by using below methods:
mCursor.moveToNext() // for next record from cursor
mCursor.moveToPrevious() // for previous record from cursor
By looking at above different solutions, I would say 1st method is easy when you have thousands of records because there way you won't have to manage thousand of records but a single record. Decision can be taken based on the number of records and your requirement.
Update:
After having talk with you in #AndroidDev chatroom, I came to know your doubt exactly, you should have mentioned earlier and it could have saved time.
Anyway, now as you want to implement prev/next in your SingleMenuItemActivity and as you are already having contactList which you have prepared in AndroidJSONParsingActivity, I would suggest you to pass ArrayList<HashMap<String, String>> from AndroidJSNOParsingActivity to SingleMenuItemActivity.
Now, as you are having complete list, you can fetch prev/next item.
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;
}
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
static final int MENU_MANUAL_REFRESH = 0;
static final int MENU_DISABLE_SCROLL = 1;
static final int MENU_SET_MODE = 2;
private LinkedList<String> mListItems;
//private PullToRefreshView mPullRefreshListView;
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// 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_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is My parsing COde i m able to get String value now i have Put JsonParser class in My project .
public class PullToRefreshListActivity extends Activity {
static final int MENU_MANUAL_REFRESH = 0;
static final int MENU_DISABLE_SCROLL = 1;
static final int MENU_SET_MODE = 2;
private PullToRefreshView mPullRefreshListView;
private ArrayAdapter<String> mAdapter;
private static String url = "http://api.androidhive.info/contacts/";
/** Called when the activity is first created. */
private LinkedList<String> mListItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pull_to_refresh_listview);
mPullRefreshListView = (PullToRefreshView) findViewById(R.id.pull_refresh_list);
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshListView.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
mPullRefreshListView.setLastUpdatedLabel(DateUtils
.formatDateTime(getApplicationContext(),
System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_ABBREV_ALL));
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
ListView actualListView = mPullRefreshListView.getRefreshableView();
mListItems = new LinkedList<String>();
mListItems.addAll(Arrays.asList(mStrings));
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mListItems);
// You can also just use setListAdapter(mAdapter)
actualListView.setAdapter(mAdapter);
}
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
return mStrings;
}
#Override
protected void onPostExecute(String[] result) {
mListItems
.addFirst("Added after refresh..New Version Coming soon J-elly Bean");
mAdapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been refreshed.
mPullRefreshListView.onRefreshComplete();
super.onPostExecute(result);
}
}
private String[] mStrings = { "A-stro", "B-ender", "C-upcake", "E-clair",
"F-royo", "G-ingerbread", "H-oneycomb", "I-ce Cream Sandwich ",
"Android Versions From iamvijayakumar.blogspot.com" };
}
This is Dummy Example for PullToRefreshListview which i did. Now I want to Integrate so that i can display data in ListView with Pull To Refresh. Can u please help me how to integrate? Where i will place code for parsing and all?? Please help me .
In the Dummy Example, You given simply replace Adapter creation by using the below which is used to set data using Hashmap list. TAG_ID etc are used to be columns. Create an xml with name row and put 4 textview in the row layout and give them names as below which I have used in int array. Then set this adapter to listview.
mAdapter= new SimpleAdapter(this, mylist, R.layout.row,
new String[] {TAG_ID, TAG_NAME, TAG_EMAIL,TAG_PHONE_MOBILE}, new int[]
{R.id.tvtagid, R.id.tvtagname, R.id.tvtagemail,R.id.tvtagphone});
In the above adapter mylist is an Arraylist of your HashMap objects.