I have used Ksoap2 to connect to this .NET web service and i get a xml response when i enter the users id. I only want to see two tags callTitle and callDescription. I don't need the rest and want to see in text not surround with xml code. can some one please help? I can't find tutorial online.
public class AndroidWebService extends Activity {
/** Called when the activity is first created. */
private static String SOAP_ACTION = "http://tempuri.org/GetHelpDeskCalls";
private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME = "GetHelpDeskCalls";
static final String URL = "https:/192.2344.123:8080/Service1.asmx";
Button getData;
EditText userID;
TextView data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.helpdesk);
getData = (Button) findViewById(R.id.button1);
userID = (EditText) findViewById(R.id.txtFar);
data = (TextView) findViewById(R.id.textView1);
Thread nT = new Thread() {
#Override
public void run() {
getData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SoapObject request = new SoapObject(NAMESPACE,
METHOD_NAME);
request.addProperty("userID", userID.getText()
.toString());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
try {
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);
final String results = androidHttpTransport.responseDump
.toString();
runOnUiThread(new Runnable() {
public void run() {
data.setText(results.toString());
}
});
} catch (Exception e) {
data.setText("Error" + e);
}
}
});
}
};
nT.start();
}
}
you should parse your XML with the help of xml pull parser
Following code will guide you for doing so
MyXmlPullParser objMyXmlPullParser = new MyXmlPullParser(context);
List<Map<String , String>> list = objMyXmlPullParser.readXml("Xml respose put here", "Table");
public class MyXmlPullParser
{
Context _context ;
public MyXmlPullParser(Context _context)
{
this._context = _context ;
}
public List<Map<String , String>> readXml(String XmlString , String ParentTag)
{
Map<String , String > map = new HashMap<String, String>();
List<Map<String , String >> list = new ArrayList<Map<String , String >>();
try
{
String Tag = "" ;
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader (XmlString));
int eventType = xpp.getEventType();
while (true)
{
if(eventType == XmlPullParser.START_TAG)
{
Tag = xpp.getName();
}
else if(eventType == XmlPullParser.END_TAG)
{
Tag = "" ;
if(xpp.getName().equals(ParentTag))
{
list.add(map);
map = new HashMap<String, String>();
}
}
else if(eventType == XmlPullParser.TEXT)
{
String text = xpp.getText();
if(!Tag.equals("") && !Tag.equals(ParentTag))
{
map.put(Tag, text);
}
}
else if(eventType == XmlPullParser.END_DOCUMENT)
{
System.out.println("End document");
break ;
}
eventType = xpp.next();
}
}
catch (XmlPullParserException e)
{
Log.e("xml reader" , "error in parsing xml");
return null ;
}
catch (IOException e)
{
Log.e("xml reader" , "error in IO in xml");
return null ;
}
return list ;
}
Hope it may helps you
Related
I want to get an Number from a String.
My Code for this Class is:
The XML is download correct, it founds my Value String but i get not the number from the String.
public class XMLProcessor extends AsyncTask<String, Void, String> {
private String rssURL;
private PostParserDelegate delegate;
private ArrayList<Post> posts;
String euro;
private StringBuilder buffer;
TextView mxntoeur;
TextView eurtomxn;
public XMLProcessor(String rssURL, PostParserDelegate delegate) {
this.rssURL = rssURL;
this.delegate = delegate;
posts = new ArrayList<Post>();
}
#Override
protected String doInBackground(String... strings) {
buffer = new StringBuilder();
try {
URL url = new URL(rssURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// HTTP Status "OK" -> HTTPCODE 200
int httpResponse = httpURLConnection.getResponseCode();
if ( httpResponse != 200) {
throw new Exception("Fehlercode: " + httpResponse);
}
InputStream input = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int charactersRead;
char[] tmpChars = new char[400];
while (true) {
charactersRead = reader.read(tmpChars);
if (charactersRead <= 0) {
break;
}
buffer.append(String.copyValueOf(tmpChars, 0, charactersRead));
}
return buffer.toString();
} catch (Exception e) {
Log.e("XMLProcessor", e.getMessage());
Log.e("XMLProcessor", e.getStackTrace().toString());
}
return String.valueOf(0);
}
#Override
protected void onPostExecute(String aDouble) {
super.onPostExecute(aDouble);
parse();
}
protected void parse()
{
String rawXML = buffer.toString();
Post aPost = null;
boolean isProcessingItem = false;
String innerValue ="";
try {
XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
parser.setInput(new StringReader(rawXML));
int event = parser.getEventType();
while (event !=XmlPullParser.END_DOCUMENT)
{
String tag = parser.getName();
switch ( event) {
case XmlPullParser.START_TAG:
if (tag == "item" ) {
Log.d("XMLProcessor", "Neuer Post!");
isProcessingItem = true;
aPost = new Post();
}
break;
case XmlPullParser.TEXT:
innerValue = parser.getText();
break;
case XmlPullParser.END_TAG:
if (isProcessingItem){
if (tag == "item") {
posts.add(aPost);
isProcessingItem = false;
}
} else if ( tag == "description") {
aPost.setPesoInEuro(innerValue);
euro = new String(innerValue.substring(13,21));
//euro = innerValue.substring(13,21);
eurtomxn.setText(euro);
}
break;
}
event = parser.next();
}
delegate.xmlFeedParsed(posts);
} catch (Exception e) {
Log.e("XMLProcess", e.getStackTrace().toString());
}
}
}
In innerValue i get the Correct Sting what i need
/n 1.00 EUR = 21.90612 MXN<br/>\n 1.00 MXN = 0.04565 EUR<br/>\n
Converter--\n
<a href="http://eur.de.fxexchangerate.com/mxn-exchange-rates-history.html">Historische
</a>
\n.
But my problem is, that i need this Number 21.90612. I have try it with substring(13,21), but it was no working.
Have you a idea, how i can fix my problem?
Thank you
It's not very clear what exactly is the Problem, it would be useful if you show the Exception!
Have you checked if the String innerValue has a valid lenght?
if(innerValue.lenght() >= 21){euro = innerValue.substring(13,21);} else {/* Do something here!*/}
}
Ksoap2 trying to connect to the web service. However, the "read timed out" error getting. I do not know what to do.
Ksoap2 'There is an error too? where is the error
Ksoaps libs version: 3.0.1
Emulator 2.2
MainActivity.java
public class MainActivity extends Activity {
static final String METHOD_NAME = "GetTableUpdateVersionByTableName";
static final String NAMESPACE = "http://tempuri.org/";
static final String URL = "https://app.xxx.com/IntSecureFlight/SFInternal.svc";
static final String DOMAIN = "app.xxx.com";
static final String SOAP_ACTION = "http://tempuri.org/IOperationSvc/GetTableUpdateVersionByTableName";
TextView sonuc;
EditText tableName;
String message;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sonuc = (TextView) findViewById(R.id.textView1);
tableName = (EditText) findViewById(R.id.editText1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), tableName.getText(),
Toast.LENGTH_LONG).show();
new AsyncTaskClass().execute();
}
});
}
class AsyncTaskClass extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
// uzun islem oncesi yapilacaklar
}
#Override
protected String doInBackground(String... strings) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("tableName", tableName.getText().toString());
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER12);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(request);
soapEnvelope.headerOut = new Element[1];
soapEnvelope.headerOut[0] = buildAuthHeader();
try {
HttpsTransportSE transportSE = new HttpsTransportSE(DOMAIN,
443, "/IntSecureFlight/SFInternal.svc", 2000);
transportSE.call(SOAP_ACTION, soapEnvelope);
Object result = soapEnvelope.getResponse();
if (result instanceof SoapFault12) {
SoapFault12 soapResult = (SoapFault12) result;
message = soapResult.getLocalizedMessage();
} else if (result instanceof SoapObject) {
SoapObject soapResult = (SoapObject) result;
message = soapResult.getProperty(0).toString();
}
} catch (SoapFault12 e) {
message = e.getMessage();
} catch (XmlPullParserException e) {
message = e.getMessage();
} catch (Exception e) {
message = e.getMessage();
}
return message;
}
#Override
protected void onPostExecute(String result) {
sonuc.setText(message);
super.onPostExecute(result);
}
}
public Element buildAuthHeader() {
Element h = new Element().createElement(NAMESPACE, "UsernameToken");
Element username = new Element().createElement(NAMESPACE, "Username");
username.addChild(Node.TEXT, "genel");
h.addChild(Node.ELEMENT, username);
Element pass = new Element().createElement(NAMESPACE, "KurumKod");
pass.addChild(Node.TEXT, "050");
h.addChild(Node.ELEMENT, pass);
return h;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
HttpTransportSEImpl
public class HttpTransportSEImpl extends HttpTransportSE {
public HttpTransportSEImpl(String url) {
super(url);
}
#Override
public ServiceConnection getServiceConnection() throws IOException {
ServiceConnection connection = super.getServiceConnection();
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
return connection;
}
}
AndroidManifest add <uses-permission android:name="android.permission.INTERNET"/>
read timed out error and socket time out errors will come on low internet connections
check your internet connection strength
or check the server response string, you may mismatch the data-type on reading.
and add permissions to listen network_state and
access_fine_location
edit your code:
HttpsTransportSE transportSE = new HttpsTransportSE(DOMAIN,
443, "/IntSecureFlight/SFInternal.svc", 60000);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i need to call a web service from the url. wen i entered the no in the text box i should the output which i entered in text box. pls help me fixing the errors. here is my java code.
MainActivity.java
public class MainActivity extends Activity {
Button b;
TextView tv;
EditText et;
String editText;
String displayText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.tv_result);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (et.getText().length() != 0 && et.getText().toString() != "") {
editText = et.getText().toString();
AsyncCallWS task = new AsyncCallWS();
task.execute();
} else {
tv.setText("Please enter number");
}
}
});
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
displayText = ser.invokeiop(editText,"hello");
return null;
}
}
}
ser.java
public class ser {
private static String NAMESPACE = "http://tempuri.org/";
private static String URL = "http://my url";
private static String SOAP_ACTION = "srvice";
public static String invokeiop(String name, String webMethName) {
String resTxt = null;
SoapObject request = new SoapObject(NAMESPACE, webMethName);
PropertyInfo iop = new PropertyInfo();
iop.setName("name");
iop.setValue(name);
//iop.setType(String.class);
request.addProperty(iop);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION+webMethName, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
resTxt = response.toString();
} catch (Exception e) {
e.printStackTrace();
resTxt = "Error occured";
}
This might help you!!
public class MainActivity extends Activity {
Button b;
EditText et;
String editText;
String displayText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (et.getText().length() != 0 && et.getText().toString() != "") {
editText = et.getText().toString();
AsyncCallWS();
} else {
// declare a toast
}
}
});
}
public void AsyncCallWS(final String q)
{
class HttpGetAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
String txtSearch = params[0];
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("URL"+editText);
try
{
HttpResponse httpResponse = httpClient.execute(httpGet);
inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder strB = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null)
{
strB.append(bufferedStrChunk);
}
return strB.toString();
}
catch (ClientProtocolException cpe)
{
cpe.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try {
// Parse your data here
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
}
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
httpGetAsyncTask.execute(editText);
}
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"/>
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;
}