Thursday 25 September 2014

Activity using webservice


Activity using webservice


1. Creating input parameters
2. Calling  web services using controls.
3. Call webservices class from background method
4. Handling result in post method.



Web Service Class




public class WS_Request {

private static final String NAMESPACE = "http://tempuri.org/";
private static final String METHOD_NAME = "Request";
private static final String SOAP_ACTION = "http://tempuri.org/methodname";
private static final String URL = "http://www.webservice.asmx";

private static final int retryCount = 7;
public String SoapAction(String[] values){

String[] data = new String[]
 {
Username",
"password",
"fromdate",
"todate",
"REQUESTID",
"DataString"};


SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
for(int i = 0; i < data.length; i++){
PropertyInfo property = new PropertyInfo();
property.setName(data[i]);
property.setNamespace(NAMESPACE);
property.setType(PropertyInfo.STRING_CLASS);
property.setValue(values[i]);
Log.i("test", data[i]+"::"+values[i]);
request.addProperty(property);
}


SoapSerializationEnvelope envelope;
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
String resultString = "";
int loopCount = 0;



while ((resultString.equalsIgnoreCase("") || resultString.equalsIgnoreCase("serverError") ||                              resultString.equalsIgnoreCase("Data Not Found")) && loopCount < retryCount) {

try{
HttpTransportSE http = new HttpTransportSE(URL);
http.debug = true;
System.setProperty("http.keepAlive", "false");
http.call(SOAP_ACTION, envelope);
//Log.v("SoapAction for index no " + values[3], "2");
}catch (IOException e1) {
e1.printStackTrace();
//Log.w("IOException for index no " + values[3], e1.toString());

resultString = "serverError";
} catch (XmlPullParserException e1) {
e1.printStackTrace();
//Log.w("XmlPullParserException for index no " + values[3], e1.toString());
resultString = "serverError";
} catch (Exception e) {
e.printStackTrace();
//Log.w("Exception for index no " + values[3], e.toString());
resultString = "serverError";

}

if(!resultString.equalsIgnoreCase("serverError")) {
SoapPrimitive soapResult = null;

try{
soapResult = (SoapPrimitive)envelope.getResponse();
}catch (SoapFault e) {
e.printStackTrace();
//Log.w("SoapFaultException for index no " + values[3], e.toString());
resultString = "serverError";
}

if(soapResult != null){
resultString = soapResult.toString();
Log.i("resultstring", resultString);
} else {

resultString = "serverError";
}
}
loopCount += 1;
}

return resultString;
}

}





Activity Class


String[] values={
et_Uname.getText().toString(),
et_upw.getText().toString().trim(),
 "01/01/2012", "01/01/2014", "110", "10055"};

Web_Req_Asyn obj_Web_Req_Asy= new Web_Req_Asyn();
obj_Web_Req_Asy.execute(values);




Asyntask Class


public class Web_Req_Asyn extends AsyncTask<String[], Void, String> {

ProgressDialog pdlg;
public String xml_result_set="";
public String str_DmanCode;


@Override
protected void onPreExecute() {
super.onPreExecute();

pdlg = new ProgressDialog(Registration_login.this);
pdlg.setTitle("Stock And Sale");
pdlg.setMessage("Validating with server...");
pdlg.show();
pdlg.setCancelable(false);
}


@Override
protected String doInBackground(String[]... params) {

if (checkNetwork()) {
WS_Request ob1 = new WS_Request();
String[] values = params[0];
Log.i("", " Sending Envolope file");
xml_result_set = ob1.SoapAction(values);
if(!xml_result_set.equalsIgnoreCase("serverError")) {

/// Wot to do ???

}
} else {
return "networkError";
}
return xml_result_set;
}

@SuppressLint("ShowToast")
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("onPostExecute", "result : " + result);
pdlg.dismiss();
if(result.equalsIgnoreCase("serverError")) {
vibrate_alert();
new AlertDialog.Builder(Registration_login.this)
.setTitle("User Details Error")
.setMessage("Invalid User details.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
}).show();

} else if(result.equalsIgnoreCase("networkError")) {


} else if(result.trim().equals("<Masters />")) {
vibrate_alert();

new AlertDialog.Builder(Registration_login.this)
.setTitle("Attention!")
.setMessage("Invalid User details.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
}).show();

} else {

String[] parts = xml_result_set.split("~");

if(parts[0].equalsIgnoreCase("1")){

                                       // IF RESULT IS XML START HERE


ArrayList<HashMap<String, String>> filemaps = XMLfunctions
.ParseData(xml_result_set, new String[] { "xmlnode-1",
"xmlnode-2", "xmlnode-3", "xmlnode-3"},                                                                              "Xmlheader");

int count = filemaps.size();
int i;
for (i = 0; i < count; i++) {
String resultone = filemaps.get(i).get("xmlnode-1"");
Editor edit = pref.edit();
edit.putString("result", resultone );
edit.commit();

                                       // IF RESULT IS XML ENDS  HERE


                                        String result=parts[1];
Intent intent = new Intent(getApplicationContext(), activitytwo.class);
bundle.putString("result", result);
bundle.putString("User_ID",    et_Uname .getText().toString().trim() );
bundle.putString("User_PW",  et_upw.getText().toString().trim());
intent.putExtras(bundle);
startActivity(intent);

}
else{
vibrate_alert();
Intent intent = new Intent(getApplicationContext(), activityone.class);
startActivity(intent);
}

}
}

private void vibrate_alert() {
Vibrator vibrator;
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
// TODO Auto-generated method stub

}

@SuppressLint("ShowToast")
protected boolean checkNetwork() {

try {
java.net.URL myUrl = new java.net.URL("http://www.service.asmx");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(2000);
connection.connect();
connection_status_flag = true;
} catch (Exception e) {
Log.w("checkNetwork", e.toString());
connection_status_flag = false;
}
return connection_status_flag;
}
}





// XML parsing class (Depends on result)


public class XMLfunctions {
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 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));
}

/******** Parsing XML String to data ********/
public static String[] ParseData(String xml, String code, String header) {

org.w3c.dom.Document doc = XMLfunctions.XMLfromString(xml);

NodeList nodes = doc.getElementsByTagName(header);
String[] spin = new String[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++) {
Element e = (Element) nodes.item(i);
spin[i] = XMLfunctions.getValue(e, code);

}
return spin;
}

/*************************************************************************************/

public static ArrayList<HashMap<String, String>> ParseData(String xml,
String[] code, String header) {

org.w3c.dom.Document doc = XMLfunctions.XMLfromString(xml);

int counter = code.length;

ArrayList<HashMap<String, String>> filemaps = new ArrayList<HashMap<String, String>>();
NodeList nodes = doc.getElementsByTagName(header);
for (int i = 0; i < nodes.getLength(); i++) {
Element e = (Element) nodes.item(i);
HashMap<String, String> map = new HashMap<String, String>();
for (int j = 0; j < counter; j++) {
map.put(code[j], XMLfunctions.getValue(e, code[j]));
//Log.i("xmlreply", XMLfunctions.getValue(e, code[j]));
}
filemaps.add(map);
}
return filemaps;
}
}




No comments:

Post a Comment

How to do text writing animation?  In Android Development we do not have the option to use any other custom font in our default Tex...