Is it possible to reload a ListView once the data is downloaded? Basically I'm updating an app for 4.1 but my ListView downloads and parses an XML file, I know that I have to run this now in a background thread but when I open the activity via a tab the screen is blank. I am not sure how to get this to work or what part of the code I need to use in the background thread, can someone please help. Thank you.
public class ThirdActivity extends ListActivity {
// All static variables
static final String URL = "http://selectukradio.com/SelectUKSchedule.xml"; // http://api.androidhive.info/pizza/?format=xml http://selectukradio.com/SelectUKSchedule.xml
// XML node keys
static final String KEY_ITEM = "day"; // parent node item
static final String KEY_ID = "link"; // id
static final String KEY_NAME = "dj"; // name
static final String KEY_COST = "time"; // cost
static final String KEY_DESC = "tempDay"; // description
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
try{
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_ITEM);
// 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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, parser.getValue(e, KEY_COST)); // "Rs. " +
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(ThirdActivity.this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_COST,KEY_DESC,KEY_ID }, new int[] {
R.id.name, R.id.cost, R.id.day, R.id.link });
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 name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String link = ((TextView) view.findViewById(R.id.link)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_ID, link);
startActivity(in);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
return super.onKeyDown(keyCode, event);
}
}
Nick's comment has upvotes but everyone is forgetting that notifyDataSetChanged() must be called on the adapter, not on the list view.
In this example you are using a SimpleAdapter which takes the list of items in the constructor. So to change the data wrapped by the adapter, you have to update this list and then call notifyDataSetChanged() on the adapter to get the list view to update.
Here's how you could rework the code to solve your problems. All I have done is move the XML download code to an AsyncTask, and moved the list adapter and data items to be instance variables so you can access them when async task completes.
Please note I haven't tested this code, but it should give you the right idea!
public class ThirdActivity extends ListActivity {
// All static variables
static final String URL = "http://selectukradio.com/SelectUKSchedule.xml"; // http://api.androidhive.info/pizza/?format=xml http://selectukradio.com/SelectUKSchedule.xml
// XML node keys
static final String KEY_ITEM = "day"; // parent node item
static final String KEY_ID = "link"; // id
static final String KEY_NAME = "dj"; // name
static final String KEY_COST = "time"; // cost
static final String KEY_DESC = "tempDay"; // description
// Initially set list of items to empty array
ArrayList<HashMap<String, String>> mMenuItems = new ArrayList<HashMap<String, String>>();
SimpleAdapter mAdapter;
UpdateTask mUpdateTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
// Adding menuItems to ListView
mAdapter = new SimpleAdapter(ThirdActivity.this, mMenuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_COST,KEY_DESC,KEY_ID },
new int[] { R.id.name, R.id.cost, R.id.day, R.id.link });
setListAdapter(mAdapter);
// 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 name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String link = ((TextView) view.findViewById(R.id.link)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_ID, link);
startActivity(in);
}
});
// Start an update
updateMenuItems();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
return true; // handled event
}
return super.onKeyDown(keyCode, event);
}
// Call this method to download latest XML file from network and update listview
private void updateMenuItems() {
if (mUpdateTask == null) {
mUpdateTask = new UpdateTask();
mUpdateTask.execute(URL);
}
}
// Async task to download XML on background thread
private class UpdateTask extends AsyncTask<String, Void, String> {
// This method runs on a background.
// Do network operation and returns XML parser, or null on exception
protected String doInBackground(String... url) {
try {
XMLParser parser = new XMLParser();
return parser.getXmlFromUrl(url[0]);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// This method runs on the main thread when the async task completes.
// Make sure you only update your UI from this method!
protected void onPostExecute(String xml) {
if (xml == null) {
// Download failed, display error message or something
return;
}
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
mMenuItems.clear();
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_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, parser.getValue(e, KEY_COST)); // "Rs. " +
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
mMenuItems.add(map);
}
// all done, notify listview adapter to update
mAdapter.notifyDataSetChanged();
}
}
}
Here is the final class
public class ThirdActivity extends ListActivity {
// All static variables
static final String URL = "http://selectukradio.com/SelectUKSchedule.xml"; // http://api.androidhive.info/pizza/?format=xml http://selectukradio.com/SelectUKSchedule.xml
// XML node keys
static final String KEY_ITEM = "day"; // parent node item
static final String KEY_ID = "link"; // id
static final String KEY_NAME = "dj"; // name
static final String KEY_COST = "time"; // cost
static final String KEY_DESC = "tempDay"; // description
String xml = new String();
// Initially set list of items to empty array
ArrayList<HashMap<String, String>> mMenuItems = new ArrayList<HashMap<String, String>>();
SimpleAdapter mAdapter;
UpdateTask mUpdateTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
// Adding menuItems to ListView
mAdapter = new SimpleAdapter(ThirdActivity.this, mMenuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_COST,KEY_DESC,KEY_ID },
new int[] { R.id.name, R.id.cost, R.id.day, R.id.link });
setListAdapter(mAdapter);
// 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 name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String link = ((TextView) view.findViewById(R.id.link)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_ID, link);
startActivity(in);
}
});
// Start an update
updateMenuItems();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
return true; // handled event
}
return super.onKeyDown(keyCode, event);
}
// Call this method to download latest XML file from network and update listview
private void updateMenuItems() {
if (mUpdateTask == null) {
mUpdateTask = new UpdateTask();
mUpdateTask.execute(URL);
}
}
// Async task to download XML on background thread
private class UpdateTask extends AsyncTask<String, Void, XMLParser> {
// This method runs on a background.
// Do network operation and returns XML parser, or null on exception
protected XMLParser doInBackground(String... url) {
try {
XMLParser parser = new XMLParser();
xml = parser.getXmlFromUrl(url[0]);
// xml = parser.getXmlFromUrl(URL); // getting XML
return parser;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// This method runs on the main thread when the async task completes.
// Make sure you only update your UI from this method!
protected void onPostExecute(XMLParser parser) {
if (parser == null) {
// Download failed, display error message or something
return;
}
// String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
mMenuItems.clear();
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_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, parser.getValue(e, KEY_COST)); // "Rs. " +
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
mMenuItems.add(map);
}
// all done, notify listview adapter to update
mAdapter.notifyDataSetChanged();
}
}
}
Related
hello guys I am having problems with my parse data it seems that this extra letters are also being parse i want them remove how to do this in my code, i will post below.
here is my xmlparser.java
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setCoalescing(true);
dbf.setNamespaceAware(true);
if (dbf.isNamespaceAware()==Boolean.TRUE) {
dbf.setNamespaceAware(Boolean.FALSE);
}
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
str = str.replaceAll("<br/>"," \n");
return this.getElementValue(n.item(0));
}
public final String getElemementValue2 ( Node elem) {
Node child;
if( elem != null) {
if (elem.hasChildNodes()) {
for ( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ) {
if(child.getNodeType() == Node.CDATA_SECTION_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
public String getValue3(Element item, String str) {
NodeList n = item.getElementsByTagNameNS("http://purl.org/rss/1.0/modules/content/",str );
String ses = this.getElemementValue2(n.item(0));
String mim =ses.replaceAll("(?s)\\<.*?\\>", " \n");
return mim;
}
}
here is main.java AndroidXMLParsingActivity
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "https://news.instaforex.com/news";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_PUBDATE = "pubDate";
static final String KEY_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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_ITEM);
// 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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_PUBDATE, parser.getValue(e, KEY_PUBDATE));
map.put(KEY_DESCRIPTION, parser.getValue(e, KEY_DESCRIPTION));
// 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_DESCRIPTION, KEY_PUBDATE }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
adapter.setNotifyOnChange(true);
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.name)).getText().toString();
String pubDate = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_PUBDATE, pubDate);
in.putExtra(KEY_DESCRIPTION, description);
startActivity(in);
}
});
}
}
i just wan to parse these codes here in description and i want to stop the parse data before this
please look into this link and check description.
Check out How to strip or escape html tags in Android
You can use Html.fromHtml(stringToEscape).toString(); method to escape the tags whichever you want.
EDITED:
Try to pass the values of the pudate & description by getting from the HashMap as i showned below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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_ITEM);
// 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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_PUBDATE, parser.getValue(e, KEY_PUBDATE));
map.put(KEY_DESCRIPTION, parser.getValue(e, KEY_DESCRIPTION));
// 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_PUBDATE }, new int[] {
R.id.name, R.id.cost });
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) {
String m_pubDate = menuItems.get(position).get(KEY_PUBDATE).toString();
String m_description=menuItems.get(position).get(KEY_DESCRIPTION).toString();
System.out.println("PubDate==>"+m_pubDate+"\n Description===>"+m_description);
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_PUBDATE, m_pubDate);
in.putExtra(KEY_DESCRIPTION, m_description);
startActivity(in);
}
});
}
I hope it will help you.
Thanks.
I have two tabs hosted in my Main Activity (I use ActionBarSherlock).
My fragments load and parse a distant xml to populate the listview.
If I change the device orientation when fragment is fully loaded, it loads again without problem with the new orientation.
But if I change it while the fragment is loading, the app force closes at the completion of loading.
Am I doing something wrong?
public class PartOne extends SherlockListFragment{
// All static variables
static final String URL = "http://Y.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_CAT = "category";
static final String KEY_DESC = "description";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new BackgroundAsyncTask().execute();
}
public class BackgroundAsyncTask extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
#Override
protected void onPreExecute() {
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... paths) {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
if (xml != null) {
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
if(i%2 != 1) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// data to string (to modify them)
String titre = parser.getValue(e, KEY_TITLE);
String categorie = parser.getValue(e, KEY_CAT);
String description = parser.getValue(e, KEY_DESC);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, titre);
map.put(KEY_CAT, categorie);
map.put(KEY_DESC, description);
// adding HashList to ArrayList
menuItems.add(map);
}
}
}
// 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 name = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.categ)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(view.getContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, name);
in.putExtra(KEY_CAT, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
return menuItems;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new SimpleAdapter(getActivity(),
result, R.layout.list_item,
new String[] {KEY_TITLE, KEY_DESC, KEY_CAT},
new int[] {R.id.title, R.id.desciption, R.id.categ});
setListAdapter(adapter);
}
}
Log :
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:278)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.IllegalStateException: Content view not yet created
at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
Handle your task in onConfigurationChanged (Configuration newConfig) mothod,
something like this
Thread th=null;
public void onCreate(bundle savedInstanceState)
{
//Initialize layout
if(th==null) //This is to check whether task is running
{
//Assign your task
th=new Thread();
th.start();
}
}
//handle the same here
public void onConfigurationChanged (Configuration newConfig)
{
//Do the layout changes
if(th==null)//This is to check whether task is running
{
//Assign your task
th=new Thread();
th.start();
}
}
It is my mainactivity code. Following is my main activity code and it shows four errors:
adapter cannot be resolved to a type
Syntax error on token ")", { expected after this token
Syntax error on token "adapter", VariableDeclaratorId expected after this token.
Source code:
public class HospitalParseActivity extends ListActivity {
//url where request is made
private static String url="url";
//JSON node names
private static final String TAG_NETFOX="transfer";
private static final String TAG_DATE="date";
private static final String TAG_CWEB="c_web";
private static final String TAG_CBANK="c_bank";
private static final String TAG_CCASH="c_cash";
private static final String TAG_SWEB="s_web";
private static final String TAG_SBANK="s_bank";
private static final String TAG_SCASH="s_cash";
//creation of JSONArray
JSONArray netfoxlimited=null;
private List<? extends Map<String, ?>> contactList;
#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
netfoxlimited = json.getJSONArray(TAG_NETFOX);
// looping through All Contacts
for(int i = 0; i < netfoxlimited.length(); i++){
JSONObject c = netfoxlimited.getJSONObject(i);
// Storing each json item in variable
String date = c.getString(TAG_DATE);
String c_web = c.getString(TAG_CWEB);
String c_bank = c.getString(TAG_CBANK);
String c_cash = c.getString(TAG_CCASH);
String s_web = c.getString(TAG_SWEB);
String s_bank = c.getString(TAG_SBANK);
String s_cash = c.getString(TAG_SCASH);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DATE, date);
map.put(TAG_CWEB, c_web);
map.put(TAG_CBANK, c_bank);
map.put(TAG_CCASH, c_cash);
map.put(TAG_SWEB, s_web);
map.put(TAG_SBANK, s_bank);
map.put(TAG_SCASH, s_cash);
// 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_DATE, TAG_CWEB, TAG_CBANK,TAG_CCASH, TAG_CWEB,TAG_CBANK, TAG_CCASH }, new int[] {
R.id.date, R.id.cweb, R.id.cbank,R.id.sweb,R.id.sbank,R.id.scash });
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 dt = ((TextView) view.findViewById(R.id.date)).getText().toString();
String web = ((TextView) view.findViewById(R.id.cweb)).getText().toString();
String bank = ((TextView) view.findViewById(R.id.cbank)).getText().toString();
String cash = ((TextView) view.findViewById(R.id.ccash)).getText().toString();
String web1 = ((TextView) view.findViewById(R.id.sweb)).getText().toString();
String bank1 = ((TextView) view.findViewById(R.id.sbank)).getText().toString();
String cash1 = ((TextView) view.findViewById(R.id.scash)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_DATE, dt);
in.putExtra(TAG_CWEB, web);
in.putExtra(TAG_CBANK, bank);
in.putExtra(TAG_CCASH, cash);
in.putExtra(TAG_SWEB, web1);
in.putExtra(TAG_SBANK, bank1);
in.putExtra(TAG_SCASH, cash1);
startActivity(in);
}
});
}
}
Are you writing code outside the onCreate function? Seems like onCreate function ended at the '}' after the catch block. You may just want to remove that
I am making an app in which I have to add progress dialog in footer View but I am unable to get any progress dialog in footer view:
Main Activity:
I want to add progress dialog in footer in this class
public class MainActivity extends Activity implements OnScrollListener {
// All variables
XmlParser parser;
Document doc;
String xml;
ListView lv;
ListViewAdapter adapter;
ArrayList<HashMap<String, String>> menuItems;
ProgressDialog pDialog;
private String URL = "http://api.androidhive.info/list_paging/?page=1";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
ProgressDialog dialog;
// Flag for current page
int current_page = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.list);
menuItems = new ArrayList<HashMap<String, String>>();
parser = new XmlParser();
xml = parser.getXmlFromUrl(URL); // getting XML
doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// 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_ID, parser.getValue(e, KEY_ID)); // id not using any where
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
// adding HashList to ArrayList
menuItems.add(map);
}
// LoadMore button
dialog=new ProgressDialog(this);
// Button btnLoadMore = new Button(this);
//btnLoadMore.setText("Load More");
// Adding Load More button to lisview at bottom
// lv.addFooterView(dialog);
// I want to use Progress Dialog in footer
/* lv.addFooterView(dialog);*/
// Getting adapter
adapter = new ListViewAdapter(this, menuItems);
lv.setAdapter(adapter);
lv.setOnScrollListener(this);
lv.addFooterView(dialog.getListView());
/**
* Listening to Load More button click event
* */
if(dialog.isShowing())
{
}
/* btnLoadMore.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Starting a new async task
new loadMoreListView().execute();
}
});*/
/**
* Listening to listview single row selected
* **/
lv.setOnItemClickListener(new OnItemClickListener() {
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();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
Test123.class);
in.putExtra(KEY_NAME, name);
startActivity(in);
}
});
}
/**
* Async Task that send a request to url
* Gets new list view data
* Appends to list view
* */
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
if(dialog.isShowing())
{
dialog.cancel();
}
else
{
pDialog = new ProgressDialog(
MainActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
}
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
// increment current page
current_page += 1;
// Next page request
URL = "http://api.androidhive.info/list_paging/?page=" + current_page;
xml = parser.getXmlFromUrl(URL); // getting XML
doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// 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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
// adding HashList to ArrayList
menuItems.add(map);
}
// get listview current position - used to maintain scroll position
int currentPosition = lv.getFirstVisiblePosition();
// Appending new data to menuItems ArrayList
adapter = new ListViewAdapter(
MainActivity.this,
menuItems);
lv.setAdapter(adapter);
// Setting new scroll position
lv.setSelectionFromTop(currentPosition + 1, 0);
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
}
}
public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
dialog.show();
lv.setOnScrollListener(this);
lv.addFooterView(dialog.getListView());
new loadMoreListView().execute();
}
public void onScrollStateChanged(AbsListView arg0, int arg1) {
// TODO Auto-generated method stub
new loadMoreListView().execute();
}
}
Adapter:
public class ListViewAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ListViewAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_item, null);
TextView name = (TextView)vi.findViewById(R.id.name);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
//Setting all values in listview
name.setText(item.get("name"));
return vi;
}
}
XmlParser
public class XmlParser {
// constructor
public XmlParser() {
}
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
Any help will be appreciated.
I think, You want a ProgressBar and not ProgressDialog
Add a new layout pb_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleSmall"
android:indeterminate="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
In code add
view = getLayoutInflater().inflate(R.layout.pb_layout, null);
TextView tv = (TextView)view.findViewById(R.id.textView1);
tv.setText("Please wait..");
ProgressBar pb = (ProgressBar)view.findViewById(R.id.progressBar1);
pb.setIndeterminate(true);
lv.addFooterView(view);
You can only do addFooterView before you do setadapter.
You can write a simple/enhanced custom control with special actions and behaviors. For example a complete menu system on this thread
https://stackoverflow.com/a/11805044/1290995
An enhanced layout is very simpler than the menu in above link.
Some points to make a progressDialog like window:
Use FrameLayout as root view
Design it in an XML Layout file
Inflate it in a subclass of FrameLayout ( in Constructor )
Provide some method like show() , hide(), stop() or everything else you need and implements those actions
Pass a layout to the custom control to use as it's parent like
public void addTo(ViewGroup viewgroup){
viewgroup.addView(this);
}
and more...
If you need more information let me know.
You can Try this:
ProgressDialog myDialog = ProgressDialog.show(MyActivity.this, "Display Information","atthe bottom...", true);
myDialog.getWindow().setGravity(Gravity.BOTTOM);
I have implemented a Custom List View which displays text along with image. The List View fetches data from XML data present over the internet. When the user scrolls down, more data is loaded into the application. Now, I am trying to include a search bar so that when the user searches for some data, the application displays the results returned by the search. The main problem is that the list view doesn't show the correct data when search is performed.
When I check the URL that is being executed by the Search bar in a browser, it shows the correct results, but in Android application it behaves differently.
Below is the code of my Activity that performs this whole work:-
public class OrganizationActivity extends Activity implements OnScrollListener {
int itemsPerPage = 10;
boolean loadingMore = false;
int mPos=0;
// All static variables
static final String URL = "some URL";
static int page_no = 1;
// XML node keys
static final String KEY_ORGANIZATION = "organization"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_CITY = "city";
static final String KEY_STATE = "state";
static final String KEY_IMAGE_URL = "image";
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> orgsList = new ArrayList<HashMap<String, String>>();
private EditText filterText = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
filterText = (EditText) findViewById(R.id.search_box_et);
filterText.addTextChangedListener(new TextWatcher()
{
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
if(arg0.length()==0)
{
list.setAdapter(new LazyAdapter(OrganizationActivity.this, orgsList));
}
list.setAdapter(new LazyAdapter(OrganizationActivity.this, orgsList));
String searchtext = null;
try {
searchtext=URLEncoder.encode(arg0.toString().trim(),"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String urlStr = "myURL?search="+searchtext;
new LoadData().execute(urlStr);
adapter = new LazyAdapter(OrganizationActivity.this, orgsList);
list.setAdapter(adapter);
}
});
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_ORGANIZATION);
// looping through all organization nodes <organization>
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_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_CITY, parser.getValue(e, KEY_CITY));
map.put(KEY_STATE, parser.getValue(e, KEY_STATE));
map.put(KEY_IMAGE_URL, parser.getValue(e, KEY_IMAGE_URL));
// adding HashList to ArrayList
orgsList.add(map);
}
list = (ListView) findViewById(R.id.list);
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.listfooter, null, false);
list.addFooterView(footerView);
// Getting adapter by passing xml data ArrayList
adapter = new LazyAdapter(this, orgsList);
list.setAdapter(adapter);
list.setOnScrollListener(this);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = orgsList.get(position).get(KEY_NAME).toString();
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG)
.show();
}
});
}
private class LoadData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
for (String url : urls) {
// TODO Auto-generated method stub
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_ORGANIZATION);
// looping through all organization nodes <organization>
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_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_CITY, parser.getValue(e, KEY_CITY));
map.put(KEY_STATE, parser.getValue(e, KEY_STATE));
map.put(KEY_IMAGE_URL, parser.getValue(e, KEY_IMAGE_URL));
// adding HashList to ArrayList
orgsList.add(map);
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
adapter = new LazyAdapter(OrganizationActivity.this, orgsList);
list.setAdapter(adapter);
list.setSelectionFromTop(mPos, 0);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//Get the visible item position
mPos=list.getFirstVisiblePosition();
int lastInScreen = firstVisibleItem + visibleItemCount;
//Is the bottom item visible & not loading more already? Load more !
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
page_no++;
String pageURL = "myURL?page="
+ page_no;
new LoadData().execute(pageURL);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
}
Please help me out in finding the solution to this problem...
Looks like I was doing little bit of mistake in refreshing my ListView with the new data and also I was calling the notifyDataSetListener somewhere else. Now it is working absolutely fine..