Monday, 17 December 2012

AsyncTask with ProgressBar and Xml parsing using DOM parser

AsynCall.java ::

package com.web;

import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.w3c.dom.Document;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;

public class Async extends AsyncTask<String, Void, Document> {

public ProgressDialog pDialog;
Context context;
public boolean isRunning = false;
AsyncListener listener;
public boolean isCancelled = false;
String errorMessage;
boolean isError = false;
public String message = "Loading please wait...";
Document doc;
DefaultHttpClient client;
HttpParams httpParameters;

public Async(Context context) {
this.context = context;
pDialog = new ProgressDialog(context);
pDialog.setMessage(message);
pDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

@Override
public void onCancel(DialogInterface arg0) {
cancel(true);
}
});
client = new DefaultHttpClient(httpParameters);
}

@Override
protected Document doInBackground(String... params) {
try {
pDialog.setCancelable(false);
HttpGet uri = new HttpGet("Your Url.");
httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 4000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
client = new DefaultHttpClient(httpParameters);
HttpResponse resp = client.execute(uri);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(resp.getEntity().getContent());
return doc;
} catch (Exception e) {
     e.printStack();
return null;
}
}

public void setAsyncListener(AsyncListener listener) {
this.listener = listener;
}

public void setProggressDialogMessage(String msg) {
this.message = msg;
}

@Override
protected void onPostExecute(Document doc) {
pDialog.dismiss();
if (listener != null) {
if (isError) {
listener.onErrorReceived(errorMessage);
} else
listener.onResponseReceived(doc);
}
}

@Override
protected void onPreExecute() {
pDialog.setMessage(message);
showProgressbar();
}

private void showProgressbar() {
if (!isCancelled) {
pDialog.show();
}
}

@Override
protected void onCancelled() {
pDialog.dismiss();
super.onCancelled();
isCancelled = true;
}
}

AsyncListener.java ::


package com.web;
import org.w3c.dom.Document;

public interface AsyncListener {
  public void onResponseReceived(Document doc);
public void onErrorReceived(String str);
}

AsyncActivity.java ::

public class AsyncActivity  extends BaseActivity{
public AsyncCall asyncCall;
private Async async;
@Override
public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
asyncCall = (AsyncCall) getLastNonConfigurationInstance();
  
if (asyncCall == null) {
asyncCall = new AsyncCall(this);
}
async = (Async) getLastNonConfigurationInstance();
if (async == null) {
async = new Async(this);
}
}
  
@Override
public void onResume() {
if(async != null && async.isRunning && async.pDialog != null && !async.pDialog.isShowing()) {
async.pDialog.setMessage(async.message);
async.pDialog.show();
}
else if(async != null && !async.isRunning && async.pDialog.isShowing()) {
async.pDialog.dismiss();
}
if(asyncCall != null && asyncCall.isRunning && asyncCall.pDialog != null && !asyncCall.pDialog.isShowing()) {
asyncCall.pDialog.setMessage(asyncCall.message);
asyncCall.pDialog.show();
}
else if(asyncCall != null && !asyncCall.isRunning && asyncCall.pDialog.isShowing()) {
asyncCall.pDialog.dismiss();
}
super.onResume();
}
    @Override
    protected void onPause() {
    super.onPause();
    }
}

XMLParser :: 


public class XMLParser {

/**
* Getting XML from URL making HTTP request
* @param url string
* */


public String getXmlFromUrl(String url) {
String xml = null;
try {
       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;
}

/**
* 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) {
return null;
} catch (SAXException e) {
return null;
} catch (IOException e) {
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));
}


// code snipest ::


NodeList nl,statelist;
nl= doc.getElementsByTagName("country");
XMLParser parser = new XMLParser();
// looping through all item nodes <item>
if(nl != null) {
for (int i = 0; i < nl.getLength(); i++) {
Country country_obj = new Country();
Element e = (Element) nl.item(i);

country_obj.c_id = parser.getValue(e, "id");
country_obj.c_name = parser.getValue(e, "c_name");
statelist = e.getElementsByTagName("state");
------------------------------------

}
}

1 comment:

  1. Playcasino - Jacksonville, MS Jobs | JtmHub
    Learn 이천 출장안마 about Playcasino jobs, salaries, 수원 출장안마 top office 이천 출장안마 locations and how you can get started. 남원 출장안마 Get top 김해 출장샵 pay for jobs in Jacksonville, MS.

    ReplyDelete