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);
Related
I am creating an app with tabs with fragment and swipable views ...
I have xml parser fragment which works in asynctask in background ..
The problem is that when i open the other fragment and not the xml parser fragment it starts the asynctask and shows progressbar dialog that keeps the user waiting till the task complete! How do i make it like that it will start the async task when i go to that xmlparser fragment only ? Can anybody help?
My code:
public class CircularsFragment extends Fragment {
// All static variables
public static final String URL = "https://dl.dropboxusercontent.com/7978967896/something.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
ProgressDialog dialog;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
private static class GetStuffFromUrlTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String url = params[0];
String xml = "";
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;
}
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));
}
}
private static class ParseStuffIGotFromSomeWhereTask extends AsyncTask<String, Void, Document> {
#Override
protected Document doInBackground(String... params) {
String stringToParse = params[0];
Document document = new XMLParser().getDomElement(stringToParse);
return document;
}
}
private static class XMLParser {
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;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_games, container, false);
setRetainInstance(true);
//check internet
cd = new ConnectionDetector(getActivity().getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
//This is the task we use to parse the XML we got back from the getStuffFromUrlTask
//do only if internet is present
if (isInternetPresent) {
final ParseStuffIGotFromSomeWhereTask parseTask = new ParseStuffIGotFromSomeWhereTask() {
#Override
protected void onPreExecute(){
}
#Override
public void onPostExecute(Document document) {
// here you can access the document that is the result of our parse operation
// progressDialog.dismiss();
//document.getElementsByTagName(XYZ)...
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
NodeList nl = document.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);
GetStuffFromUrlTask parser1 = new GetStuffFromUrlTask();
// adding each child node to HashMap key => value
map.put(KEY_ID, parser1.getValue(e, KEY_ID));
map.put(KEY_NAME, parser1.getValue(e, KEY_NAME));
map.put(KEY_COST, "Rs." + parser1.getValue(e, KEY_COST));
map.put(KEY_DESC, parser1.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
final ListView lview = (ListView) rootView.findViewById(R.id.lview);
lview.setAdapter(adapter);
// selecting single ListView item
//ListView lv = getListView();
lview.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 description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getActivity().getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
};
//This is the task we use to get stuff from the URL
GetStuffFromUrlTask getStuffFromUrlTask = new GetStuffFromUrlTask() {
protected void onPreExecute(){
dialog=ProgressDialog.show(getActivity(), "", "Loading...Please wait!");
}
#Override
public void onPostExecute(String result) {
//The task has completed, the string result contains the XML data we got from the URL
parseTask.execute(result); //Now we start the task to parse the xml
dialog.dismiss();
}
};
getStuffFromUrlTask.execute(URL);
}
else{
Toast.makeText(
getActivity().getApplicationContext(),
"No INTERNET! Circulars can't be loaded.",
Toast.LENGTH_LONG).show();
}
return rootView;
}
}
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 an Rss feed that i'm parsing. I need it to sort and organize from top to bottom by pubdate. Here is the code that i'm using.
XML Parser
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();
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));
}
}
Parsing Activity
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://www.cpcofc.org/devoapp.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "item";
static final String KEY_NAME = "title";
static final String KEY_COST = "description";
static final String KEY_DESC = "description";
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
#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_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_DESC, KEY_NAME, KEY_COST}, new int[] {
R.id.desciption, 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) {
// 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();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
startActivity(in);
}
});
}
}
Here is what it looks like right now
I need to show the reverse of this with day 1 at the top. Anyone have any ideas on how to make this work?
You just need to reverse the order of the List in order to achieve what you want,
we can use Collections class provided by java collection framework ... here is the simple code
Collections.reverse(menuItems);
it will reverse your collection.... I hope this will help you
you shouldn't need to override sort the ArrayAdapter class implements that for you. All you need to do is create your own Comparator that will sort the generic type objects the way you want them to appear. Also, Your code should work correctly if you use this approach.
adapter = new CustomAdapter(this, R.layout.list,R.id.title, data);
adapter.sort(new Comparator<RowData>() {
public int compare(RowData arg0, RowData arg1) {
return arg0.mProductName.compareTo(arg1.mProductName);
}
});
setListAdapter(adapter);
adapter.notifyDataSetChanged();
For more reference..
http://www.vogella.com/articles/AndroidListView/article.html#listview_filtersort
https://github.com/bauerca/drag-sort-listview/tree/master/demo
both previous answers will cost you some performance because they loop through the ArrayList AT LEAST once.
you can simply use a reverse iterator for your loop like this:
int len = nl.getLength();
for (int i = len; i > 0; --i)
i also extracted the length of the array into a local variable cause it's way faster than calling the getLength method every time.
I have the following mistake:
12-05 20:35:31.005: E/AndroidRuntime(1084): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helplawyer/com.example.helplawyer.AndroidXMLParsingActivity}: android.os.NetworkOnMainThreadException
in xml manifest I added <uses-permission android:name="android.permission.INTERNET" />
this is my main class
package com.example.helplawyer;
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://www.consultant.ru/rss/hotdocs.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_DATE = "pubDate";
static final String KEY_LINK = "link";
static final String KEY_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainxml);
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_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// 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_DATE, KEY_LINK }, new int[] {
R.id.name, R.id.description, R.id.cost, R.id.link });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
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();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String link = ((TextView) view.findViewById(R.id.link)).getText().toString();
String description = ((TextView) view.findViewById(R.id.description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, name);
in.putExtra(KEY_DATE, cost);
in.putExtra(KEY_LINK, link);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
XMLParser
package com.example.helplawyer;
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();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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));
}
}
I read on stackoverflow that I need to use new Thread(new Runnable() {
but I don't understand how to rewrite my code that my app works good.
Please, help me with my problem!
Thank you
From the Android documentation.
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or
higher. Applications targeting earlier SDK versions are allowed to do
networking on their main event loop threads, but it's heavily
discouraged. See the document Designing for Responsiveness.
Also see StrictMode.
Look here for examples of running this operation in the background (Find "How to Avoid ANRs")
You cannot access network from your main thread.
you need to use AsyncTask . Check my answer at
Android Connecting with PHP and MySql Force Close
Note the AsyncTask<String, Void, String>, here first String is the parameter to doInBackground , Void is parameter to onProgressUpdate(), we are not implementing this method, second String is parameter to onPostExecute()
Now, from MainActivity when you call new InnerClass().execute(urltoxml); Android will automatically call doInBackground() and will pass urltoxml as the argument`
Do all your network stuff inside doInbackground, when finished, doInBackground will return a result string and android will pass that as the parameter to onPostExecute().
Use that string however you want from onPostExecute
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener( new OnClickListener(){
#Override
public void onClick(View v){
new InnerClass().execute(urltoxml);
}
});
}
public class InnerClass extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... arg0) {
String returnVal;
//process your xml here
//store the result in returnVal;
return returnVal;
}
#Override
protected void onPostExecute(String result) {
//do something with the data
}
}
}
You are running Network Request on main UI thread.
Android >=3.0 does not allow to run Network Request on main UI thread. You need to use
AsyncTask to do network operation.
Ok I have been working on this a few days now and have narrowed down my problem to the fact I don't think it is actually getting the node item from the xml file to load the URL. I'm using a DOM parser to parse the xml file and load into a listview. I am trying to load the URL from each item into a custom webview activity and if i hardcode a url in place of the stringed url it works perfectly, if i put the stringed url in there it doesn't load the URL value. Here are the code and classes i'm working with. Thank you for your help.
xml parser activity
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();
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));
}
}
listview adaptor class
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
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_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(CustomizedListView.KEY_TITLE));
artist.setText(song.get(CustomizedListView.KEY_PUB_DATE));
imageLoader.DisplayImage(song.get(CustomizedListView.KEY_LINK), thumb_image);
return vi;
}
}
main activity
public class CustomizedListView extends Activity {
// All static variables
static final String URL = "http://treymorgan.net/feed";
// 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_PUB_DATE = "pubDate";
static final String KEY_LINK = "link";
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_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);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ITEM));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_PUB_DATE, parser.getValue(e, KEY_PUB_DATE));
map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
// 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) {
Intent intent = new Intent(CustomizedListView.this, WebviewActivity.class);
Bundle b = new Bundle();
intent.putExtra( "b", "KEY_LINK");
startActivity(intent);
}
});
}
}
Webview Activity
public class WebviewActivity extends Activity{
private WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
Bundle b = getIntent().getExtras();
String KEY_LINK = b.getString("b");
webview = (WebView) findViewById(R.id.webView1);
webview.setWebViewClient(new MyWebViewClient(this));
webview.getSettings().setAppCacheEnabled(false);
webview.getSettings().setBuiltInZoomControls(true);
webview.setInitialScale(1);
webview.loadUrl(KEY_LINK);
}
}
Here is a sample item of the XML i am parsing
<item>
<title>We’re Building a Feeding Center and Church in Honduras!</title>
<link>http://treymorgan.net/were-building-a-feeding-center-and-church-in-honduras/</link>
<comments>http://treymorgan.net/were-building-a-feeding-center-and-church-in-honduras/#comments</comments>
<pubDate>Fri, 14 Sep 2012 15:47:15 +0000</pubDate>
<dc:creator>Trey Morgan</dc:creator>
<category><![CDATA[Honduras]]></category>
<guid isPermaLink="false">http://treymorgan.net/?p=4640</guid>
<description><![CDATA[Do you remember this post from two weeks ago about feeding kids in Buen Samaritano? Marc Tindall needed $6000 to get the feeding center started (which will be used as a church too) … and this past Monday morning we presented him with the money. WOO HOO! Thanks to all those who gave.]]></description>
<wfw:commentRss>http://treymorgan.net/were-building-a-feeding-center-and-church-in-honduras/feed/</wfw:commentRss>
<slash:comments>1</slash:comments>
<enclosure url="http://treymorgan.net/wp-content/uploads/2012/09/photo-101-224x300.jpg" length="2854" type="image/jpeg" />
</item>
Thank you for any help you can give on this
The KEY_LINK url passed to the webView might not be formatted properly.
Try encoding it properly using this first:
String urlStr = KEY_LINK;
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
webview.loadUrl(url);
Try like:
For the pass string from one activity to the other
First activity:
Intent indisplay = new Intent(FirstClass.this,SecondClass.class);
indisplay.putExtra("link",your link here);
startActivity(indisplay);
Second activity:
Intent indispaly = getIntent();
String url = indispaly.getStringExtra("link");
// your link from previous activity is stored into the url