I have android code which has two integers variables getting from HashMap Key , value .
i'm trying to pass these two variables to SOAP web service but nothing happened .
notes 1: I'm sure my WebService code is working and entering the right data to database , i have tested it .
note 2 : FROM debug shows that "SID" and "status" has right values .
but the problem in sending these values to SOAP .
FULL SOAP code in android Activity :
sumbit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (Map.Entry<Integer, Integer> mapEntry : checkBoxState
.entrySet()) {
int SID = mapEntry.getKey();
int status = mapEntry.getValue();
Toast.makeText(context,
String.valueOf(SID) + String.valueOf(status),
Toast.LENGTH_SHORT).show();
try {
SoapObject request = new SoapObject(NAMESPACE,
METHOD_NAME);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
PropertyInfo pi = new PropertyInfo();
pi.setName("SID");
pi.setValue(SID);
pi.setType(Integer.class);
request.addProperty(pi);
PropertyInfo pi2 = new PropertyInfo();
pi2.setName("status");
pi2.setValue(status);
pi2.setType(Integer.class);
request.addProperty(pi2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
androidHttpTransport.call(SOAP_ACTION, envelope);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FULL webService Method Code :
public void insertApsentData(int SID , int status ) throws SQLException, ClassNotFoundException, ReflectiveOperationException, Throwable{
// Make new Connection to database .
Dbconnection NewConnect = new Dbconnection();
Connection con = NewConnect.MakeConnect();
Statement stmt = con.createStatement();
// this i'm usre is working fine
stmt.executeUpdate("INSERT INTO apsent SET course_id=1, teacher_id= 1 , class_id= 3 , interval_id= 5 , day_id = 1 , APSSENT_DATE = CURdate() ,state = " + status + ", student_id = " + SID +" ,school_id = 1;");//called the procedure
}
I have had this problem before. Have you tried generating the wsdl using eclipse?(see page 6). This tool generates the client code for a webservice and makes it easy to call something like
ServiceProxy.insertApsentData(args)
There is some project Folders are closed , i reopened it and it's works now .
Related
I am fairly new to android programming and I have faced a small problem. I have an arraylist consisting of names of person selected from a multi-select listview, the problem is that Whenever I insert those arraylist values into the database, It inserts it as one string:
Database row. How do i iterate thru an arraylist and at the same time insert its values into the database?
here is my code:
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {
String samp = "";
String names = "";
samp = myArrayAdapter.getCheckedItems().toString();
ArrayList<String> data1 = new ArrayList<String>();
data1.add(samp);
for(int x=0; x<data1.size(); x++)
{
names += String.valueOf(data1.get(x));
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+names+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
}
Toast.makeText(getApplicationContext(), "INSERT SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "INSERT FAILED", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}
Thank you for any future replies.
Can you try with that?
List<String> data1 = new ArrayList<String>(Arrays.asList(samp.replace("[","").replace("]","").split(",")));
for (String name : data1) {
names += name; // This lines concatenate the name.
//If you want to insert single name the you can directly insert the name value into databas.
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+name+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
}
look at this code...
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi=new PropertyInfo();
pi.setName("UserName");
pi.setValue(txtName.getText().toString());
pi.setType(String.class);
request.addProperty(pi);
pi=new PropertyInfo();
pi.setName("UserAge");
pi.setValue(txtVal.getText().toString());
pi.setType(String.class);
request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(webRequest);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope);
Log.d("CheckLogin-SOAP ACTION", SOAP_ACTION + METHOD_NAME);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.d("CheckLogin - Response", response.toString());
status= Boolean.valueOf(response.toString());
i am trying to set up connection to SOAP WebService from Android app but every time i get wried error in my result :
object reference not set to an instance of an object java
It seems to be error from server --> SOAP Webservice call from Java gives "Object reference not set to an instance of an object"
But when i try it throught web browser with POST request it works fine :)
This service http://ws.cdyne.com/ip2geo/ip2geo.asmx?op=ResolveIP
private static String NAMESPACE = "http://ws.cdyne.com/";
private static String URL = "http://ws.cdyne.com/ip2geo/ip2geo.asmx";
private static String SOAP_ACTION = "http://ws.cdyne.com/";
public static String invokeHelloWorldWS(String name, String webMethName) {
String resTxt = null;
SoapObject request = new SoapObject(NAMESPACE, webMethName);
PropertyInfo sayHelloPI = new PropertyInfo();
// Set name
sayHelloPI.setName("ipAddress");
// Set Value
sayHelloPI.setValue("88.212.35.129");
// Set dataType
sayHelloPI.setType(String.class);
// Add the property to request object
request.addProperty(sayHelloPI);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
try{
// Invoke web service
androidHttpTransport.call(SOAP_ACTION+webMethName, envelope); //webMethName = "ResolveIP"
// Get the response
Log.d("a", androidHttpTransport.responseDump);
//SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
// Assign it to resTxt variable static variable
//resTxt = response.toString();
}catch(Exception e){
//Print error
e.printStackTrace();
}
}
I spend lot of time on google but i cant figure right answer why this happend
// EDIT
Finally i get it right ... idk why but when i send second parameter like this (i reuse old property) :
sayHelloPI.setName("licenseKey");
sayHelloPI.setValue("some_key");
sayHelloPI.setType(String.class);
request.addProperty(sayHelloPI);
it wasnt working. But when i make new Property object it works:
PropertyInfo sayHelloPI1 = new PropertyInfo();
sayHelloPI1.setName("licenseKey");
sayHelloPI1.setValue("ds");
sayHelloPI1.setType(String.class);
request.addProperty(sayHelloPI1);
Maybe it help someone next time
This is some code that I have used myself - Hope it will help you:
// Initialize soap request + add parameters
SoapObject request = new SoapObject(getString(R.string.Namespace),
getString(R.string.Method_Name_GetStudentsByTeam));
Log.d("GetStudentsByTeamTask", "SOAP request");
// Use this to add parameters
request.addProperty("teamId", params[0]);
Log.d("GetStudentsByTeamTask", "id: " + params[0]);
// Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
Log.d("GetStudentsByTeamTask",
"Declared the version of the SOAP request");
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
Log.d("GetStudentsByTeamTask", "Setting som variables");
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(
getString(R.string.URL));
Log.d("GetStudentsByTeamTask", "Instance the HttpTransportSE");
// this is the actual part that will call the webservice
androidHttpTransport.call(
getString(R.string.Soap_Action_GetStudentsByTeam),
envelope);
Log.d("GetStudentsByTeamTask", "Called the Webservice");
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject) envelope.getResponse();
Log.d("GetStudentsByTeamTask", "Got the Soapresult");
if (result != null) {
// Do something with result
// success = true;
Log.d("GetStudentsByTeamTask", "set sucess boolean to true");
for (int i = 0; i < result.getPropertyCount(); i++) {
PropertyInfo pi = new PropertyInfo();
result.getPropertyInfo(i, pi);
Log.d("GetStudentsByTeamTask",
pi.name + " : " + result.getProperty(i));
SoapObject obj = (SoapObject) result.getProperty(i);
Student student = new Student();
student.address = obj.getProperty("Address").toString();
student.city = obj.getProperty("City").toString();
student.created = DateTime.parse(obj.getProperty(
"Created").toString());
student.dateOfBirth = DateTime.parse(obj.getProperty(
"DateOfBirth").toString());
student.email = obj.getProperty("Email").toString();
student.firstname = obj.getProperty("FirstName")
.toString();
student.id = Integer.parseInt(obj.getProperty("ID")
.toString());
student.imageId = Integer.parseInt(obj.getProperty(
"ImageID").toString());
// SoapObject lastNameObject = (SoapObject) obj
// .getProperty("LastName");
//
student.lastName = obj.getProperty("LastName")
.toString();
student.phone = obj.getProperty("Mobile").toString();
student.zipcode = obj.getProperty("PostalCode")
.toString();
student.schoolId = Integer.parseInt(obj
.getPropertyAsString("SchoolId"));
student.teamId = Integer.parseInt(obj
.getPropertyAsString("TeamId"));
student.testStarted = Integer.parseInt(obj
.getPropertyAsString("TestsStarted"));
student.timeStamp = DateTime.parse(obj
.getPropertyAsString("TimeStamp"));
student.image = getImage(Integer.parseInt(obj
.getProperty("ImageID").toString()));
if (student.image == null)
student.image = BitmapFactory
.decodeResource(getResources(),
R.drawable.default_usericon);
MyApp.getController().addStudent(student);
}
} else {
// If fails
// success = false;
Log.d("GetStudentsByTeamTask", "set login boolean to false");
}
} catch (Exception e) {
Log.d("GetStudentsByTeamTask", "FAILED! " + e.getMessage());
e.printStackTrace();
}
This has been asked in different ways so far, but I am unable to find a solution to this particular issue.
Short Version:
I am seeking a way to fetch json from a URL that requires authentication. And rather than authenticating every time, I want it to store the received cookies so that it doesn't have to re-login, and on subsequent connections remain logged in.
Long version:
Basically, I want the app to store the user's username and password (as internal private strings with shared preferences). Then after that, it would call a login url to authenticate and remain logged in(get the cookies). Once this is done, I want the program to fetch json data from different urls (that require a user to be logged in via cookies for example). I want this to remain in place even after the app is paused or destroyed.
It can be considered as an idea similar to a chrome plugin that can simply fetch data from a website once its logged in.
I reckon the solution to this would be useful for many developers who are new to android.
try this it stores username pass and session into shared pref
app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
userid=app_preferences.getLong("userid",0);
username=app_preferences.getString("username", "");
password=app_preferences.getString("password", "");
session=app_preferences.getString("session", "");
class task extends AsyncTask<String, integer, Boolean>{
//httpreqclass htrq= new httpreqclass();
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
showProgressDialog();
}
#Override
protected Boolean doInBackground(String... params) {
String usr=params[0];
String p=params[1];
String data[]=new String[2];
String ur= "http://192.168.1.45/Android.asmx/Login";
// TODO Auto-generated method stub
data= postData(usr,p,ur);
boolean sucess=false;
try {
JSONObject jso = new JSONObject(data[0]);
sucess =jso.getBoolean("isSucceeded");
if (sucess) {
SharedPreferences.Editor editor = app_preferences.edit();
JSONObject jsr= jso.getJSONObject("result");
Long a= jsr.getLong("Id");
editor.putLong("userid", a);
editor.putString("username", usr);
editor.putString("password", p);
editor.putString("session", data[1]);
editor.commit(); // Very important
}
}catch (Exception e){
}
return sucess;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
here put code what you want to do next
}
}
public String[] postData(String u, String p,String url) {
String asp = null,data = null;
String[] rtrn=new String[2];
//Log.e("i entrd here", "");
try {
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpPost httppost = new HttpPost();
HttpResponse response;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("EmailId", u));
params.add(new BasicNameValuePair("PassWord", p));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
httppost.setEntity(ent);
response = httpclient.execute(httppost);
Header[] headers;
headers = response.getHeaders("Set-Cookie");
//Header atha= respone.getFirstHeader("PHPSESSID");
List<Cookie> cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();
if (cookies.isEmpty()) {
Log.d("TAG","no cookies received");
} else {
for (int i = 0; i < cookies.size(); i++) {
if(cookies.get(i).getName().contentEquals("ASP.NET_SessionId")) {
asp = cookies.get(i).getValue();
}
}
Log.e("this is the cookiee", asp);
}
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
Log.e("", sb.toString());
rtrn[0]=sb.toString();
rtrn[1]=asp;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rtrn;
}
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, 3000);
HttpConnectionParams.setSoTimeout(htpp, 5000);
return htpp;
}
you can refer the code and make the application as per your logic
and note when the next time onwards when you send a request to the server do not forget to add the session/cookie in the header
Just to not leave the question unanswered and explain how I solved the problem, here is my answer.
I resorted to use the Loopj Android Async Http Client library, which is being used by major apps like Instagram and Pinterest.
Keeping the cookies persistent is pretty simple this way. All you need is:
AsyncHttpClient myClient = new AsyncHttpClient(); // a client instance
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore); // setting the cookie store
i am new in blackberry & calling WCF services by using ksoap method.
when i am calling a service it gives an error message on simulator.
The error is:
unexpected type(position :text--uuid:dcd5cdf3..#3:13 in java.io.StreamReader#a0190eaa)
this service successfully call in dot net.
My code:
String serviceUrl = "<service url>";
String serviceNameSpace ="<service namespaces>";
String soapAction = "<service soapaction>";
String methodName = "logOn";
SoapObject rpc = new SoapObject(serviceNameSpace, methodName);
//String a="52";
//String b="28";
rpc.addProperty("username", String.valueOf(edUserName.getText()));
rpc.addProperty("password",String.valueOf(edPaswd.getText()));
// rpc.addProperty("a","nil");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = rpc;
envelope.dotNet = true; //IF you are accessing .net based web service this should be true
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
//HttpTransport ht = new HttpTransport(serviceUrl);
HttpTransport ht = new HttpTransport(serviceUrl + "; deviceside=true; apn=blackberry.net");
ht.debug = true;
//SoapObject result=null;
//ht.setXmlVersionTag("");
try
{
ht.call(soapAction, envelope);
String result = (envelope.getResponse()).toString();
Dialog.alert(result);
Dialog.alert("login success");
}
catch(Exception ex2)
{
Dialog.alert("error is :"+ex2.getMessage());
}
// if((edUserName.getText().equals("")))
// {
// Dialog.alert("Enter User Name ");
// }
// if(edPaswd.getText().equals(""))
// {
// Dialog.alert("Enter Password");
//
// }
An error from StreamReader means it has some bad data coming from the HttpTransport. Try doing what is suggested in this forum post, especially since it also deals with a .NET WebService.
I have added the library "ksoap2-android-assembly-2.4-jar-with-dependencies.jar "
but i am getting below error :
Exception in thread "main" java.lang.NullPointerException at org.kxml2.io.KXmlParser.require(KXmlParser.java:1353) at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:127) at org.ksoap2.transport.Transport.parseResponse(Transport.java:63) at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:100)
private void getData()
{
String METHOD_NAME = "schedule.setschedule";
String SOAP_ACTION = "urn:schedule#setschedule";
String NAMESPACE = "urn:schedule";
String URL = "http://96.30.19.40:8080/server.php?wsdl";
try {
SoapObject request=soap(METHOD_NAME,SOAP_ACTION,NAMESPACE,URL);
System.out.println("suceess");
System.out.println(request.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("fail1");
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("fail2");
}
}
public static SoapObject soap(String METHOD_NAME, String SOAP_ACTION, String NAMESPACE, String URL) throws IOException, XmlPullParserException {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); //set up request
request.addProperty("iTopN", "5"); //variable name, value. I got the variable name, from the wsdl file!
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); //put all required data into a soap envelope
envelope.setOutputSoapObject(request); //prepare request
HttpTransport httpTransport = new HttpTransport(URL);
httpTransport.debug = true; //this is optional, use it if you don't want to use a packet sniffer to check what the sent message was (httpTransport.requestDump)
httpTransport.call(SOAP_ACTION, envelope); //send request
SoapObject result=(SoapObject)envelope.getResponse(); //get response
return result;
}
The correct download url for the project is here
http://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2
The direct url provided above is an old version. Read the instructions and download the complete bundle.
You may not have the correct ksoap2 package