I try to create web service, code for webservice client of android appliaction as below:
String SOAP_ACTION = "";
String METHOD_NAME = "operation1";
String NAMESPACE = "http://service.livebackup.com/";
String URL = "http://192.168.1.3:8084/test/webService?wsdl";
Button signin;
Thread t;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
signin = (Button) findViewById(R.id.btn_sign_in);
signin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(0);
t=new Thread() {
public void run() {
tryLogin();
}
};
t.start();
}
});
}
private void tryLogin() {
// TODO Auto-generated method stub
EditText etxt_user = (EditText) findViewById(R.id.txt_username);
EditText etxt_pass = (EditText) findViewById(R.id.txt_password);
String username = etxt_user.getText().toString();
String password = etxt_pass.getText().toString();
callWebService(username,password);
}
private void callWebService(String username, String password) {
// TODO Auto-generated method stub
//String result = "ishan";
try {
int no=2;
SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
PropertyInfo p1 = new PropertyInfo();
Check C = new Check();//use check KvmSerializable{
C.UserName=username;
C.PassWord=password;
p1.setName("C");
p1.setValue(C);
p1.setType(C.getClass());
request.addProperty(p1);
SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=false;
envelope.setOutputSoapObject(request);
androidHttpTransport.call(SOAP_ACTION, envelope);
Log.v("Ok","wait for response");
Object results =(Object)envelope.getResponse();
Log.v("Ok","Connection has response object" +results);
Log.v("Ok","jj");
//to get the data String resultData=result.getProperty(0).toString();
String temp = results.toString();
Log.v("Ok","Connection has response" +temp);
}
catch (Exception e) {
// TODO: handle exception
System.out.println("Error:" +e.getClass().getName()+":"+e.getMessage());
}
}
check class as follow:
public class Check implements KvmSerializable{
public String UserName;
public String PassWord;
public Check(){}
public Check(String userName, String passWord) {
super();
UserName = userName;
PassWord = passWord;
}
#Override
public Object getProperty(int arg0) {
// TODO Auto-generated method stub
switch(arg0)
{
case 0:
return UserName;
case 1:
return PassWord;
}
return null;
}
#Override
public int getPropertyCount() {
// TODO Auto-generated method stub
return 2;
}
#Override
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
// TODO Auto-generated method stub
switch(index)
{
case 0:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "UserName";
break;
case 1:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "PassWord";
break;
default:break;
}
}
#Override
public void setProperty(int index, Object value) {
// TODO Auto-generated method stub
switch(index)
{
case 0:
UserName = value.toString();
break;
case 1:
PassWord = value.toString();
break;
default:
break;
}
}
}
My problem: i use net beans jax-ws on server side,
how to i handle a request of username & password from android ws -client,
i complete done with only request.addproperty("userName",username);
plz,help..
First of all, in your client:
UserName and PassWord are Strings, but you treated them as int. In Check class do this:
#Override
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
switch(index) {
case 0:
info.type = PropertyInfo.STRING_CLASS;
info.name = "UserName";
break;
case 1:
info.type = PropertyInfo.STRING_CLASS;
info.name = "PassWord";
break;
default:
break;
}
Remove wsdl at the end of your URL string:
String URL = "http://192.168.1.3:8084/test/webService/";
In your server: check it out http://www.ibm.com/developerworks/webservices/library/ws-android/index.html
Hope it helps.
Related
public class MovieDescription extends Activity {
Vibrator vibrator;
TextView tv_title,tv_year,tv_banner,tv_desc;
RatingBar ratingBar;
ImageView iv_watch,iv_poster;
private static final String TAG_CONTACTS = "Demo";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_YEAR = "year";
private static final String TAG_RATING = "rating";
private static final String TAG_BANNER= "category";
private static final String TAG_DESC = "description";
private static final String TAG_URL = "url";
private static final String TAG_POSTER = "poster";
String id,title,year,rating,banner,description,poster, movieUrl;
static JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_description);
initialize();
String movieDescUrl = "http://vaibhavtech.com/work/android/movie_description.php?id="+MainActivity.movie_Id;
MovieDescriptionParser jParser = new MovieDescriptionParser();
JSONObject json = jParser.getJSONFromUrl(movieDescUrl);
try {
contacts = json.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++)
{
/**********************************Value Parse FromUrl**********************************/
JSONObject c = contacts.getJSONObject(i);
id = c.getString(TAG_ID);
title = c.getString(TAG_TITLE);
year = c.getString(TAG_YEAR);
rating = c.getString(TAG_RATING);
banner=c.getString(TAG_BANNER);
description = c.getString(TAG_DESC);
movieUrl = c.getString(TAG_URL);
poster = c.getString(TAG_POSTER);
/**********************************Valeu Assing to UI Component**********************************/
Log.i(id, title);
}
} catch (JSONException e) {
e.printStackTrace();
}
tv_title.setText(title);
tv_year.setText(year);
tv_banner.setText(banner);
tv_desc.setText(description);
Float rat=Float.parseFloat(rating);
ratingBar.setRating(rat);
Bitmap bimage= getBitmapFromURL("http://vaibhavtech.com/work/android/admin/upload/"+poster);
iv_poster.setImageBitmap(bimage);
iv_watch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibrator.vibrate(40);
LayoutInflater inflater=getLayoutInflater();
View view=inflater.inflate(R.layout.customtoast,(ViewGroup)findViewById(R.id.custom_toast_layout));
Toast toast=new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setView(view);
toast.show();
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(movieUrl));
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.i("Device Versoin is", ""+currentapiVersion);
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN){
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
getMenuInflater().inflate(R.menu.main, menu);
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Log.i("Home", "Press");
return true;
}
return super.onOptionsItemSelected(item);
}
public void initialize()
{
tv_banner=(TextView) findViewById(R.id.tv_movie_description_banner);
tv_desc=(TextView) findViewById(R.id.tv_movie_description_decription);
tv_title=(TextView) findViewById(R.id.tv_movie_description_name);
tv_year=(TextView) findViewById(R.id.tv_movie_description_year);
ratingBar=(RatingBar) findViewById(R.id.ratingBar1);
iv_watch=(ImageView) findViewById(R.id.iv_movie_description_watch);
iv_poster=(ImageView) findViewById(R.id.iv_movie_description_poster);
vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);;
}
public static Bitmap getBitmapFromURL(String src) {
try {
Log.i("src",src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.i("Bitmap","returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
}
When I am clicking on "watch now" button it's giving me four options - by mozilz, by Chrome, by YouTube. I want that when I click on watch now button it get redirect on YouTube url link. How can I do this?
Try this :
Intent i = app.getPackageManager().getLaunchIntentForPackage("com.google.android.youtube");
if (i != null)
app.startActivity(i);
Check this link also : Redirect YouTube in Android
Hope this helps.
I'm struggeling on getting a complex type (list) out of my response for three days now, but always getting a ClassCastException
D/SOAPEnvelope(1552): Error: java.lang.ClassCastException: org.ksoap2.serialization.SoapObject cannot be cast to com.example.webservice.ResponsiblepartyGetResponse
I read several linked pages / tutorials so often that I almost can tell them by mind, including these four very helpful pages:
http://seesharpgears.blogspot.de/2010/10/web-service-that-returns-array-of.html
http://code.google.com/p/ksoap2-android/wiki/CodingTipsAndTricks#sending/receiving_array_of_complex_types_or_primitives
ksoap2 Receive Array of complex objects via SOAP
How to parse this Web service response in Android?
and many more, but I still don't get it :(
I hope I'll give you all the input you need to show me my mistake and give me a hint to fix it. The webservice is already successfully implemented in a rich client application and I have to build an android app now using the same webservice.
My first step is to handle a "responsibleparty_get"-Response.
My response looks (with a limit to 3, but can be more/less) like this. Note: There are two additional properties of the "responsiblePartyFacades" that are just null for these responses (see below in the JAVADOC).
responsibleparty_getResponse{
responsiblePartyFacades=anyType{
id=1;
name=hans;
discriminator=person;
admin=false;
};
responsiblePartyFacades=anyType{
id=2;
name=dieter;
discriminator=person;
admin=false;
};
responsiblePartyFacades=anyType{
id=3;
name=stefan;
discriminator=person;
admin=false;
};
}
The related XML looks like this (got out of SoapUI):
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:responsibleparty_getResponse xmlns:ns2="http://ws.my-url.com/">
<responsiblePartyFacades>
<id>1</id>
<name>hans</name>
<discriminator>person</discriminator>
<admin>false</admin>
</responsiblePartyFacades>
<responsiblePartyFacades>
<id>2</id>
<name>dieter</name>
<discriminator>person</discriminator>
<admin>false</admin>
</responsiblePartyFacades>
<responsiblePartyFacades>
<id>3</id>
<name>stefan</name>
<discriminator>person</discriminator>
<admin>false</admin>
</responsiblePartyFacades>
</ns2:responsibleparty_getResponse>
</S:Body>
</S:Envelope>
From our JAVADOC (out of the rich client) the responsiblePartyFacades looks the same:
* <complexType name="responsiblePartyFacade">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="discriminator" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="admin" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="children" type="{http://ws.my-url.com/}pairIntBoolFacade" maxOccurs="unbounded" minOccurs="0"/>
* <element name="plantcomponents" type="{http://www.w3.org/2001/XMLSchema}int" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
So far, so nice.
I wrote these classes to handle the reponse:
ResponsiblepartyGetResponse
public class ResponsiblepartyGetResponse extends Vector<ResponsiblePartyFacade> implements KvmSerializable {
private static final long serialVersionUID = -8065084038519643055L;
#Override
public Object getProperty(int index) {
return this.get(index);
}
#Override
public int getPropertyCount() {
return this.size();
}
#Override
public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) {
info.name = "ResponsiblePartyFacades";
info.type = new ResponsiblePartyFacade().getClass();
}
#Override
public void setProperty(int index, Object value) {
// add ResponsiblePartyFacade to vector
this.add((ResponsiblePartyFacade) value);
}
}
ResponsiblePartyFacade: For now i comment out the vecor-items as they are not in the response, because I throught it might work (as there are several blogs on the web saying ksoap2 vector does not work).
public final class ResponsiblePartyFacade implements KvmSerializable {
private Integer id;
private String name;
private String discriminator;
private Boolean admin;
// private List<PairIntBoolFacade> children; // not used
// private List<Integer> plantcomponents; // not used
public ResponsiblePartyFacade() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDiscriminator() {
return discriminator;
}
public void setDiscriminator(String discriminator) {
this.discriminator = discriminator;
}
public Boolean getAdmin() {
return admin;
}
public void setAdmin(Boolean admin) {
this.admin = admin;
}
/*
public List<PairIntBoolFacade> getChildren() {
if (children == null) {
children = new ArrayList<PairIntBoolFacade>();
}
return children;
}
public void setChildren(List<PairIntBoolFacade> children) {
this.children = children;
}
public List<Integer> getPlantcomponents() {
if (plantcomponents == null) {
plantcomponents = new ArrayList<Integer>();
}
return plantcomponents;
}
public void setPlantcomponents(List<Integer> plantcomponents) {
this.plantcomponents = plantcomponents;
}
*/
public int getPropertyCount() {
return 4;
}
public Object getProperty(int __index) {
switch(__index) {
case 0: return id;
case 1: return name;
case 2: return discriminator;
case 3: return admin;
//case 4: return children;
//case 5: return plantcomponents;
}
return null;
}
public void setProperty(int __index, Object value) {
switch(__index) {
case 0: id = Integer.parseInt(value.toString()); break;
case 1: name = value.toString(); break;
case 2: discriminator = value.toString(); break;
case 3: admin = Boolean.parseBoolean(value.toString()); break;
//case 4: children = (List) __obj; break;
//case 5: plantcomponents = (List) __obj; break;
}
}
public void getPropertyInfo(int __index, Hashtable __table, PropertyInfo __info) {
switch(__index) {
case 0:
__info.name = "id";
__info.type = Integer.class; break;
case 1:
__info.name = "name";
__info.type = String.class; break;
case 2:
__info.name = "discriminator";
__info.type = String.class; break;
case 3:
__info.name = "admin";
__info.type = Boolean.class; break;
/*
case 4:
__info.name = "children";
__info.type = PropertyInfo.VECTOR_CLASS;
case 5:
__info.name = "plantcomponents";
__info.type = PropertyInfo.VECTOR_CLASS;
*/
}
}
}
Here is my webservice call:
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// For testing I only want to have 3 results
request.addProperty("limit", "3");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
// add mapping
// ResponsiblepartyGetResponse got namespace in XML
envelope.addMapping(NAMESPACE, "ResponsiblepartyGetResponse", new ResponsiblepartyGetResponse().getClass());
// ResponsiblePartyFacades doesn't have namespace. I also tried to add namespace, but same result
envelope.addMapping("", "ResponsiblePartyFacades", new ResponsiblePartyFacade().getClass());
ResponsiblepartyGetResponse result = new ResponsiblepartyGetResponse();
try {
AuthTransportSE androidHttpTransport = new AuthTransportSE(URL, USERNAME, PASSWORD);
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);
// this shows me my result as a string, see above
System.out.println(envelope.bodyIn.toString());
// Trying to case the response -> Exception
result = (ResponsiblepartyGetResponse) envelope.bodyIn;
} catch (Exception e){
Log.d("SOAPEnvelope", "Error: "+e.toString());
}
return result;
As in some tutorials shown I also tried to parse the response manually. But for this the response has to be casted to "SoapObject" like this
SoapObject response = (SoapObject)envelope.getResponse();
When I do this I get the following exception:
05-11 07:09:56.389: D/SOAPEnvelope(2209): Error: java.lang.ClassCastException: java.util.Vector cannot be cast to org.ksoap2.serialization.SoapObject
05-11 07:09:56.402: D/SOAPEnvelope(2209): java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
Can anybody give me a hint?
After despairing one more day I found a soultion that goes back to "misco" in java.lang.ClassCastException: org.ksoap2.serialization.SoapObject
I don't try to cast the Response anymore, but building the List myself by hand:
androidHttpTransport.call(SOAP_ACTION, envelope);
ArrayList<ResponsiblePartyFacades> returnlist = new ArrayList<ResponsiblePartyFacades>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
ResponsiblePartyFacades rp = new ResponsiblePartyFacades();
rp.setId(Integer.parseInt(cs.getProperty(0).toString()));
rp.setName(cs.getProperty(1).toString());
rp.setDiscriminator(cs.getProperty(2).toString());
rp.setAdmin(Boolean.parseBoolean(cs.getProperty(3).toString()));
Log.d("WS", "ID = "+rp.getId() +" name = "+rp.getName()+" disc = "+rp.getDiscriminator()+" admin = "+rp.getAdmin().toString() );
returnlist.add(rp);
}
}
here is my solution. It works for me. Instead of using Vector, get the value of SoapObject response.
SoapObject response = (SoapObject) envelope.getResponse();
int count = response.getPropertyCount();
Log.i("count", Integer.toString(count));
for (int i = 0; i < count; i++) {
int id = Integer.parseInt(response
.getPropertyAsString("id"));
Log.i("id", Integer.toString(id));
String name = (response.getPropertyAsString("name"));
Log.i("name", name);
String discriminator = (response
.getPropertyAsString("discriminator"));
Log.i("discriminator", discriminator);
//add this value to List
}
public ArrayList<CadernetaTO> buscarTodasAsCadernetas() {
ArrayList<CadernetaTO> lista = new ArrayList<CadernetaTO>();
SoapObject buscarTodasAsCadernetas = new SoapObject(NAMESPACE, BUSCAR_TODOS);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(buscarTodasAsCadernetas);
envelope.implicitTypes = true;
HttpTransportSE http = new HttpTransportSE(URL);
try {
http.call(URL + "/" + BUSCAR_TODOS,envelope);
Vector<SoapObject> resposta = (Vector<SoapObject>) envelope.getResponse();
Log.i("entrou no Vector", "Vector");
for (SoapObject soapObject : resposta) {
Log.i("entrou no for", "msg");
CadernetaTO cadern = new CadernetaTO();
Log.i("entrou no to", "CadernetaTO");
cadern.setIdCaderneta(Integer.parseInt(soapObject.getProperty("idCaderneta").toString()));
Log.i("ggigfjjg", "passou linha 1");
cadern.setDose(soapObject.getProperty("dose").toString());
Log.i("ggigfjjg", "passou linha 2");
cadern.setLote(soapObject.getProperty("lote").toString());
Log.i("ggigfjjg", "passou linha 3");
cadern.setData_aplicacao(soapObject.getProperty("data_aplicacao").toString());
Log.i("ggigfjjg", "passou linha 4");
cadern.setSituacao(soapObject.getProperty("situacao").toString());
Log.i("ggigfjjg", "passou linha 5");
cadern.setFkCrianca_idCrianca(Integer.parseInt(soapObject.getProperty("fkCrianca_idCrianca").toString()));
Log.i("ggigfjjg", "passou linha 6");
cadern.setFkVacina_idVacina(Integer.parseInt(soapObject.getProperty("fkVacina_idVacina").toString()));
Log.i("ggigfjjg", "passou linha 7");
lista.add(cadern);
Log.i("testando", cadern.getSituacao() + cadern.getDose() + cadern.getIdCaderneta());
//http.getServiceConnection().setRequestProperty("Connection", "close");
System.setProperty("http.keepAlive", "false");
}
So, I am a newbie in mobile development and interoperability. I am developing a Android application that comunnicates send a Contact object to a remove server that is running a .NET Web Service (via kSOAP). But there is a 500 error in the server and I really don't know how to map it because it is running remotely and my host plan doesn't allow me to debug remotely. I believe it is an error in the interpretation of the Java object in the ASP.NET Web Service, I don't know if it is necessary to deserialize the object and how to do it. I hope that a more experienced developer could help me. I already used primitive objects (string, int and others) and it worked like a charm but I really prefer to work with my models.
The Android Application - Call of the Web Service:
public int webServiceMethodRegisterUser(String... paramss)
{
String resultData;
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
Contact c = new Contact(paramss[0], paramss[1]);
c._email = paramss[0];
c._password = paramss[1];
c._cellphonesim = paramss[2];
c._simoperator = paramss[3];
PropertyInfo pi = new PropertyInfo();
pi.setName("contact");
pi.setValue(c);
pi.setType(c.getClass());
request.addProperty(pi);
//request.addProperty("useremail", paramss[0]);
//request.addProperty("userpass", paramss[1]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
envelope.addMapping(NAMESPACE, "Contact" , new Contact().getClass());
//Marshal floatMarshal = new Marshal();
//floatMarshal.register(envelope);
//Marshal oi = new ();
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
Object result=(Object)envelope.getResponse();
//To get the data.
resultData= result.toString();
publishProgress(resultData);
return Integer.parseInt(resultData);
} catch (Exception e) {
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
throw new RuntimeException(e1.toString());
}
throw new RuntimeException(e.toString());
}
}
Custom Object in Java
package com.example.ivi;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.MarshalDate;
import org.ksoap2.serialization.PropertyInfo;
public class Contact implements KvmSerializable {
// private variables
int _id;
String _email;
String _password;
String _simoperator;
String _cellphonesim;
String _sn_facebook;
String _sn_linkedin;
String _sn_googleplus;
String _sn_orkut;
String _sn_twitter;
Date _last_refresh;
Date _register_date;
public Contact(int id, String email, String password, String simoperator,
String cellphonesim, String facebook, String linkedin,
String googleplus, String orkut, String twitter, Date refreshuser,
Date userregister) {
_id = id;
_email = email;
_password = password;
_simoperator = simoperator;
_cellphonesim = cellphonesim;
_sn_facebook = facebook;
_sn_linkedin = linkedin;
_sn_googleplus = googleplus;
_sn_orkut = orkut;
_sn_twitter = twitter;
_last_refresh = refreshuser;
_register_date = userregister;
}
public Contact() {
}
// constructor
public Contact(int id, String email, String password) {
this._id = id;
this._email = email;
this._password = password;
}
// constructor
public Contact(String email, String password) {
this._email = email;
this._password = password;
}
#Override
public Object getProperty(int arg0) {
switch (arg0) {
case 0:
return _id;
case 1:
return _email;
case 2:
return _password;
case 3:
return _simoperator;
case 4:
return _cellphonesim;
case 5:
return _sn_facebook;
case 6:
return _sn_linkedin;
case 7:
return _sn_googleplus;
case 8:
return _sn_orkut;
case 9:
return _sn_twitter;
case 10:
return _last_refresh;
case 11:
return _register_date;
}
return null;
}
#Override
public int getPropertyCount() {
// TODO Auto-generated method stub
return 12;
}
#Override
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
switch (index) {
case 0:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "UserId";
break;
case 1:
info.type = PropertyInfo.STRING_CLASS;
info.name = "UserEmail";
break;
case 2:
info.type = PropertyInfo.STRING_CLASS;
info.name = "UserPassword";
break;
case 3:
info.type = PropertyInfo.STRING_CLASS;
info.name = "UserSimOperator";
break;
case 4:
info.type = PropertyInfo.STRING_CLASS;
info.name = "UserCellPhoneSim";
break;
case 5:
info.type = PropertyInfo.STRING_CLASS;
info.name = "UserFacebook";
break;
case 6:
info.type = PropertyInfo.STRING_CLASS;
info.name = "UserLinkedin";
break;
case 7:
info.type = PropertyInfo.STRING_CLASS;
info.name = "UserGoogleplus";
break;
case 8:
info.type = PropertyInfo.STRING_CLASS;
info.name = "UserOrkut";
break;
case 9:
info.type = PropertyInfo.STRING_CLASS;
info.name = "UserTwitter";
break;
case 10:
info.type = MarshalDate.DATE_CLASS;
;
info.name = "UserLastRefresh";
break;
case 11:
info.type = MarshalDate.DATE_CLASS;
;
info.name = "UserRegisterDate";
break;
}
}
#Override
public void setProperty(int index, Object value) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
switch (index) {
case 0:
_id = Integer.parseInt(value.toString());
break;
case 1:
_email = value.toString();
break;
case 2:
_password = value.toString();
break;
case 3:
_simoperator = value.toString();
break;
case 4:
_cellphonesim = value.toString();
break;
case 5:
_sn_facebook = value.toString();
break;
case 6:
_sn_linkedin = value.toString();
break;
case 7:
_sn_googleplus = value.toString();
break;
case 8:
_sn_orkut = value.toString();
break;
case 9:
_sn_twitter = value.toString();
break;
case 10:
try {
_last_refresh = formatter.parse(value.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 11:
try {
_register_date = formatter.parse(value.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
. NET Web Service
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
namespace WebServiceIvi
{
[WebService(Namespace = "http://www.ividomain.somee.com/Service1")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public int registerUser(Contact contato)
{
string connString = CONNECTION_STRING;
SqlConnection con = new SqlConnection(connString);
SqlCommand cmdSQL = con.CreateCommand();
try
{
con.Open();
cmdSQL.CommandText = String.Format("INSERT INTO [databaseivi].[dbo].[UsersIvi] ([Useremail],[Userpass],[Userxml],[Usersince]) VALUES('{0}','{1}',null ,getDate())", contato.UserEmail, contato.UserPassword);
int result = cmdSQL.ExecuteNonQuery();
con.Close();
return result;
}
catch (SqlException e)
{
foreach (SqlError error in e.Errors)
{
return error.Number;
}
return 0;
}
}
}
}
The Custom Object in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebServiceIvi
{
public class Contact
{
public Contact(int id, String email, String password, String simoperator, String cellphonesim, String facebook, String linkedin, String googleplus, String orkut, String twitter, DateTime refreshuser, DateTime userregister )
{
_id = id;
_email = email;
_password = password;
_simoperator = simoperator;
_cellphonesim = cellphonesim;
_sn_facebook = facebook;
_sn_linkedin = linkedin;
_sn_googleplus = googleplus;
_sn_orkut = orkut;
_sn_twitter = twitter;
_last_refresh = refreshuser;
_register_date = userregister;
}
public Contact()
{
}
int _id;
String _email;
String _password;
String _simoperator;
String _cellphonesim;
String _sn_facebook;
String _sn_linkedin;
String _sn_googleplus;
String _sn_orkut;
String _sn_twitter;
DateTime _last_refresh;
DateTime _register_date;
public int UserId
{
set { _id = value; }
get
{
if (_id <= 0) return _id;
else return 0;
}
}
public string UserEmail
{
set { _email = value; }
get
{
if (_email != null) return _email.ToString();
else return string.Empty;
}
}
public string UserPassword
{
set { _password = value; }
get
{
if (_password != null) return _password.ToString();
else return string.Empty;
}
}
public string UserSimOperator
{
set { _simoperator = value; }
get
{
if (_simoperator != null) return _simoperator.ToString();
else return string.Empty;
}
}
public string UserCellPhoneSim
{
set { _cellphonesim = value; }
get
{
if (_cellphonesim != null) return _cellphonesim.ToString();
else return string.Empty;
}
}
public string UserFacebook
{
set { _sn_facebook = value; }
get
{
if (_sn_facebook != null) return _sn_facebook.ToString();
else return string.Empty;
}
}
public string UserLinkedin
{
set { _sn_linkedin = value; }
get
{
if (_sn_linkedin != null) return _sn_linkedin.ToString();
else return string.Empty;
}
}
public string UserGoogleplus
{
set { _sn_googleplus = value; }
get
{
if (_sn_googleplus != null) return _sn_googleplus.ToString();
else return string.Empty;
}
}
public string UserOrkut
{
set { _sn_orkut = value; }
get
{
if (_sn_orkut != null) return _sn_orkut.ToString();
else return string.Empty;
}
}
public string UserTwitter
{
set { _sn_twitter = value; }
get
{
if (_sn_twitter != null) return _sn_twitter.ToString();
else return string.Empty;
}
}
public DateTime UserLastRefresh
{
set { _last_refresh = value; }
get
{
if (_last_refresh != null) return DateTime.Parse(_last_refresh.ToString());
else return DateTime.MinValue;
}
}
public DateTime UserRegisterDate
{
set { _register_date = value; }
get
{
if (_register_date != null) return DateTime.Parse(_register_date.ToString());
else return DateTime.MinValue;
}
}
}
}
The SOAP Request XML:
POST /Service1.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://www.ividomain.somee.com/Service1/registerUser"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<registerUser xmlns="http://www.ividomain.somee.com/Service1">
<contato>
<UserId>int</UserId>
<UserEmail>string</UserEmail>
<UserPassword>string</UserPassword>
<UserSimOperator>string</UserSimOperator>
<UserCellPhoneSim>string</UserCellPhoneSim>
<UserFacebook>string</UserFacebook>
<UserLinkedin>string</UserLinkedin>
<UserGoogleplus>string</UserGoogleplus>
<UserOrkut>string</UserOrkut>
<UserTwitter>string</UserTwitter>
<UserLastRefresh>dateTime</UserLastRefresh>
<UserRegisterDate>dateTime</UserRegisterDate>
</contato>
</registerUser>
</soap:Body>
</soap:Envelope>
I've been stuck in this for a while and didn't found any implementation and deserialization of a java model in .NET. I hope someone out there helps me! =D
ThiagoMello, I had this error days ago and solve it generting java class from this site:
http://www.wsdl2code.com/Pages/Home.aspx
With this classes my code works fine! Try it.
Hope this helps.
Joan.
I have a listview, when i click on any item in listview a detailed activity will open.This layout has many widgets like textview, ImageView, share buttons etc. Now I want to slide this detail activity of the item to show the detail view of next item in the list. I am following this http://misha.beshkin.lv/android-swipe-gesture-implementation/ but when i swipe from left to right next view is not displaying just getting a toast message "swipe right". Can any one direct me how to work on this? i am new to android Answers will be appreciated. Following is the code i have used
MainActivity.java(listview page)
public class MainActivity extends ListActivity {
ArrayList<HashMap<String, String>> songsList;
ListView list;
LazyAdapter adapter;
JSONArray posts;
// All static variables
static final String URL = "http://siteurl/posts/pages";
static final String KEY_URL_FOR_MAP = "url_site";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_SITEURL = "url";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String siteurl = c.getString(KEY_SITEURL);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_URL_FOR_MAP, siteurl);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
final ListView list=(ListView)findViewById(android.R.id.list);
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent(MainActivity.this, SampleDesp.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_URL_FOR_MAP, map.get(KEY_URL_FOR_MAP));
in.putExtra(KEY_DATE, map.get(KEY_DATE));
in.putExtra(KEY_NAME, map.get(KEY_NAME));
in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
in.putExtra(KEY_URL, map.get(KEY_URL));
startActivity(in);
}
});
}
}
SampleDesp.java(detailed Activity)
public class SampleDesp extends Activity implements SimpleGestureListener {
private SimpleGestureFilter detector;
static String title;
String content;
// Your Facebook APP ID
private static String APP_ID = "308180782571605"; // Replace with your App ID
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
Button btnFbLogin;
Button btnPostToWall;
// JSON node keys
static final String KEY_URL_FOR_MAP = "url_site";
private static final String KEY_TITLE = "title";
private static final String KEY_SITEURL = "url";
private static final String KEY_DATE = "date";
private static final String KEY_NAME = "name";
private static final String KEY_CONTENT = "content";
private static final String KEY_URL = "url";
static final String KEY_SLUG1= "slug";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sampledes);
detector = new SimpleGestureFilter(this,this);
final LinearLayout line1 = (LinearLayout)findViewById(R.id.ll1);
LinearLayout line2 = (LinearLayout)findViewById(R.id.ll2);
Button btnShare = (Button)findViewById(R.id.share);
btnShare.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
line1.setVisibility(View.VISIBLE);
}
});
// getting intent data
Intent in = getIntent();
final String url1 = in.getStringExtra(KEY_URL);
ImageView imgv = (ImageView) findViewById(R.id.imgdesc);
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
imageLoader.DisplayImage(url1, imgv);
// Get JSON values from previous intent
final String title = in.getStringExtra(KEY_TITLE);
final String siteurl = in.getStringExtra(KEY_URL_FOR_MAP);
String date = in.getStringExtra(KEY_DATE);
String name = in.getStringExtra(KEY_NAME);
final String content = in.getStringExtra(KEY_CONTENT);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblUrl = (TextView) findViewById(R.id.url_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
TextView lblCont = (TextView) findViewById(R.id.content_label);
lblName.setText(title);
lblUrl.setText(siteurl);
lblCost.setText(date);
lblDesc.setText(name);
lblCont.setText(content);
final ImageView email3 = (ImageView) findViewById(R.id.email);
email3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//my codes
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:?subject=" + title + "&body=" + content);
intent.setData(data);
startActivity(intent);
}
});
final ImageView sms4 = (ImageView) findViewById(R.id.sms);
sms4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
// Perform action on click
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setData(Uri.parse(Uri.encode(title)+Uri.encode(content)));
shareIntent.setType("text/*");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, content);
startActivity(shareIntent);
}
});
final ImageView twitter4 = (ImageView) findViewById(R.id.twitter);
twitter4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
// Perform action on click
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://twitter.com/?status=" + Uri.encode(title) + "" + Uri.encode(siteurl)));
startActivity(i);
}
});
Button btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
if (facebook.isSessionValid()) {
postToWall();
}
}
});
}
#Override
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
public void onSwipe(int direction) {
String str = "";
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
break;
case SimpleGestureFilter.SWIPE_DOWN : str = "Swipe Down";
break;
case SimpleGestureFilter.SWIPE_UP : str = "Swipe Up";
break;
}
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public void onDoubleTap() {
Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
}
/**
* Function to login into facebook
* */
private void loginToFacebook() {
// TODO Auto-generated method stub
{
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}else{}
}
}
/**
* Function to post to facebook wall
* */
public void postToWall() {
Bundle parameters = new Bundle();
parameters.putString("title", "visit us");
parameters.putString("link", "http://india.dollardesi.net/ads/metro-logistic-packers-movers/");
// post on user's wall.
facebook.dialog(this, "feed",parameters, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
/**
* Function to Logout user from Facebook
* */
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);
}
});
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
}
SimpleGestureFilter.java
public class SimpleGestureFilter extends SimpleOnGestureListener{
public final static int SWIPE_UP = 1;
public final static int SWIPE_DOWN = 2;
public final static int SWIPE_LEFT = 3;
public final static int SWIPE_RIGHT = 4;
public final static int MODE_TRANSPARENT = 0;
public final static int MODE_SOLID = 1;
public final static int MODE_DYNAMIC = 2;
private final static int ACTION_FAKE = -13; //just an unlikely number
private int swipe_Min_Distance = 100;
private int swipe_Max_Distance = 350;
private int swipe_Min_Velocity = 100;
private int mode = MODE_DYNAMIC;
private boolean running = true;
private boolean tapIndicator = false;
private Activity context;
private GestureDetector detector;
private SimpleGestureListener listener;
public SimpleGestureFilter(Activity context,SimpleGestureListener sgl) {
this.context = context;
this.detector = new GestureDetector(context, this);
this.listener = sgl;
}
public void onTouchEvent(MotionEvent event){
if(!this.running)
return;
boolean result = this.detector.onTouchEvent(event);
if(this.mode == MODE_SOLID)
event.setAction(MotionEvent.ACTION_CANCEL);
else if (this.mode == MODE_DYNAMIC) {
if(event.getAction() == ACTION_FAKE)
event.setAction(MotionEvent.ACTION_UP);
else if (result)
event.setAction(MotionEvent.ACTION_CANCEL);
else if(this.tapIndicator){
event.setAction(MotionEvent.ACTION_DOWN);
this.tapIndicator = false;
}
}
//else just do nothing, it's Transparent
}
public void setMode(int m){
this.mode = m;
}
public int getMode(){
return this.mode;
}
public void setEnabled(boolean status){
this.running = status;
}
public void setSwipeMaxDistance(int distance){
this.swipe_Max_Distance = distance;
}
public void setSwipeMinDistance(int distance){
this.swipe_Min_Distance = distance;
}
public void setSwipeMinVelocity(int distance){
this.swipe_Min_Velocity = distance;
}
public int getSwipeMaxDistance(){
return this.swipe_Max_Distance;
}
public int getSwipeMinDistance(){
return this.swipe_Min_Distance;
}
public int getSwipeMinVelocity(){
return this.swipe_Min_Velocity;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
final float xDistance = Math.abs(e1.getX() - e2.getX());
final float yDistance = Math.abs(e1.getY() - e2.getY());
if(xDistance > this.swipe_Max_Distance || yDistance > this.swipe_Max_Distance)
return false;
velocityX = Math.abs(velocityX);
velocityY = Math.abs(velocityY);
boolean result = false;
if(velocityX > this.swipe_Min_Velocity && xDistance > this.swipe_Min_Distance){
if(e1.getX() > e2.getX()) // right to left
this.listener.onSwipe(SWIPE_LEFT);
else
this.listener.onSwipe(SWIPE_RIGHT);
result = true;
}
else if(velocityY > this.swipe_Min_Velocity && yDistance > this.swipe_Min_Distance){
if(e1.getY() > e2.getY()) // bottom to up
this.listener.onSwipe(SWIPE_UP);
else
this.listener.onSwipe(SWIPE_DOWN);
result = true;
}
return result;
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
this.tapIndicator = true;
return false;
}
#Override
public boolean onDoubleTap(MotionEvent arg0) {
this.listener.onDoubleTap();;
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent arg0) {
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent arg0) {
if(this.mode == MODE_DYNAMIC){ // we owe an ACTION_UP, so we fake an
arg0.setAction(ACTION_FAKE); //action which will be converted to an ACTION_UP later.
this.context.dispatchTouchEvent(arg0);
}
return false;
}
static interface SimpleGestureListener{
void onSwipe(int direction);
void onDoubleTap();
}
}
I think that it may work:
//code from your onItemClick
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent(MainActivity.this, SampleDesp.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_URL_FOR_MAP, map.get(KEY_URL_FOR_MAP));
in.putExtra(KEY_DATE, map.get(KEY_DATE));
in.putExtra(KEY_NAME, map.get(KEY_NAME));
in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
in.putExtra(KEY_URL, map.get(KEY_URL));
in.putExtra(LIST_POSITION, position); //passing incremented position
startActivity(in);
And then in your details Activity you will have position of current item of the list that details are displayed on the screen. So now you can increment position, and use the same code (the above one) in your onSwipe(int direction) method. So if you want to open next item details on your left swipe you do something like this:
public void onSwipe(int direction) {
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT :
break;
case SimpleGestureFilter.SWIPE_LEFT :
Intent in = getIntent();
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_URL_FOR_MAP, map.get(KEY_URL_FOR_MAP));
in.putExtra(KEY_DATE, map.get(KEY_DATE));
in.putExtra(KEY_NAME, map.get(KEY_NAME));
in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
in.putExtra(KEY_URL, map.get(KEY_URL));
in.putExtra(LIST_POSITION, position); //passing clicked position
finish();
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_DOWN :
break;
case SimpleGestureFilter.SWIPE_UP :
break;
}
}
But for this code in SWIPE_LEFT when your adding Extras to your intent, you need access to a HashMap from your MainActivity, so you can add a public static method in your MainActivity like:
public static String getSongFromHashMap(String key) {
return songsList.get(key);
}
And use this method in SWIPE_LEFT code. I know it's not best solution but it should work :)
change
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
break;
to
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
//Fire intent to your detail activity here
break;
I hope I am closer to your solution.
I am getting a "casting" error on a property of complex object that is sent to a .NET web service using KSOAP2 from an Android device. The property is an array of complex objects. The documentation on the internet has helped me send and receive simple data types (strings, ints, dates, etc). I can even read an array of complex objects from a .NET web service. I just cannot send back an array of complex objects to the web service. Please help. Here is what I have:
Environment:
Client = Android Development using the latest KSOAP lib for communication.
Server = .NET Web Service (Visual Studio 2008). Note: this is NOT WCF.
.NET Web Service:
[SoapRpcMethod(), WebMethod]
public void WriteCaseInfo(CaseInformation caseInfo)
{
...
...
}
ANDROID CLIENT CODE:
Parent Class Sent as Complex Parameter:
public class CaseInformation extends IABaseKSoap2Serializable
{
public String Name;
public int Id;
public Vector<MultiPartDataElement> SiteListItems = new Vector<MultiPartDataElement>();
#Override
public Object getProperty(int arg0)
{
switch(arg0)
{
case 0:
return Name;
case 1:
return Id;
case 2:
return SiteListItems;
}
return null;
}
#Override
public int getPropertyCount()
{
return 3;
}
#Override
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info)
{
switch(index)
{
case 0:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Name";
break;
case 1:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "Id";
break;
case 2:
info.type = new Vector<MultiPartDataElement>().getClass();
info.name = "SiteListItems";
break;
default:break;
}
}
#Override
public void setProperty(int index, Object value)
{
switch(index)
{
case 0:
Name = value.toString();
break;
case 1:
Id = Integer.parseInt(value.toString());
break;
case 2:
SiteListItems = (Vector<MultiPartDataElement>)value;
break;
default:
break;
}
}
}
Note: If I remove the SiteListItems property from the client code and the web service, everything works.
Complex Class used in Array within the above object:
public class MultiPartDataElement extends IABaseKSoap2Serializable
{
public int Id;
public String Name;
// default constructor
public MultiPartDataElement()
{
}
// overloaded constructor
public MultiPartDataElement(int id, String name)
{
Id = id;
Name = name;
}
#Override
public Object getProperty(int arg0)
{
switch(arg0)
{
case 0:
return Id;
case 1:
return Name;
}
return null;
}
#Override
public int getPropertyCount()
{
return 2;
}
#Override
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info)
{
switch(index)
{
case 0:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "Id";
break;
case 1:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Name";
break;
default:break;
}
}
#Override
public void setProperty(int index, Object value)
{
switch(index)
{
case 0:
Id = Integer.parseInt(value.toString());
break;
case 1:
Name = value.toString();
break;
default:
break;
}
}
}
Code to Send object as a Parameter to the .Net Web Service:
public static boolean WriteCaseInfo()
{
boolean status = false;
CaseInformation caseInfo = new CaseInformation();
caseInfo.Id = 2725;
caseInfo.Name = "Craig M. Buck";
caseInfo.SiteListItems = new Vector<MultiPartDataElement>();
caseInfo.SiteListItems.add(new MultiPartDataElement(1, "CMB1"));
caseInfo.SiteListItems.add(new MultiPartDataElement(2, "CMB2"));
String methodName = "WriteCaseInfo";
SoapObject request = new SoapObject(NAMESPACE, methodName);
request.addProperty("caseInfo", caseInfo);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = request;
envelope.dotNet = false;
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
envelope.addMapping(IABaseKSoap2Serializable.NAMESPACE, "MultiPartDataElement", new MultiPartDataElement().getClass());
envelope.addMapping(IABaseKSoap2Serializable.NAMESPACE, "CaseInformation", new CaseInformation().getClass());
HttpTransportSE transport = new HttpTransportSE(WebAPIURL + CaseServicesURL);
transport.debug = true;
transport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
try
{
List<HeaderProperty> headers = BuildHeader();
transport.call(NAMESPACE + methodName, envelope, headers);
String requestDump = transport.requestDump;
String soapDump = transport.responseDump;
SoapObject response = (SoapObject) envelope.bodyIn;
if(response != null)
status = new Boolean(response.getProperty(0).toString());
}
catch(Exception e)
{
status = false;
}
return status;
}
Request Dump from KSOAP:
<?xml version="1.0" encoding="utf-8"?><v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/"><v:Header /><v:Body><n0:WriteCaseInfo id="o0" c:root="1" xmlns:n0="http://www.medical.draeger.com/webservices/"><caseInfo i:type="n1:CaseInformation" xmlns:n1="http://www.medical.draeger.com/webservices/encodedTypes"><Name i:type="d:string">Craig M. Buck</Name><Id i:type="d:int">2725</Id><SiteListItems i:type="c:Array" c:arrayType="d:anyType[2]"><item i:type="n1:MultiPartDataElement"><Id i:type="d:int">1</Id><Name i:type="d:string">CMB1</Name></item><item i:type="n1:MultiPartDataElement"><Id i:type="d:int">2</Id><Name i:type="d:string">CMB2</Name></item></SiteListItems></caseInfo></n0:WriteCaseInfo></v:Body></v:Envelope>
Note: What I think the issue is, is that the array is defined as "anyTyp" and not MultiPartDataElement -> ... the question is what am I doing wrong here??
Response Dump from KSOAP (After Call):
SoapException: Server was unable to read request. ---> System.InvalidOperationException: There is an error in XML document (1, 828). ---> System.InvalidCastException: Cannot assign object of type System.Object[] to an object of type Draeger.IT.Platform.Web.WebServices.MultiPartDataElement[]
I've had similar problem. You might want to try my personal solution.
http://www.codeproject.com/Tips/222578/Android-access-to-NET-Web-Service-with-object-as-p
You could do this:
int propertyCount = countryDetails.getPropertyCount();
ArrayList list = new ArrayList(propertyCount);
lv_arr = new String[propertyCount];
for (int i = 0; i < propertyCount; i++) {
Object property = countryDetails.getProperty(i);
if (property instanceof SoapObject) {
SoapObject countryObj = (SoapObject) property;
String countryName = countryObj.getProperty("countryName").toString();
list.add(countryName);
}
}
from : Parsing ksoap2 response