Adding XML file to a SOAP request - android

(i'm trying to say hello, but the site keeps deleting it oO)... !
Here is my question : I found out how to send a request to a webservice using ksoap, but i still cannot figure out where to add my XML to the request !
Here is my code :
public static SoapObject soap () throws IOException, XmlPullParserException {
SoapObject request = new SoapObject (NAMESPACE, METHOD_NAME);
/* HERE IS THE PROBLEM */
request.addProperty(toto, HERE IS MY XML);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope (
SoapEnvelope.VER11);
envelope.setOutputSoapObject (request);
HttpTransportSE androidHttpTransport = new HttpTransportSE (URL);
androidHttpTransport.debug = true;
androidHttpTransport.call (SOAP_ACTION, envelope);
SoapObject soapResult = (SoapObject) envelope.getResponse ();
return soapResult;
}
If i delete the "request.addProperty line", it reaches the server, but it does nothing, because i need to send my XML. If someone know how to do that, it would definitely make my day !!
Thanks you for reading this !

Maybe it doesn't help you with this particular issue, but I would not recommended using ksoap. I wasted so much time getting it to work and after that I wrote my SOAP client with few hours and it works without problem.
It's easy:
public static HashMap<String, Object> callSOAPServer(StringBuffer soap /* YOUR XML GOES HERE*/,String action) {
HashMap<String, Object> xMap = new HashMap<String, Object>();
byte[] result = null;
byte[] data = new byte[1024*1024];
HttpClient httpclient = new DefaultHttpClient(); /* Your probably need to edit client for your needs, like timeout, scheme, etc */
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
DataInputStream is = null;
boolean download = true;
HttpPost httppost = new HttpPost(/* YOUR URL GOES HERE */ );
httppost.setHeader("soapaction", action);
httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
try {
HttpEntity entity = new StringEntity(soap.toString(),HTTP.UTF_8);
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
if (r_entity != null) {
result = new byte[(int) r_entity.getContentLength()];
size = result.length;
if (r_entity.isStreaming()) {
is = new DataInputStream(r_entity.getContent());
while((count = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, count);
total +=count;
}
}
buffer.flush();
result = buffer.toByteArray();
data = null;
buffer = null;
}
} catch (Exception e) {
e.printStackTrace();
result = null;
}
if(result !=null){
try {
String sb;
String sn;
sb = new String(result, "UTF-8");
sn = sb.replace("&", "AMP"); //Precaution for SAX parser
result = sn.getBytes();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
xMap.put(STATUS, "OK");
xMap.put(SOAP, result);
}else{
if(xMap.get(STATUS) == null) {
xMap.put(STATUS, "ERROR");
}
}
httpclient.getConnectionManager().shutdown();
return xMap;
}
Here is parser:
public ArrayList< HashMap<String,String>> parseSoap (byte[] soapResult,String soapFunctionName, String... args) {
ArrayList< HashMap<String,String>> xMap = new ArrayList< HashMap<String,String>>();
if(soapResult == null) xMap.put(STATUS, "Where is stuff to handle");
byte[] initReqrepsonse = soapResult;
ByteArrayInputStream bais = new ByteArrayInputStream(initReqrepsonse);
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
if(soapFunctionName.equals(NEWS)) { /*IF YOU USE MULTIPLE SOAP FUNCTION, YOU NEED TO DETERMINE WHICH IS WHICH...*/
NewsXMLHandler myXMLHandler = new NewsXMLHandler(); /*..BECAUSE HERE YOU NEED TO SPECIFY FIELDS WHICH YOU WANT TO RETRIEVE FROM XML*/
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(bais));
xMap.put(SOAP_OUTPUT, myXMLHandler.getOutput());
myXMLHandler = null;
}
sp = null;
xr = null;
} catch (Exception e) {
e.printStackTrace();
}
spf = null;
return xMap;
}
And for that thing (NewsXMLHandler) which determines which fields you want to parse:
public class NewsXMLHandler extends DefaultHandler {
public NewsXMLHandler() {}
private ArrayList< HashMap<String,String> > data;
private HashMap<String,String> dataHash;
private final StringBuilder mStringBuilder = new StringBuilder();
private boolean bStore = false;
ArrayList< HashMap<String,String>> getOutput() {
return data;
}
#Override
public void startDocument() throws SAXException
{
data = new ArrayList< HashMap<String,String> >();
}
#Override
public void endDocument() throws SAXException
{
}
#Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
mStringBuilder.setLength(0);
bStore = true;
try {
//HERE YOU NEED TO SPECIFY WHICH IS ROOT NODE OF XML FROM SOAP, IN MY EXPERIENCE ITS OUT
if(localName.equalsIgnoreCase("out")) {
dataHash = new HashMap<String,String>();
}
} catch (Exception e)
{
Log.d("error in startElement", e.getStackTrace().toString());
}
}
#Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException
{
bStore = false;
//HERE IT IS, JUST WRITE NAME OF NODE WHICH YOU WANT TO USE FOR YOUR APPLICATION
if (localName.equalsIgnoreCase("your node name"))
{
dataHash.put("your node name", mStringBuilder.toString().trim());
}
if (localName.equalsIgnoreCase("your node name 2"))
{
dataHash.put("your node name 2", mStringBuilder.toString().trim());
}
// CONTINUE WITH THOSE IFS UNTIL YOU HAVE ALL FIELDS WHICH YOU NEED COVERED
// HERE YOU WRAP ALL OF THOSE HIGHER NODE AND SAVE TO ARRAYLIST, SO IF THERE ARE MORE OF THEM, YOU GET THEM ALL - AGAIN ITS NAME OF ROOT NODE
if(localName.equalsIgnoreCase("out")) {
data.add(dataHash);
dataHash = null;
}
}
#Override
public void characters(char ch[], int start, int length)
{
if (bStore)
{
mStringBuilder.append(ch, start, length);
if(mStringBuilder.length() == 0) mStringBuilder.setLength(0);
}
}
}
And here goes the usage. As it seems you alredy figured out, you can't execute URL request on main thread. You just need to use AsyncTask, Service, IntentService, etc. I am not going to cover it here. I like to use IntentService and save entries to database.
So lets say, you wrap those two static function in class SOAPHandler:
HashMap<String, Object> SOAPResponse = SOAPHandler.callSOAPSERVER(/*YOUR XML REQUEST HERE*/, /*NAME OF SOAP METHOD ON SERVER*/)
ArrayList< HashMap<String,String>> parsedEntries = SOAPHandler.parseSoap(SOAPResponse, NEWS, NULL);
foreach(HashMap<String,String> hash : parsedEntries) {
String entryOne = hash.get("your node name");
String entryTwo = hash.get("your node name 2");
//HERE YOU HAVE YOUR STRINGS, DO WHATEVER WITH THEM
}

Here is Basic KSOAP Android tutorial, which should greatly assist with understanding how to use KSOAP to consume a web service.
What is important to note, is that you will not be able to send a raw xml packet using KSOAP but that the parameters need to be passed as PropertyInfo class instances.
HTH

Related

I can't retrieve data from server to android studio although data is shown in a browser

I have recently made an application in android studio 2.3 to show data from a server the link that I use is working properly in a browser and data is shown successfully in json format. But in my application I can't retrieve these data, I add avolley lib in my app gradle file like this :
compile 'com.mcxiaoke.volley:library:1.0.18'
The code I use in MainActivity is :
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
String url = "http://abdulwahid.esy.es/show.php";
TextView txtshow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtshow = (TextView) findViewById(R.id.txtshow);
rq = Volley.newRequestQueue(this);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jarr = response.getJSONArray("allstudents");
for (int i = 0; i < jarr.length(); i++) {
JSONObject res = jarr.getJSONObject(i);
String id = res.getString("id");
String name = res.getString("name");
String info = res.getString("info");
txtshow.append("\n" + id + " - " + name + "\n" + info + "\n" + "------------------" + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
});
rq.add(jor);
}
The link of php file that I use is executed successfully in a web browser.
How to show data in my application or is there another code or library to use for retrieving data form online ?
you can use StringRequest instead of jsonObject with the new library of volley
compile 'com.android.volley:volley:1.0.0'
Use this code to retrieve data, in string line your data will be appended as a complete string as shown in browser
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://abdulwahid.esy.es/show.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
The problem is that the Content-Type header is not set in the response of your server. For Volley to be able to parse it, you will need that header set to application/json.
Add the following line in your show.php:
header('Content-Type: application/json');
Edit
After the above change, the response seems strange...
I can see strange characters in the response, that might be causing parsing issues on the client side.

Code in FOR loop not executed

I have a ProgressDialog that retrieves in background data from database by executing php script.
I'm using gson Google library. php script is working well when executed from browser:
{"surveys":[{"id_survey":"1","question_survey":"Are you happy with the actual government?","answer_yes":"50","answer_no":"20"}],"success":1}
However, ProgressDialog background treatment is not working well:
#Override
protected Void doInBackground(Void... params) {
String url = "http://192.168.1.4/tn_surveys/get_all_surveys.php";
HttpGet getRequest = new HttpGet(url);
Log.d("GETREQUEST",getRequest.toString());
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
Log.d("URL1",url);
HttpResponse getResponse = httpClient.execute(getRequest);
Log.d("GETRESPONSE",getResponse.toString());
final int statusCode = getResponse.getStatusLine().getStatusCode();
Log.d("STATUSCODE",Integer.toString(statusCode));
Log.d("HTTPSTATUSOK",Integer.toString(HttpStatus.SC_OK));
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
Log.d("RESPONSEENTITY",getResponseEntity.toString());
InputStream httpResponseStream = getResponseEntity.getContent();
Log.d("HTTPRESPONSESTREAM",httpResponseStream.toString());
Reader inputStreamReader = new InputStreamReader(httpResponseStream);
Gson gson = new Gson();
this.response = gson.fromJson(inputStreamReader, Response.class);
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.d("HELLO","HELLO");
StringBuilder builder = new StringBuilder();
Log.d("STRINGBUILDER","STRINGBUILDER");
for (Survey survey : this.response.data) {
String x= survey.getQuestion_survey();
Log.d("QUESTION",x);
builder.append(String.format("<br>ID Survey: <b>%s</b><br> <br>Question: <b>%s</b><br> <br>Answer YES: <b>%s</b><br> <br>Answer NO: <b>%s</b><br><br><br>", survey.getId_survey(), survey.getQuestion_survey(),survey.getAnswer_yes(),survey.getAnswer_no()));
}
Log.d("OUT FOR","OUT");
capitalTextView.setText(Html.fromHtml(builder.toString()));
progressDialog.cancel();
}
HELLO Log is displayed.
STRINGBUILDER Log is displayed.
QUESTION Log is NOT displayed.
OUT FOR Log is displayed.
Survey Class:
public class Survey {
int id_survey;
String question_survey;
int answer_yes;
int answer_no;
public Survey() {
this.id_survey = 0;
this.question_survey = "";
this.answer_yes=0;
this.answer_no=0;
}
public int getId_survey() {
return id_survey;
}
public String getQuestion_survey() {
return question_survey;
}
public int getAnswer_yes() {
return answer_yes;
}
public int getAnswer_no() {
return answer_no;
}
}
Response Class:
public class Response {
ArrayList<Survey> data;
public Response() {
data = new ArrayList<Survey>();
}
}
Any help please concerning WHY the FOR loop is not executed.
Thank you for helping.
Any help please concerning WHY the FOR loop is not executed.
Simply put: data is empty. (So there is nothing for the loop to iterate over...)
Try something like this, from GSON's documentation:
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
I haven't used GSON myself, but there are other examples of how to read lists:
Android gson deserialization into list
GSON : custom object deserialization
Your onPostExecute takes in a parameter called result. Your for loop iterates over the elements in an instance variable called response. Are they supposed to be the same?

in AsyncTask i want the data in list view

hi friends i just want the data show in a list view i using async task and i complete get the data in json and filtering it by id and title now i show id and title in a listview can you help me thanks in advance
public class runActivity extends Activity implements OnClickListener {
String returnString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document.json");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
String var =text;
try{
JSONObject jObj = new JSONObject(var);
JSONArray jArray = jObj.getJSONArray("document");
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("id")+
", title: "+json_data.getString("title")
);
returnString += "\n" +"id:"+ json_data.getString("id")+" "+"Title:"+ json_data.getString("title");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
protected void onPostExecute(String results) {
if (results!=null) {
ListView listView = (ListView) findViewById(R.id.mylist);
listView.setFilterText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
You will need to build an Array to use with ListAdapter.
Here is a guide from Google: http://developer.android.com/resources/tutorials/views/hello-listview.html
I think the best solution would be to create a Handler in your activity. You can then send a message to the handler and get the data and put it in the ListView.
In doInBackground "for" loop just either create the array of your data or put data in Array list of object (then need to write custom adapter)
for
1- option
http://www.java-samples.com/showtutorial.php?tutorialid=1516
http://www.ezzylearning.com/tutorial.aspx?tid=1659127&q=binding-android-listview-with-string-array-using-arrayadapter
For
2- option
http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter

passing object through intent from background service to an activity

I want to pass a custom made vector object containing data from background service to an activity in order to updating UI of that activity.
I am not able to pass my data via intent. Please assist me what i need to do..
Following is the code snippet that i am using. In below code I want to pass article list to an activity.
Vector<RowData> getArticleLog() throws JSONException{
Vector<RowData> articleList = new Vector<RowData>();
RowData rd;
InputStream is = null;
String result = null;
JSONArray jarray = new JSONArray();
//Add data to be send.
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("article_title", "Flying Horse"));
try {
HttpClient httpclient = new DefaultHttpClient();
// for local server xampp
HttpPost httppost = new HttpPost("http://10.0.2.2/groupbook/return_article_log.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.i("postData", response.getStatusLine().toString());
} catch (Exception e) {
Log.e(TAG, "json error : " + e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result "+e.toString());
}
try {
jarray = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
//return jArray in the form of Array list;
JSONObject rowElement = null;
int viewers = 0;
int votes = 0;
for (int i = 0; i < jarray.length(); i++) {
rowElement = jarray.getJSONObject(i);
viewers = rowElement.getInt("viewers");
votes = rowElement.getInt("votes");
rd = new RowData(i,
rowElement.getString("article_title"),
Integer.toString(i),
rowElement.getString("last_post_by"),
"2 hours",
rowElement.getString("catagory_tag"),
Integer.toString(viewers),
rowElement.getString("privacy_tag"),
Integer.toString(votes),
rowElement.getString("catagory_title"));
articleList.add(rd);
}
return articleList;
}
RowData class is as follows :
public class RowData {
protected int mId;
public String articleTitle;
public String articleCounter;
public String lastPostBy;
public String updatedTime;
public String catagoryTag;
public String viewingNow;
public String privacyTag;
public String votes;
public String catagoryTitle;
public RowData(int mId, String articleTitle, String articleCounter,
String lastPostBy, String updatedTime, String catagoryTag,
String viewingNow, String privacyTag, String votes,
String catagoryTitle) {
this.mId = mId;
this.articleTitle = articleTitle;
this.articleCounter = articleCounter;
this.lastPostBy = lastPostBy;
this.updatedTime = updatedTime;
this.catagoryTag = catagoryTag;
this.viewingNow = viewingNow;
this.privacyTag = privacyTag;
this.votes = votes;
this.catagoryTitle = catagoryTitle;
}
}
Is following way is right way??
private void DisplayingInfo() throws JSONException{
Log.d(TAG, "entered DisplayLoggingInfo");
intent.putExtra("articleLog", getArticleLog());
sendBroadcast(intent);
}
One thing you can do is to make your custom class implement Serializable (or Parcelable), send the serializable object with putExtra() method to the activity and use getSerializableExtra() on your activity to get it.
Edit 1:
a quick example:
In your custom class:
import java.io.Serializable;
#SuppressWarnings("serial")
public class YourCustomVectorClass implements Serializable {
// ...
}
In your service where you want to start the activity:
Intent intent = new Intent(yourContext, yourActivity.class);
intent.putExtra("theNameOfTheObject", yourObject);
startActivity(intent);
In your activity:
YourCustomVectorClass yourVector = (YourCustomVectorClass) getIntent().getSerializableExtra("theNameOfTheObject");
Edit 2: After reading the question again, I realized that you're passing a Vector of RowData objects to your Activity.
Since Java Vector class implements Serializable, I think you shouldn't do anything but passing the vector to the activity using putExtra() and get it with getSerializableExtra() on the Activity.

Need a simple tutorial for android/webservice work?

I'm really new working with Android, so there's a lot that's confusing me. I've looked at what seems like 100 tutorials and examples of how to get information from a web service on Android, but what I need is something for a guy that doesn't have a clue. Here are a couple of things in particular that I'm not getting:
I don't know what to do with XML files.. meaning, once I do the Java work, is that all that needs to be done? or does anything need to be changed in the XML files?
Seems like maybe I'm supposed to create a new class for some of these tutorials, but I'm not sure, and if so, I'm not sure what to do once I've made the class
I want to retrieve the information in JSON format. For right now as long as I can get just that information that's fine, I can learn how to work with JSON later.
It seems like kSoap2 is the best way to do this. I have the jar file that's needed to work with it
I've delved a little into phonegap, so if there's an answer that uses that, then I can work with that
My web service is working properly, and is essentially the same as what I've seen in a number of tutorials, so there's no problem there.
If anyone can point me to a tutorial that will help me out to learn ALL that I need to know to create a sample app that gets information from my web service, or if anyone is willing to walk me through it, I would greatly appreciate it!
Thanks in advance!
Initially you have to make an http connection so that you can get the response from your api be it xml response or json response. You can use the following code for it.
Keep the class separate than activity. :-
public class Response {
String get_url, response;
Activity activity;
public Response(String url){
this.get_url = url;
}
public String getResponse(){
InputStream in = null;
byte[] data = new byte[1000];
try {
URL url = new URL(get_url);
URLConnection conn = url.openConnection();
conn.connect();
/* conn.*/
in = conn.getInputStream();
Log.d("Buffer Size +++++++++++++", ""+in.toString().length());
BufferedReader rd = new BufferedReader(new InputStreamReader(in),in.toString().length());
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
response = sb.toString();
in.read(data);
Log.d("INPUT STREAM PROFILE RESPONSE",response);
in.close();
} catch (IOException e1) {
Log.d("CONNECTION ERROR", "+++++++++++++++++++++++++++");
// TODO Auto-generated catch block
e1.printStackTrace();
}
return response;
}
}
You may call the class in your activity like this :-
Response res = new Response("your_url");
String getResponse = res.getResponse();
So here you get the response from the api.
Now Lets make the parser
//Extend the class with Default Handler
public class XMLParser extends DefaultHandler {
//You must have basic knowledge about Array List and setter/getter methods
// This is where the data will be stored
ArrayList<Item> itemsList;
Item item;
String data;
String type;
private String tempVal;
//Create the Constructor
public XMLParser(String data){
itemsList = new ArrayList<Item>();
this.data = data;
}
public byte parse(){
SAXParserFactory spf = null;
SAXParser sp = null;
InputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(data.getBytes());
spf = SAXParserFactory.newInstance();
if (spf != null) {
sp = spf.newSAXParser();
sp.parse(inputStream, this);
}
}
/*
* Exceptions need to be handled MalformedURLException
* ParserConfigurationException IOException SAXException
*/
catch (Exception e) {
System.out.println("Exception: " + e);
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception e) {
}
}
if (itemsList != null && itemsList.size() > 0) {
// //Log.d("Array List Size",""+tipsList.get(4).getTitle());
return 1;
} else {
return 0;
}
}
public ArrayList<Item> getItemList(){
return itemsList;
}
// Here you can check for the xml Tags
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(localName.equalsIgnoreCase("item")){
item = new Item();
Log.d("Working", "+++++++++++++++++++++++");
}
}
//tempVal is the variable which stores text temporarily and you
// may save the data in arraylists
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equalsIgnoreCase("item")){
itemsList.add(item);
Log.d("Working in endelement", "+++++++++++++++++++++++");
item.setTitle(tempVal);
}
}
Combining all this :-
Now lets see the activity
public void oncreate(){
// Do something or mostly the basic code
// Call the class to initate the connection and get the data
FetchList fl = new FetchList();
fl.execute();
}
//Always better to use async task for these purposes
public class FetchList extends asyncTask<Void,Void,Byte>{
doinbackground{
// this was explained in first step
Response res = new Response("url");
String response = res.getResponse();
XmlParser xml = new XmlParser(response);
ArrayList<item> itemList = xml.getItemList();
xml.parse();
}
}
Well that is all to it.

Categories

Resources