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
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;
}
}
"http://54.251.60.177/StudentWebService/StudentDetail.asmx"
The above link is the web service, which contains two methods namely
GetStudentDetails
GetStudentsDetailsXML
The input values for this method is "carrier" for both methods
I am trying to consume this web service from android by the method SOAP.Actually the second method service is returning the values in the form of XML,here i am trying to consume this method and trying to show that returned values into List-view.But after getting run of my emulator,its simply just showing a black screen.
How to achieve my requirements? Can any one make me clear.
Please find my sources for reference
web method.java
package org.test.web.services;
public class GetStudentsDetailsXML
{
public String GetStudentsDetailsXML(String fieldName)
{
return fieldName;
}
}
AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity
{
private String METHOD_NAME = "GetStudentsDetailsXML";
private String NAMESPACE = "http://tempuri.org/";
private String SOAP_ACTION ="http://tempuri.org/GetStudentsDetailsXML";
private static final String URL = "http://54.251.60.177/StudentWebService/StudentDetail.asmx?WSDL";
EditText edt1,edt2;
Button btn;
TextView tv;
static final String URL_XML = "http://54.251.60.177/StudentWebService/StudentDetail.asmx/GetStudentsDetailsXML";
//XML node keys
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_FIELDTYPE = "FieldType";
static final String KEY_FIELDFORMAT = "FieldFormat";
static final String KEY_SAMPLE = "Sample";
static final String KEY_SEARCH = "SearchTags";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.button_get_result);
edt1 = (EditText)findViewById(R.id.editText1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Use this to add parameters
request.addProperty("fieldName",edt1.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try
{
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
System.out.println("Result : "+ result.toString());
}
catch (Exception E)
{
E.printStackTrace();
}
}
});
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL_XML); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// 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_FIELDTYPE, parser.getValue(e, KEY_FIELDTYPE));
map.put(KEY_FIELDFORMAT, parser.getValue(e, KEY_FIELDFORMAT));
map.put(KEY_SAMPLE, parser.getValue(e, KEY_SAMPLE));
map.put(KEY_SEARCH, parser.getValue(e, KEY_SEARCH));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.list_item,new String[] { KEY_FIELDFORMAT, KEY_SEARCH, KEY_SAMPLE }, new int[]
{R.id.FieldFORMAT_textView, R.id.Search_TEXTVIEW, R.id.Sample_TEXTVIEW });
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 FieldFormat = ((TextView) view.findViewById(R.id.FieldFORMAT_textView)).getText().toString();
String Sample = ((TextView) view.findViewById(R.id.Sample_TEXTVIEW)).getText().toString();
String Search = ((TextView) view.findViewById(R.id.Search_TEXTVIEW)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_FIELDFORMAT, FieldFormat);
in.putExtra(KEY_SAMPLE, Sample);
in.putExtra(KEY_SEARCH, Search);
startActivity(in);
}
}); } }
SingleMenuItemActivity.java
public class SingleMenuItemActivity extends Activity
{
// XML node keys
static final String KEY_FIELDFORMAT = "FieldFormat";
static final String KEY_SAMPLE = "Sample";
static final String KEY_SEARCH = "SearchTags";
#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 Fieldformat = in.getStringExtra(KEY_FIELDFORMAT);
String Sample = in.getStringExtra(KEY_SAMPLE);
String Search = in.getStringExtra(KEY_SEARCH);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.fieldformat_label);
TextView lblCost = (TextView) findViewById(R.id.Sample_label);
TextView lblDesc = (TextView) findViewById(R.id.Search_label);
lblName.setText(Fieldformat);
lblCost.setText(Sample);
lblDesc.setText(Search);
}}
XMLParser.java
public class XMLParser
{
// constructor
public XMLParser()
{
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String urlxml) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlxml);
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));
}
}
Thanks in advance!..
After the line:
// selecting single ListView item
ListView lv = getListView();
if the adapter related to lv is adapter (a few lines above), I would put this way,though it works with ArrayAdapter and not ListAdapter:
lv.setAdapter(adapter);
then, you have to add elements to the adapter with adapter.add(what you add, which is a string if I'm not wrong according to the documentation),and when all is added add:
adapter.notifyDataSetChanged();
The last one is to make the elements to be shown on the screen
Ok, about this specific situation, I have large XML file that should be parsed and shown in Android, and the part of it is here:
.
.
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/:
.
.
<item>
<title>RTS1</title>
<pubDate>Tue, 14, Aug 2012</pubDate>
<content:encoded><![CDATA[6:00 Vesti<br>06:05 Jutarnji program<br>08:15 Jutarnji dnevnik
<br>09:00 Kamiondzije .................. 23:15 Film<br>]]>
</content:encoded>
<item>
In my main, app I have done this:
public class Main extends ListActivity {
// All static variables
static final String URL = "http://tvprofil.net/rss/feed/channel-group-2.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_NAME = "title";
static final String KEY_DATE = "pubDate";
static final String KEY_DESC = "content:encoded";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String,String>> menuItems = new ArrayList<HashMap<String,String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); //get XML
Document doc = parser.getDomElement(xml); // get DOM elem.
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
//loop
for (int i=0; i< nl.getLength(); i++){
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
//add to map
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// hash => list
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item,
new String[]{KEY_NAME, KEY_DESC, KEY_DATE}, new int[]{
R.id.name, R.id.description, R.id.date
});
setListAdapter(adapter);
//singleView
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String name = ((TextView)view.findViewById(R.id.name)).getText().toString();
String date = ((TextView)view.findViewById(R.id.date)).getText().toString();
String description = ((TextView)view.findViewById(R.id.description)).getText().toString();
//intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_DATE, date);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
please, look closely at:
static final String KEY_DESC = "content:encoded";
I've tried with:
static final String KEY_DESC = "encoded";
and even with:
static final String KEY_DESC = "http://purl.org/rss/1.0/modules/content/encoded";
but nothing works.. doesn't show anything nor in Log.w when I set it nor on phone...
I'll even post parser class, I don't want any confusion:
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);
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 am using soap webservice and I have got the proper response, now i want to parse the response I have written code for that but I am not getting output, 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);
} 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 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));
}
}
My response is as follows
04-25 11:53:32.806: D/status(2924): GetLearningPortalsListResponse{GetLearningPortalsListResult=anyType{schema=anyType{element=anyType{complexType=anyType{choice=anyType{element=anyType{complexType=anyType{sequence=anyType{element=anyType{}; element=anyType{}; element=anyType{}; element=anyType{}; element=anyType{}; element=anyType{}; }; }; }; element=anyType{complexType=anyType{sequence=anyType{element=anyType{}; }; }; }; }; }; }; };
diffgram=anyType
{
NewDataSet=anyType
{
Table=anyType
{
ROWID=1; SiteID=7; PortalName=Pinneast; mSiteURL=http://pinneast.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/7/MyportalLogo.gif; Description=Pinneast is focused on improving business performance through human capital development and experienced in helping organizations of all sizes and across all industries;
};
Table=anyType
{
ROWID=2; SiteID=10; PortalName=Coach Institute; mSiteURL=http://coachinstitute.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/10/MyportalLogo.gif; Description=The Coaching Institute, where you are learning from someone who “does” and not just someone who “teaches”. We can train you to be a successful coach.;
};
Table=anyType
{
ROWID=3; SiteID=12; PortalName=Ready Courses; mSiteURL=http://readycourses.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/12/MyportalLogo.gif; Description=When you work with us, you get a professional team of e-learning and corporate training professionals who are passionate about getting the best technology implemented without high costs.;
};
Table=anyType
{
ROWID=4; SiteID=13; PortalName=A Step to Gold; mSiteURL=http://asteptogold.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/13/MyportalLogo.gif;
Description=The Ballroom is solely owned and operated by Melanie Dale. It has a 2400 square foot floating floor, and two other teaching studios.;
};
Table=anyType
{ROWID=5; SiteID=14; PortalName=In Sync Training; mSiteURL=http://insynctraining.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/14/MyportalLogo.gif;
Description=InSync Training offers a variety of consulting, development and delivery services to support synchronous training initiatives.;
};
Table=anyType
{ROWID=6; SiteID=15; PortalName=Total Motion Release; mSiteURL=http://totalmotionrelease.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/15/MyportalLogo.gif;
Description=Two stories emphasize how Tom Dalonzo-Baker discovered Total Motion Release.; };
Table=anyType
{ROWID=7; SiteID=16; PortalName=Polaris Consultants; mSiteURL=http://polaris.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/16/MyportalLogo.gif;
Description=Founded in 1997, and located adjacent to the Research Triangle Park in North Carolina, Polaris Clinical Research Consultants, Inc.; };
Table=anyType
{ROWID=8; SiteID=17;
PortalName=Develop Mentor Training; mSiteURL=http://developmentor.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/17/MyportalLogo.gif; Description=DevelopMentor provides in-depth, hands-on training for experienced developers.; };
Table=anyType
{ROWID=9; SiteID=18; PortalName=Cranky Middle Manager; mSiteURL=http://cmm.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/18/MyportalLogo.gif;
Description=If you've ever felt like you're trapped between the idiots who make the decisions and the morons who won't do as their told.; };
Table=anyType
{ROWID=10; SiteID=19;
PortalName=ITPreneurs; mSiteURL=http://itpreneurs.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/19/MyportalLogo.gif;
Description=ITpreneurs is the leading training solutions company in the IT management and IT governance best practices domain.;
};
Table1=anyType{TotalRecordsCount=387; };
};
};
};
}
do you have count tag in your xml.have you checked?
because in numResults function.it returns result according to count tag in xml.
This code parses XML data from web service. It Works.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_servis_uygulamasi);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String pSoapAction = "http://tempuri.org/GetMagazaList";
String pMethodName = "GetMagazaList";
String pNameSpace = "http://tempuri.org/";
String pUrl ="";
SoapObject result =(SoapObject)getWebServisDATA(pUrl, pMethodName, pNameSpace, pSoapAction, "333");
TextView tv =(TextView)findViewById(R.id.textView2);
try
{
SoapObject soapObjectGetProperty=(SoapObject)result.getProperty(0);
SoapObject resDiff = (SoapObject)soapObjectGetProperty.getProperty("diffgram");
SoapObject resDocEl = (SoapObject)resDiff.getProperty("DocumentElement");
StringBuilder stringBuilder = new StringBuilder();
for(int j=0;j<resDocEl.getPropertyCount();j++)
{
SoapObject resTable= (SoapObject)resDocEl.getProperty(j);
String MagazaObjId =resTable.getProperty("MagazaObjId").toString();
String MagazaAdi = resTable.getProperty("MagazaAdi").toString();
String MagazaKodu = resTable.getProperty("MagazaKodu").toString();
String MagazaPosDepoNo =resTable.getProperty("MagazaPosDepoNo").toString();
String PosId = resTable.getProperty("PosId").toString();
String IsYeriObjId = resTable.getProperty("IsYeriObjId").toString();
stringBuilder.append
(
"MagazaObjId :" +MagazaObjId+"\n"+
"MagazaAdi :" +MagazaAdi+"\n"+
"MagazaKodu :" +MagazaKodu+"\n"+
"MagazaPosDepoNo :"+MagazaPosDepoNo+"\n"+
"PosId :" +PosId+"\n"+
"Type :" +IsYeriObjId+"\n"+
"******************************"
);
stringBuilder.append("\n");
}
tv.setText(stringBuilder);
}
catch(Exception e)
{
tv.setText(e.getMessage());
}
}
});
}
public static SoapObject getWebServisDATA(String pUrl, String pMethodName,String pNameSpace, String pSoapAction,String pname)
{
SoapObject result = null;
SoapObject request = new SoapObject(pNameSpace, pMethodName);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
request.addProperty("firma",pname);
envelope.setOutputSoapObject(request);
AndroidHttpTransport httpTransport = new AndroidHttpTransport(pUrl);
try {
httpTransport.call(pSoapAction, envelope);
result = (SoapObject)envelope.bodyIn;
}
catch (Exception e)
{
}
return result;
}
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