android.os.NetworkOnMainThreadException Manifest - android

In the below code I got an error when running my android project for RssReader.
My main file:
public class Earthquake extends Activity {
ListView earthquakeListView;
ArrayAdapter < Quake > aa;
ArrayList < Quake > earthquakes = new ArrayList < Quake > ()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
earthquakeListView = (ListView) this.findViewById(R.id.earthquakeListView);
int layoutID = android.R.layout.simple_list_item_1;
aa = new ArrayAdapter < Quake > (this, layoutID, earthquakes);
earthquakeListView.setAdapter(aa);
refreshEarthquakes();
}
private void refreshEarthquakes() {
//get the XML
URL url;
try {
String quakeFeed = getString(R.string.quake_feed);
url = new URL(quakeFeed);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
//Parse the earthquake feed
Document dom = db.parse( in );
Element docEle = dom.getDocumentElement();
//Clear the old earthquakes
earthquakes.clear();
//Get a list of each earthquake entry
NodeList nl = docEle.getElementsByTagName("entry");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Element entry = (Element) nl.item(i);
Element title = (Element) entry.getElementsByTagName("title").item(0);
Element g = (Element) entry.getElementsByTagName("georss:point").item(0);
Element when = (Element) entry.getElementsByTagName("updated").item(0);
Element link = (Element) entry.getElementsByTagName("link").item(0);
String details = title.getFirstChild().getNodeValue();
String hostname = "http://earthquake.usgs.gov";
String linkString = hostname + link.getAttribute("href");
String point = g.getFirstChild().getNodeValue();
String dt = when.getFirstChild().getNodeValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
Date qdate = new GregorianCalendar(0, 0, 0).getTime();
try {
qdate = sdf.parse(dt);
} catch (ParseException e) {
e.printStackTrace();
}
String[] location = point.split(" ");
Location l = new Location("dummyGPS");
l.setLatitude(Double.parseDouble(location[0]));
l.setLongitude(Double.parseDouble(location[1]));
String magnitudeString = details.split(" ")[1];
int end = magnitudeString.length() - 1;
double magnitude = Double.parseDouble(magnitudeString.substring(0, end));
details = details.split(",")[1].trim();
Quake quake = new Quake(qdate, details, l, magnitude, linkString);
//Process a newly found earthquake
addNewQuake(quake);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} finally {}
}
private void addNewQuake(Quake _quake) {
//Add the new quake to our list of earthquakes
earthquakes.add(_quake);
//Notify the array adapter of a change
aa.notifyDataSetChanged();
}
}
Second file:
public class Quake {
private Date date;
private String details;
private Location location;
private double magnitude;
private String link;
public Date getDate() {
return date;
}
public String getDetails() {
return details;
}
public Location getLocation() {
return location;
}
public double getMagnitude() {
return magnitude;
}
public String getLink() {
return link;
}
public Quake(Date _d, String _det, Location _loc, double _mag, String _link) {
date = _d;
details = _det;
location = _loc;
magnitude = _mag;
link = _link;
}
#Override
public String toString() {
SimpleDateFormat sdf = new SimpleDateFormat("HH.mm");
String dateString = sdf.format(date);
return dateString + ": " + magnitude + " " + details;
}
}
I have read many articles with this and I have tried to add AsyncTask but it doesn't work. Also I have tried to add this:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
But this error comes up:
android.os.NetworkOnMainThreadException
How can I fix this issue?

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask.
see : http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html

Related

Normal class to AsyncTask

I have made a normal class and an AsyncTask and I want to make this code:
private void addNewQuake (Quake _quake) {
//Add the new quake to our list of earthquakes
earthquakes.add(_quake);
//Notify the array adapter of a change
aa.notifyDataSetChanged();
}
So I can add it to AsyncTask?
Or do I need to do in a other way?
#Override
protected void onCreate(Bundle savedInstanceState) {
// your other code
new DataLoadAsync().execute(); //start to get data
}
public class DataLoadAsync extends AsyncTask{
private Quake quake;
#Override
protected void doInBackground(){
// handle network data in here and put the result to quake in here.
refreshEarthquakes();
}
#Override
protected void onPostExecute(){
// use the result
addNewQuake(quake);
}
}
syntax is not complete, I just wanted to show you, you need to put your network data load method in doInBackground to get data, then you can use it in onPostExecute()
Here is my new code:
public class Earthquake extends Activity {
ListView earthquakeListView;
ArrayAdapter<Quake> aa;
ArrayList<Quake> earthquakes = new ArrayList<Quake>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
earthquakeListView = (ListView) this
.findViewById(R.id.earthquakeListView);
int layoutID = android.R.layout.simple_list_item_1;
aa = new ArrayAdapter<Quake>(this, layoutID, earthquakes);
earthquakeListView.setAdapter(aa);
new DataLoadAsync().execute();
}
public class DataLoadAsync extends AsyncTask<Object, Object, Object>{
private Quake quake;
protected void doInBackground(){
// handle network data in here and put the result to quake in here.
refreshEarthquakes();
}
protected void onPostExecute(){
// use the result
addNewQuake(quake);
}
#Override
protected Object doInBackground(Object... arg0) {
// TODO Auto-generated method stub
return null;
}
}
void refreshEarthquakes() {
//get the XML
URL url;
try {
String quakeFeed = getString(R.string.quake_feed);
url = new URL(quakeFeed);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
//Parse the earthquake feed
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
//Clear the old earthquakes
earthquakes.clear();
//Get a list of each earthquake entry
NodeList nl = docEle.getElementsByTagName("entry");
if (nl != null && nl.getLength() > 0) {
for (int i = 0 ; i < nl.getLength(); i++) {
Element entry = (Element)nl.item(i);
Element title = (Element)entry.getElementsByTagName("title").item(0);
Element g = (Element)entry.getElementsByTagName("georss:point").item(0);
Element when = (Element)entry.getElementsByTagName("updated").item(0);
Element link = (Element)entry.getElementsByTagName("link").item(0);
String details = title.getFirstChild().getNodeValue();
String hostname = "http://earthquake.usgs.gov";
String linkString = hostname + link.getAttribute("href");
String point = g.getFirstChild().getNodeValue();
String dt = when.getFirstChild().getNodeValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
Date qdate = new GregorianCalendar(0,0,0).getTime();
try {
qdate = sdf.parse(dt);
} catch (ParseException e) {
e.printStackTrace();
}
String[] location = point.split(" ");
Location l = new Location("dummyGPS");
l.setLatitude(Double.parseDouble(location[0]));
l.setLongitude(Double.parseDouble(location[1]));
String magnitudeString = details.split(" ")[1];
int end = magnitudeString.length()-1;
double magnitude = Double.parseDouble(magnitudeString.substring(0, end));
details = details.split(",")[1].trim();
Quake quake = new Quake(qdate, details, l, magnitude, linkString);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
finally {
}
}
private void addNewQuake (Quake _quake) {
//Add the new quake to our list of earthquakes
earthquakes.add(_quake);
//Notify the array adapter of a change
aa.notifyDataSetChanged();
}
}

The application has stopped unexpectedly, specific case on android

Ok, I am working on one android application. It has many features, such as showing the News, Horoscope, TV schedule, Weather forecast ... Every piece of information is comming to me through RSS, using XML. Application works as it is supposed to do when I have wifi or 3G, but as soon as there is no wifi or 3G signal, or some of the links are down under maintenance I get kicked out of application and error like:
The application has stopped unexpectedly! Please Try Again.
I was trying to make some Activity that will show something like:
There was a problem with your request! Please make sure that wifi or 3G signals are available or try again later.
I've tried many ways but nothing seams to work. Here are a few classes that might help:
1.
public class Pocetna extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pocetna);
.
.
.
vijesti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent xw = new Intent(getApplicationContext(), Vijesti.class );
xw.putExtra("A", "http://klix.ba/rss/naslovnica");
startActivity(xw);
}
});
2.
public class Vijesti extends ListActivity {
static String url =null;
// 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_DESC = "encoded";
static final String UVOD = "uvod";
static final String CLANAK = "clanak";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.vijesti_m);
Intent in = getIntent();
// Get XML values from previous intent
url = in.getStringExtra("A");
final ArrayList<HashMap<String,String>> menuItems = new ArrayList<HashMap<String,String>>();
ArrayList<String> xqw = new ArrayList<String>();
ParserVijesti parser=null;
Document doc=null;
try {
parser = new ParserVijesti();
String xml = parser.getXmlFromUrl(url); //get XML
doc = parser.getDomElement(xml);
} catch (Exception e1) {
finish();
}
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
//loop
for (int i=0; i< nl.getLength(); i++){
HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, String> mapq = new HashMap<String, String>();
Element e = (Element) nl.item(i);
//add to map
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
map.put(UVOD, parser.getValue(e,UVOD));
map.put(CLANAK, parser.getValue(e,CLANAK));
menuItems.add(map);
xqw.add(parser.getValue(e,KEY_TITLE));
}
for(int gf=0; gf<xqw.size(); gf++){
Log.w("ISPISI: ", xqw.get(gf));
}
ArrayAdapter adapterx = new ArrayAdapter(this, R.layout.vijesti_m,R.id.tetkica, xqw);
setListAdapter(adapterx);
//singleView
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
int hg = position;
HashMap<String, String> kaktus = menuItems.get(hg);
String uvod1 = kaktus.get(UVOD);
String clanak1 = kaktus.get(CLANAK);
String dat1 = kaktus.get(KEY_DATE);
String tit1 = kaktus.get(KEY_TITLE);
//intent
Intent inx = new Intent(getApplicationContext(), VijestiSingle.class);
inx.putExtra(KEY_TITLE, tit1);
inx.putExtra(KEY_DATE, dat1);
inx.putExtra(UVOD, uvod1);
inx.putExtra(CLANAK, clanak1);
startActivity(inx);
}
});
}
}
3.
public class ParserVijesti {
// constructor
public ParserVijesti() {
}
/**
* 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, "UTF-8");
} 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);
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setByteStream(new ByteArrayInputStream(xml.getBytes("UTF-8")));
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 "";
}
public final String getElementValue2( 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 "SRANJE";
}
/**
* 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));
}
public String getValue3(Element item, String str){
NodeList n = item.getElementsByTagNameNS("http://purl.org/rss/1.0/modules/content/", str);
String ses = this.getElementValue2(n.item(0));
//String mim =ses.replaceAll("(?s)\\<.*?\\>", " \n");
String html = ses;
Spanned strxa = Html.fromHtml(html);
String fffx=strxa.toString();
//return this.getElementValue2(n.item(0));
//return ses;
//return Promjena(ses);
return fffx;
}
}
So basically, what I want to do is not to check whether there is or not wifi or 3G. I just want to implement that Activity that will show that there is an error and not allow instantly kicking out of application whenever error occures. Please, anyone?
To check if the device is connected to Wifi or 3G, you could create a method like this:
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
Then, if the Activity you are trying to launch is dependent on internet connection, you could do:
if(!isOnline) {
Toast.makeText(getApplicationContext(), "You are not connected to the internet", Toast.LENGTH_SHORT).show();
} else {
startActivity(*yourIntent);
}
You'll need these permissions in your manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

App Not working, Unfortunately, XML has stopped error

I have written this code to parse this xml:
http://hiscentral.cuahsi.org/webservices/hiscentral.asmx/GetSeriesCatalogForBox2
But when I run it... it say "APP Stopped Working" and I can't figure out the reason... Please help!
The code is:
xmlActivity.java
package com.example.xml;
public class XmlActivity extends ListActivity {
static final String URL = "http://hiscentral.cuahsi.org/webservices/hiscentral.asmx/GetSeriesCatalogForBox2";
// XML node keys
static final String KEY_SeriesRecord = "SeriesRecord"; // parent node
static final String KEY_latitude = "latitude";
static final String KEY_longitude = "longitude";
static final String KEY_location = "location";
/** Called when the activity is first created. */
#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_SeriesRecord);
// 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_SeriesRecord, parser.getValue(e, KEY_SeriesRecord));
map.put(KEY_latitude, parser.getValue(e, KEY_latitude));
map.put(KEY_longitude, parser.getValue(e, KEY_longitude));
map.put(KEY_location, parser.getValue(e, KEY_location));
// adding HashList to ArrayList
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_latitude, KEY_longitude,
KEY_location }, new int[] { R.id.name, R.id.desciption,
R.id.cost });
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 description = ((TextView) view
.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_latitude, name);
in.putExtra(KEY_longitude, cost);
in.putExtra(KEY_location, description);
startActivity(in);
}
});
}
}
SingleMenuItemActivity.java
package com.example.xml;
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_latitude = "latitude";
static final String KEY_longitude = "longitude";
static final String KEY_location = "location ";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String latitude = in.getStringExtra(KEY_latitude);
String longitude = in.getStringExtra(KEY_longitude);
String location = in.getStringExtra(KEY_location);
// 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);
lblName.setText(latitude);
lblCost.setText(longitude);
lblDesc.setText(location);
}
}
xmlParser.java
package com.example.xml;
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));
}
}
You cannot do slow operation like HttpRequest in the Activity Thread. You must put them in a separate thread (AsyncTask). This is mentionned by Google but i lost source i'm sorry.
You should try creating an AsyncTask here is how you should try :
public class GetSoigneurInfoTask extends AsyncTask<Document, Integer, Document> //Le même code s'applique pour presque tout sauf onPostExecute()
{
Document doc;
String xml;
String url;
public GetSoigneurInfoTask(String URL)
{
url = URL;
}
protected Document doInBackground(Document...params)
{
xml = XmlFunctions.getXML(url);
doc = XmlFunctions.XMLfromString(xml);
return doc;
}
protected void onPostExecute(Document result)
{
if(result != null)
{
NodeList nodeList = doc.getElementsByTagName("RootTag"); //Crée une liste avec les elements sous soigneur
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
NodeList nodelist = element.getElementsByTagName("childTag");
Element element1 = (Element) nodelist.item(0);
NodeList fstNm = element1.getChildNodes();
soignTemp = fstNm.item(0).getNodeValue();
}
}
}
}
So you call your methods in doInBackground() and you do everything you have to do with UI in onPostExecute()!
Hope this helps!

how to parse the xsd schema in android

I am using soap webService and using that I have received the response which is in xsd schema format. I dont know how to parse it, I have tried the code but its not working,Can someone help me.
My Main Class is
public class Mylearning extends ListActivity {
//ArrayList<cat> list = null;
private static final String SOAP_ACTION="http://yyy.mobi/GetLearningPortalsList";
private static final String METHOD_NAME ="GetLearningPortalsList";
private static final String NAMESPACE ="http://yyy.mobi/";
private static final String URL = "http://webservices.yyy.mobi/MobileLMSServices.asmx";
private Bundle bundleResult = new Bundle();
private JSONObject JSONObj;
private JSONArray JSONArr;
//private ArrayList<HashMap<String, Object>> myList;
SoapObject request;
TextView tv;
TextView tv1;
TextView tv2;
ListView mainListView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylearning);
//mainListView = (ListView) findViewById(R.id.main_listview);
request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("SiteURL","http://www.yyy.mobi/");
request.addProperty("PageID","1");
request.addProperty("SearchText","");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
SoapObject result = null;
envelope.setOutputSoapObject(request);
AndroidHttpTransport sab = new AndroidHttpTransport(URL);
sab.debug = true;
try {
sab.call(SOAP_ACTION, envelope);
if (envelope.getResponse() != null) {
result = (SoapObject) envelope.bodyIn;
String[] values = new String[result.getPropertyCount()];
int j = result.getPropertyCount();
String repons=result.toString();
// Log.d("result",repons.toString());
Document doc = XMLfunctions.XMLfromString(repons);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(Mylearning.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("Course", XMLfunctions.getValue(e, "Course"));
map.put("Description", "Description:" + XMLfunctions.getValue(e, "Description"));
map.put("icon", "icon: " + XMLfunctions.getValue(e, "icon"));
mylist.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.rowmylearning,
new String[] { "Course", "Description","icon" },
new int[] { R.id.txt1, R.id.txt2,R.id.img1 });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Mylearning.this, "Course '" + o.get("Course") + "' was clicked.", Toast.LENGTH_LONG).show();
}
});
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
My Xmlfunction class is
public class XMLfunctions {
public final static Document XMLfromString(String repons){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(repons));
// Log.d("message",repons.toString());
doc = db.parse(is);
Log.d("doc", doc.toString());
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;
try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}
return res;
}
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
}
Take a look at this discussion
You can use the ksoap2 a SOAP Client Library to parse Responses

Please help - how to parse this xml in android - always error

This is the xml file:
http://dating.rs/nemanja/WebService/getPlaces.php?lat=44.8061999&lon=20.4595333&rad=3502&tfs=0
<places>
<place>
<id>
6
</id>
<name>
McDonalds
</name>
<type>
Fast Food
</type>
<longitude>
20.4658031097
</longitude>
<latitude>
44.80228031097
</latitude>
</place>
<place>
<id>
5
</id>
<name>
Pizza hut
</name>
<type>
Fast Food
</type>
<longitude>
20.47832518815
</longitude>
<latitude>
44.792844714
</latitude>
</place>
</places>
This is my code:
public class ShopList {
private ArrayList<String> id = new ArrayList<String>();
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> type = new ArrayList<String>();
private ArrayList<String> latitude = new ArrayList<String>();
private ArrayList<String> longitude = new ArrayList<String>();
with get i set metods...
public class ReturnPlaces extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static ShopList shopList = null;
public static ShopList getShopList(){
return shopList;
}
public static void setShopList(ShopList shopList) {
ReturnPlaces.shopList = shopList;
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
//super.characters(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (localName.equalsIgnoreCase("id"))
shopList.setId(currentValue);
else if (localName.equalsIgnoreCase("name"))
shopList.setName(currentValue);
else if (localName.equalsIgnoreCase("type"))
shopList.setType(currentValue);
else if (localName.equalsIgnoreCase("latitude"))
shopList.setLatitude(currentValue);
else if (localName.equalsIgnoreCase("longitude"))
shopList.setLongitude(currentValue);
//super.endElement(uri, localName, qName);
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if(localName.equalsIgnoreCase("place")){
shopList = new ShopList();
}else if (localName.equalsIgnoreCase("id")) {
String id1 = attributes.getValue("id");
shopList.setId(id1);
}else if (localName.equalsIgnoreCase("name")) {
String name1 = attributes.getValue("name");
shopList.setName(name1);
}else if (localName.equalsIgnoreCase("type")) {
String type1 = attributes.getValue("type");
shopList.setType(type1);
}else if (localName.equalsIgnoreCase("latitude")) {
String latitude1 = attributes.getValue("latitude");
shopList.setLatitude(latitude1);
}else if (localName.equalsIgnoreCase("longitude")) {
String longitude1 = attributes.getValue("longitude");
shopList.setLatitude(longitude1);
}
//super.startElement(uri, localName, qName, attributes);
}
and this is my activity:
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.pretraga);
mapView = (MapView) findViewById(R.id.mapView1);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(17);
mapView.setStreetView(true);
listView = (ListView) findViewById(R.id.listView);
Intent i = getIntent();
final double niz [] = i.getDoubleArrayExtra("Trenutna lokacija");
double lat = niz [0];
double lng = niz [1];
int radius = i.getIntExtra("Radius", 501);
boolean vreme = i.getBooleanExtra("Radno vreme", false);
try{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceUrl = new URL("http://dating.rs/nemanja/WebService/getPlaces.php?lat=44.8061999&lon=20.4595333&rad=3502&tfs=0");
ReturnPlaces returnPlacesHandler = new ReturnPlaces();
xr.setContentHandler(returnPlacesHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
}catch (Exception e) {
System.out.println("XML parsing exception"+e);
}
shopList = ReturnPlaces.getShopList();
for(int u = 0; u<shopList.getId().size();u++){
map = new HashMap<String, String>();
float distance;
map.put("name", shopList.getName().get(u));
map.put("type", shopList.getType().get(u));
myList.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this.getApplicationContext(), myList,R.layout.listview1, new String[]{"name","type"},
new int[]{R.id.textViewName,R.id.textViewType});
listView.setAdapter(adapter);
I think this might help you.
//Main Class
public class Place extends ListActivity
{
HashMap<String, String> map;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.placelist);
ArrayList<HashMap<String, String>> accountlist = new ArrayList<HashMap<String, String>>();
String xml = XMLParser.getXML();
Log.i("Retrieved Xml", xml);
Document doc = XMLParser.parse(xml);
//Parsing data directly from the XML
NodeList nodes = doc.getElementsByTagName("place");
for (int i = 0; i < nodes.getLength(); i++)
{
map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("id", XMLParser.getValue(e, "id"));
map.put("name", XMLParser.getValue(e, "name"));
accountlist.add(map);
}
ListAdapter adapter = new PlaceAdapter(this, accountlist , R.layout.main,
new String[] { "id", "name" },
new int[] { R.id.id, R.id.name });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Intent intent = new Intent(Place.this, Results.class);
Bundle b = new Bundle();
b.putString("name", o.get("name"));
b.putString("id", o.get("id"));
intent.putExtras(b);
startActivity(intent);
}
});
}
//Place-Adapter
public class PlaceAdapter extends SimpleAdapter
{
private ArrayList<HashMap<String, String>> results;
public PlaceAdapter(Context context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to)
{
super(context, data, resource, from, to);
this.results = data;
}
public View getView(int position, View view, ViewGroup parent)
{
int[] colors = new int[] {0x30ffffff, 0x30ff2020, 0x30808080};
View v = super.getView(position, view, parent);
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.main, null);
}
TextView id = (TextView) v.findViewById(R.id.id);
id.setText(results.get(position).get("id"));
TextView name = (TextView) v.findViewById(R.id.name);
name.setText(results.get(position).get("Name"));
int colorPos = position % colors.length;
v.setBackgroundColor(colors[colorPos]);
return v;
}
} }
//Parsing
public class XMLParser {
public final static Document XMLfromString(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) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
/** Returns element value
* #param elem element (it is XML tag)
* #return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://dating.rs/nemanja/WebService/getPlaces.php?lat=44.8061999&lon=20.4595333&rad=3502&tfs=0");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;
try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}
return res;
}
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLParser.getElementValue(n.item(0));
}
}
//Displaying Reults on click of listview
public class Results extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
Bundle b = getIntent().getExtras();
String id = b.getString("id");
String name = b.getString("name");
EditText aid = (EditText) findViewById(R.id.eid);
EditText aname = (EditText) findViewById(R.id.ename);
aid.setText(id);
aname.setText(name);
}
}
You should not be making URL connections in onCreate. This is discouraged in earlier Android versions and is enforced by the framework as of Honeycomb. You need to use a worker thread or (equivalently, but easier) an AsyncTask. See the Painless Threading blog post in the Android docs.
Use Dom xml parsing , see this sample here
and download this sample too

Categories

Resources