ksoap2 android web services complextype byte[] - java
I have a web service that receives an object of complexType Pic,
Pic.java
public class Pic implements KvmSerializable{
private double latitude;
private double longitude;
private long time;
private double accuracy;
private String name;
private byte[] imageInByte;
public byte[] getImageInByte() {
return imageInByte;
}
public void setImageInByte(byte[] imageInByte) {
this.imageInByte = imageInByte;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getAccuracy() {
return accuracy;
}
public void setAccuracy(double accuracy) {
this.accuracy = accuracy;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
#Override
public Object getProperty(int arg0) {
switch(arg0){
case 0:
return latitude;
case 1:
return longitude;
case 2:
return time;
case 3:
return accuracy;
case 4:
return name;
case 5:
return imageInByte;
}
return null;
}
#Override
public int getPropertyCount() {
return 6;
}
#Override
public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2) {
switch(arg0){
case 0:
arg2.type = PropertyInfo.STRING_CLASS;
arg2.name = "latitude";
break;
case 1:
arg2.type = PropertyInfo.STRING_CLASS;
arg2.name = "longitude";
break;
case 2:
arg2.type = PropertyInfo.LONG_CLASS;
arg2.name = "time";
break;
case 3:
arg2.type = Double.class;
arg2.name = "accuracy";
break;
case 4:
arg2.type = PropertyInfo.STRING_CLASS;
arg2.name = "name";
break;
case 5:
arg2.type = MarshalBase64.BYTE_ARRAY_CLASS;
arg2.name = "imageInBytes";
default:
break;
}
}
#Override
public void setProperty(int arg0, Object arg1) {
// TODO Auto-generated method stub
switch(arg0){
case 0:
latitude = Double.parseDouble(arg1.toString());
break;
case 1:
longitude = Double.parseDouble(arg1.toString());
break;
case 2:
time = Long.parseLong(arg1.toString());
break;
case 3:
accuracy = Double.parseDouble(arg1.toString());
break;
case 4:
name = arg1.toString();
break;
case 5:
imageInByte = Base64.decode(arg1.toString(), Base64.DEFAULT);
break;
default:
break;
}
}
}
I send it to a webservice by registering in the envelope doubles and marshalBase64. So far everything runs smoothly although in the web service once i get the object the method picture.imageInByte() returns null. I am not sure of what is happening because i could pass just a byte[] variable like this and write the file to disk. But i only passed a byte[] not a complex object with a byte[] inside.
What is the problem?
The way i solved was by altering the web service to receive 2 parameters instead of one.
like this:
public void receivePicture(Pic picture, byte[] image){
}
where picture is the information i need about the image itself and image is the actual image file.
I know this is somehow a hack and not exactly the good solution i was looking for but it works.
Related
Firebase : Data not stored in the correct format
Please understand my scenario before marking it as a duplicate. I've searched for a while but didn't find the answer on the site. I am sending data to Firebase through a fragment using setValue(Modelclass object) but the data is not stored in the format as it was supposed to be. Fragment.java public class FragmentSelectRoute extends Fragment { RadioGroup radioGroup; private int routeId; private String routeTitle; Button btnFinish; // Firebase FirebaseDatabase database; DatabaseReference studentRef; // FirebaseAUth FirebaseAuth firebaseAuth = FirebaseAuth.getInstance(); public FragmentSelectRoute() { // Required empty public constructor } #Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_select_route, container, false); database = FirebaseDatabase.getInstance(); studentRef = database.getReference(Common.STUDENT_REFERENCE); radioGroup = view.findViewById(R.id.radio_select_route); btnFinish = view.findViewById(R.id.btn_finish); Bundle bundle = this.getArguments(); String firstName = bundle.getString("firstName"); String lastName = bundle.getString("lastName"); String regNo = bundle.getString("regNo"); String gender = bundle.getString("gender"); String campus = bundle.getString("campus"); String dept = bundle.getString("dept"); String program = bundle.getString("program"); String semester = bundle.getString("semester"); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { #Override public void onCheckedChanged(RadioGroup radioGroup, int i) { switch (i) { case R.id.rdbtn_route_one: routeId = 1; routeTitle = "Lari Adda"; break; case R.id.rdbtn_route_two: routeId = 2; routeTitle = "Rehman Plaza"; break; case R.id.rdbtn_route_three: routeId = 3; routeTitle = "Aziz Bhatti Town"; break; case R.id.rdbtn_route_four: routeId = 4; routeTitle = "Gill Wala"; break; case R.id.rdbtn_route_five: routeId = 5; routeTitle = "Mela Mandi Ground"; break; case R.id.rdbtn_route_six: routeId = 6; routeTitle = "Bhera"; break; case R.id.rdbtn_route_seven: routeId = 7; routeTitle = "Jahurabad"; break; case R.id.rdbtn_route_eight: routeId = 8; routeTitle = "Nihang"; break; case R.id.rdbtn_route_nine: routeId = 9; routeTitle = "Farooka"; break; case R.id.rdbtn_route_ten: routeId = 10; routeTitle = "Silanwali"; break; case R.id.rdbtn_route_eleven: routeId = 11; routeTitle = "Chiniot"; break; case R.id.rdbtn_route_twelve: routeId = 12; routeTitle = "Laliyan"; break; case R.id.rdbtn_route_thirteen: routeId = 13; routeTitle = "Kandiwal"; break; case R.id.rdbtn_route_fourteen: routeId = 14; routeTitle = "No Title"; break; case R.id.rdbtn_route_fifteen: routeId = 15; routeTitle = "No Title"; break; case R.id.rdbtn_route_sixteen: routeId = 16; routeTitle = "Alfarid Garden"; break; } } }); btnFinish.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View view) { registerUserToFirebase(firstName, lastName, regNo, gender, campus, dept , program, semester, routeId, routeTitle); } }); return view; } private void registerUserToFirebase(String firstName, String lastName, String regNo, String gender, String campus, String dept, String program, String semester, int routeId, String routeTitle) { StudentModel studentModel = new StudentModel(); studentModel.setFirstName(firstName); studentModel.setLastName(lastName); studentModel.setRegNo(regNo); studentModel.setGender(gender); studentModel.setCampus(campus); studentModel.setDept(dept); studentModel.setProgram(program); studentModel.setSemester(semester); studentModel.setRouteId(routeId); studentModel.setRouteTitle(routeTitle); if (FirebaseAuth.getInstance().getCurrentUser() != null){ studentRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .setValue(studentModel) .addOnFailureListener(new OnFailureListener() { #Override public void onFailure(#NonNull Exception e) { Toast.makeText(getActivity(), "could not send data" + e.getMessage(), Toast.LENGTH_SHORT).show(); } }).addOnSuccessListener(new OnSuccessListener<Void>() { #Override public void onSuccess(Void aVoid) { Toast.makeText(getActivity(), "Registarion Successfull", Toast.LENGTH_SHORT).show(); } }); } else { Toast.makeText(getActivity(), "User is null", Toast.LENGTH_SHORT).show(); } } } StudentModel.java public class StudentModel { private String firstName; private String lastName; private String regNo; private String gender; private String campus; private String dept; private String program; private String semester; public String getRouteTitle() { return routeTitle; } public void setRouteTitle(String routeTitle) { this.routeTitle = routeTitle; } private String routeTitle; private int routeId; public StudentModel() { } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getRegNo() { return regNo; } public void setRegNo(String regNo) { this.regNo = regNo; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getCampus() { return campus; } public void setCampus(String campus) { this.campus = campus; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } public String getProgram() { return program; } public void setProgram(String program) { this.program = program; } public String getSemester() { return semester; } public void setSemester(String semester) { this.semester = semester; } public int getRouteId() { return routeId; } public void setRouteId(int routeId) { this.routeId = routeId; }} Data should be stored as in model class as: UID firstName : lastName : regNo : gender : campus : dept : program : semester : routeTitle : routeId: Rather, it is stored as:
It doesn't matter the order of the fields in your "StudentModel" class, because when you are adding a new instance of the class to the Firebase Realtime Database, all the fields are automatically ordered alphabetically. Besides that, the order of calling the setters on your "studentModel" object, doesn't matter too. The Firebase Console, always orders the fields alphabetically. See, the field starts with the letter "c", the second one with "d", and so on till the end, where the last field starts with "s". Unfortunately, this order cannot be changed in the Firebase Console. If you want, you can change the order in your class to be alphabetical and match the order in the database, that's fine, but it doesn't make any sense in my opinion.
Android calculator app decimal results
I'm Mikamocha, and I just started programming Android apps. I have problems in my first calculator app (the results). What I mean is so that 2+2 will be 4 instead of 4.0, 5-2 will be 3 instead of 3.0, etc. package com.yeshua.mikamocha.myxcalculator; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private EditText Scr; private float NumberBf=0, NumAf, result=0; private String Operation, mod="replace"; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Scr = (EditText) findViewById(R.id.txtScreen); Scr.setText(""); int idList[] = {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn2, R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8, R.id.btn9, R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide, R.id.btnClear,R.id.btnEquals, R.id.btnDot, }; for(int id:idList) { View v = (View) findViewById(id); v.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { onButtonClick(v); } }); } } public void mMath(String str) { mResult(); try { NumberBf = Float.parseFloat(Scr.getText().toString()); Operation = str; }catch (Exception e) { Toast.makeText(getApplicationContext(), (CharSequence) e, Toast.LENGTH_SHORT).show(); Scr.setText("SYNTAX ERROR"); mod = "replace"; } } public void mResult() { NumAf = 0; if(!Scr.getText().toString().trim().isEmpty()) NumAf = Float.parseFloat(Scr.getText().toString()); result = NumAf; try { switch (Operation) { case "+": result = NumAf + NumberBf; break; case "-": result = NumberBf - NumAf; break; case "*": result = NumAf * NumberBf; break; case "/": result = NumberBf / NumAf; break; default: result = NumAf; break; } } catch (Exception e) { e.printStackTrace(); } Scr.setText(String.valueOf(result)); mod = "replace"; } public void getKeyboard(String str) { String ScrTxt = Scr.getText().toString(); ScrTxt += str; if(mod.equals("add")) Scr.setText(ScrTxt); else Scr.setText(str); mod = "add"; } public void onButtonClick(View v) { switch (v.getId()) { case R.id.btnClear: //Clear Scr.setText(""); NumberBf = 0; Operation = ""; break;case R.id.btnAdd: mMath("+"); break; case R.id.btnSubtract: if(mod.equals("replace")) { String numb = ((Button) v).getText().toString(); getKeyboard(numb); } else mMath("-"); break; case R.id.btnMultiply: mMath("*"); break; case R.id.btnDivide: mMath("/"); break; case R.id.btnEquals: mResult(); Operation = ""; NumberBf = 0; break; default: String numb = ((Button) v).getText().toString(); getKeyboard(numb); break; } } } Thanks.
You should use NumberFormat. For example: public static void main(String[] args) { System.out.println(format(14.0184849945)); // prints '14.01' System.out.println(format(13)); // prints '13' System.out.println(format(3.5)); // prints '3.5' System.out.println(format(3.138136)); // prints '3.13' } public static String format(Number n) { NumberFormat format = DecimalFormat.getInstance(); format.setRoundingMode(RoundingMode.FLOOR); format.setMinimumFractionDigits(0); format.setMaximumFractionDigits(2); return format.format(n); }
you are using float datatype for result instead of use int type and parse operation value in int. result = (int)(NumAf + NumberBf);
For Ref. DecimalFormat Change as follows as you are using float as result you are getting decimal so use int, private int result=0; //and result =(int) (NumAf + NumberBf); OR float one= 2.0; float two= 2.5; //DecimalFormat format = new DecimalFormat(); //format.setDecimalSeparatorAlwaysShown(false); DecimalFormat format=new DecimalFormat("#,###.#"); System.out.println( format.format(one) );//prints 2 System.out.println( format.format(two) );//prints 2.5
Error Parsing XML response attributes with ksoap2 returns ClassCastException
I'm trying to figure out how to cast the response of the consume of a webservice, when casting the response envelope.bodyIn to my extended class object "BiometricConfigurationResponse" i'm getting this error: java.lang.ClassCastException: org.ksoap2.serialization.SoapObject cannot be cast to org.tempuri.BiometricConfigurationResponse The service is responding well and if i not cast it i get the dump right. Any ideas? This is what i'm doing: BiometricConfigurationResponse response= null; SoapObject obj = new SoapObject (wsNameSpace, methodName); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.implicitTypes = true; envelope.dotNet = true; envelope.setOutputSoapObject(obj); envelope.addMapping(wsNameSpace, "BiometricConfigurationResponse", new BiometricConfigurationResponse().getClass()); HttpTransportSE androidHttpTransport = new HttpTransportSE(wsURL); androidHttpTransport.debug = true; try { String soapAction=wsNameSpace + methodName; androidHttpTransport.call(soapAction, envelope); System.out.println(androidHttpTransport.requestDump); response = (BiometricConfigurationResponse)envelope.bodyIn; } catch (Exception e) { e.printStackTrace(); } And this is my custom class package org.tempuri; import java.util.Hashtable; import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.SoapObject; public final class BiometricConfigurationResponse extends SoapObject { private int coderAlgorithm; private int templateFormat; private boolean juvenileMode; private int qualityThreshold; private boolean retryAcquisition; private boolean acceptBadQualityEnrollment; private boolean showQualityBar; private boolean showQualityThreshold; private int timeout; private int timeoutQualityCoder; private int enrollSecurityLevel; private boolean securityLevelCompatibility; private boolean liveImage; private java.lang.String setCulture; private int authenticationScore; public BiometricConfigurationResponse() { super("", ""); } public void setCoderAlgorithm(int coderAlgorithm) { this.coderAlgorithm = coderAlgorithm; } public int getCoderAlgorithm(int coderAlgorithm) { return this.coderAlgorithm; } public void setTemplateFormat(int templateFormat) { this.templateFormat = templateFormat; } public int getTemplateFormat(int templateFormat) { return this.templateFormat; } public void setJuvenileMode(boolean juvenileMode) { this.juvenileMode = juvenileMode; } public boolean getJuvenileMode(boolean juvenileMode) { return this.juvenileMode; } public void setQualityThreshold(int qualityThreshold) { this.qualityThreshold = qualityThreshold; } public int getQualityThreshold(int qualityThreshold) { return this.qualityThreshold; } public void setRetryAcquisition(boolean retryAcquisition) { this.retryAcquisition = retryAcquisition; } public boolean getRetryAcquisition(boolean retryAcquisition) { return this.retryAcquisition; } public void setAcceptBadQualityEnrollment(boolean acceptBadQualityEnrollment) { this.acceptBadQualityEnrollment = acceptBadQualityEnrollment; } public boolean getAcceptBadQualityEnrollment(boolean acceptBadQualityEnrollment) { return this.acceptBadQualityEnrollment; } public void setShowQualityBar(boolean showQualityBar) { this.showQualityBar = showQualityBar; } public boolean getShowQualityBar(boolean showQualityBar) { return this.showQualityBar; } public void setShowQualityThreshold(boolean showQualityThreshold) { this.showQualityThreshold = showQualityThreshold; } public boolean getShowQualityThreshold(boolean showQualityThreshold) { return this.showQualityThreshold; } public void setTimeout(int timeout) { this.timeout = timeout; } public int getTimeout(int timeout) { return this.timeout; } public void setTimeoutQualityCoder(int timeoutQualityCoder) { this.timeoutQualityCoder = timeoutQualityCoder; } public int getTimeoutQualityCoder(int timeoutQualityCoder) { return this.timeoutQualityCoder; } public void setEnrollSecurityLevel(int enrollSecurityLevel) { this.enrollSecurityLevel = enrollSecurityLevel; } public int getEnrollSecurityLevel(int enrollSecurityLevel) { return this.enrollSecurityLevel; } public void setSecurityLevelCompatibility(boolean securityLevelCompatibility) { this.securityLevelCompatibility = securityLevelCompatibility; } public boolean getSecurityLevelCompatibility(boolean securityLevelCompatibility) { return this.securityLevelCompatibility; } public void setLiveImage(boolean liveImage) { this.liveImage = liveImage; } public boolean getLiveImage(boolean liveImage) { return this.liveImage; } public void setSetCulture(java.lang.String setCulture) { this.setCulture = setCulture; } public java.lang.String getSetCulture(java.lang.String setCulture) { return this.setCulture; } public void setAuthenticationScore(int authenticationScore) { this.authenticationScore = authenticationScore; } public int getAuthenticationScore(int authenticationScore) { return this.authenticationScore; } public int getPropertyCount() { return 15; } public Object getProperty(int __index) { switch(__index) { case 0: return new Integer(coderAlgorithm); case 1: return new Integer(templateFormat); case 2: return new Boolean(juvenileMode); case 3: return new Integer(qualityThreshold); case 4: return new Boolean(retryAcquisition); case 5: return new Boolean(acceptBadQualityEnrollment); case 6: return new Boolean(showQualityBar); case 7: return new Boolean(showQualityThreshold); case 8: return new Integer(timeout); case 9: return new Integer(timeoutQualityCoder); case 10: return new Integer(enrollSecurityLevel); case 11: return new Boolean(securityLevelCompatibility); case 12: return new Boolean(liveImage); case 13: return setCulture; case 14: return new Integer(authenticationScore); } return null; } public void setProperty(int __index, Object __obj) { switch(__index) { case 0: coderAlgorithm = Integer.parseInt(__obj.toString()); break; case 1: templateFormat = Integer.parseInt(__obj.toString()); break; case 2: juvenileMode = "true".equals(__obj.toString()); break; case 3: qualityThreshold = Integer.parseInt(__obj.toString()); break; case 4: retryAcquisition = "true".equals(__obj.toString()); break; case 5: acceptBadQualityEnrollment = "true".equals(__obj.toString()); break; case 6: showQualityBar = "true".equals(__obj.toString()); break; case 7: showQualityThreshold = "true".equals(__obj.toString()); break; case 8: timeout = Integer.parseInt(__obj.toString()); break; case 9: timeoutQualityCoder = Integer.parseInt(__obj.toString()); break; case 10: enrollSecurityLevel = Integer.parseInt(__obj.toString()); break; case 11: securityLevelCompatibility = "true".equals(__obj.toString()); break; case 12: liveImage = "true".equals(__obj.toString()); break; case 13: setCulture = (java.lang.String) __obj; break; case 14: authenticationScore = Integer.parseInt(__obj.toString()); break; } } public void getPropertyInfo(int __index, Hashtable __table, PropertyInfo __info) { switch(__index) { case 0: __info.name = "coderAlgorithm"; __info.type = Integer.class; break; case 1: __info.name = "templateFormat"; __info.type = Integer.class; break; case 2: __info.name = "juvenileMode"; __info.type = Boolean.class; break; case 3: __info.name = "qualityThreshold"; __info.type = Integer.class; break; case 4: __info.name = "retryAcquisition"; __info.type = Boolean.class; break; case 5: __info.name = "acceptBadQualityEnrollment"; __info.type = Boolean.class; break; case 6: __info.name = "showQualityBar"; __info.type = Boolean.class; break; case 7: __info.name = "showQualityThreshold"; __info.type = Boolean.class; break; case 8: __info.name = "timeout"; __info.type = Integer.class; break; case 9: __info.name = "timeoutQualityCoder"; __info.type = Integer.class; break; case 10: __info.name = "enrollSecurityLevel"; __info.type = Integer.class; break; case 11: __info.name = "securityLevelCompatibility"; __info.type = Boolean.class; break; case 12: __info.name = "liveImage"; __info.type = Boolean.class; break; case 13: __info.name = "setCulture"; __info.type = java.lang.String.class; break; case 14: __info.name = "authenticationScore"; __info.type = Integer.class; break; } } }
After several days of research i understood that WSDL autogenerated code parse Properties but not Atrributes. So what i did was this: First i generate the stub code from my WSDL in this website: http://www.wsdl2code.com/pages/home.aspx My webservice name is "nutriment" son when you call it in MainActivity you have to do this: nutriment nws= new nutriment(); BiometricConfigurationResponse respuesta = nws.GetBiometricConfiguration(); Log.i(TAG, String.valueOf(respuesta.coderAlgorithm)); Log.i(TAG, String.valueOf(respuesta.templateFormat)); But it responses 0 in all cases because the WDSL stub files are parsing PROPERTIES NOT ATRIBUTES, so when you open the serialization generated file you'll got something like this: import org.ksoap2.serialization.KvmSerializable; import org.ksoap2.serialization.PropertyInfo; import java.util.Hashtable; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapPrimitive; public class BiometricConfigurationResponse implements KvmSerializable { public int coderAlgorithm; public int templateFormat; public BiometricConfigurationResponse(){} public BiometricConfigurationResponse(SoapObject soapObject) { if (soapObject == null) return; if (soapObject.hasProperty("coderAlgorithm")) { Object obj = soapObject.getProperty("coderAlgorithm"); if (obj != null && obj.getClass().equals(SoapObject.class)){ SoapPrimitive j =(SoapPrimitive) obj; coderAlgorithm = Integer.parseInt(j.toString()); } else if (obj!= null && obj instanceof Number){ coderAlgorithm = (Integer) obj; } } if (soapObject.hasProperty("templateFormat")) { Object obj = soapObject.getProperty("templateFormat"); if (obj != null && obj.getClass().equals(SoapPrimitive.class)){ SoapPrimitive j =(SoapPrimitive) obj; templateFormat = Integer.parseInt(j.toString()); }else if (obj!= null && obj instanceof Number){ templateFormat = (Integer) obj; } } } #Override public Object getProperty(int arg0) { switch(arg0){ case 0: return coderAlgorithm; case 1: return templateFormat; } return null; } #Override public int getPropertyCount() { return 15; } #Override public void getPropertyInfo(int index, #SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo info) { switch(index){ case 0: info.type = PropertyInfo.INTEGER_CLASS; info.name = "coderAlgorithm"; break; case 1: info.type = PropertyInfo.INTEGER_CLASS; info.name = "templateFormat"; break; } #Override public void setProperty(int arg0, Object arg1) { } #Override public String getInnerText() { // TODO Auto-generated method stub return null; } #Override public void setInnerText(String arg0) { // TODO Auto-generated method stub } } The trick is to modify the parsing so instead of get the properties(e.g.): if (soapObject.hasProperty("coderAlgorithm")){ Object obj = soapObject.getProperty("coderAlgorithm"); if (obj != null && obj.getClass().equals(SoapObject.class)){ SoapPrimitive j =(SoapPrimitive) obj; coderAlgorithm = Integer.parseInt(j.toString()); } else if (obj!= null && obj instanceof Number){ coderAlgorithm = (Integer) obj; } } Get the ATTRIBUTES (e.g.): if (soapObject.hasAttribute("coderAlgorithm")) { Object obj = soapObject.getAttribute("coderAlgorithm"); if (obj != null && obj.getClass().equals(SoapObject.class)){ SoapPrimitive j =(SoapPrimitive) obj; coderAlgorithm = Integer.parseInt(j.toString()); } else if (obj!= null && obj instanceof Number){ coderAlgorithm = (Integer) obj; } else if (obj!= null && obj instanceof String){ coderAlgorithm = Integer.parseInt(obj.toString()); } }
Changing variable values from object fields
The following is my code: package com.collegeselector; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; public class CollegeList extends ListActivity { ArrayList<CollegeItem> collegeLists=new ArrayList<CollegeItem>(); ArrayList<String> nameList = new ArrayList<String>(); Comparator<CollegeItem> compare = new Comparator<CollegeItem>(){ public int compare(CollegeItem a, CollegeItem b){ return Double.compare(a.getScoreDistance(), b.getScoreDistance()); } }; CollegeItem michigan = new CollegeItem(3.79,30,2020,"University of Michigan","Ann Arbor, Michigan",true,false,true,false,true,true,true,true,true,true,true,true); CollegeItem berkeley = new CollegeItem(3.84,30,2040,"University of California Berkeley","Berkeley, California",false,false,true,true,true,true,true,true,true,true,true,true); CollegeItem stanford = new CollegeItem(3.96,33,2215,"Stanford University","Stanford, California",true,false,true,true,true,true,true,true,true,true,true,true); CollegeItem mit = new CollegeItem(3.92,33,2206,"Massachusetts Institute of Technology","Cambridge,Massachusetts",true,false,true,true,true,true,true,true,true,true,true,true); CollegeItem cit = new CollegeItem(3.95,34,2300,"California Institute of Technology","Pasadena,California",true,false,false,true,false,true,true,true,false,false,false,true); CollegeItem git = new CollegeItem(3.9,30,2010,"Georgia Institute of Technology","Atlanta,Georgia",true,false,true,true,true,true,true,false,true,true,true,true); CollegeItem uiuc = new CollegeItem(3.4,28,1975,"University of Illinois at Urbana-Champaign","Champaign,Illinois",true,true,false,false,true,true,true,true,true,false,true,true); CollegeItem carnegie = new CollegeItem(3.69,31,2100,"Carnegie Mellon University","Pittsburgh, Pennsylvania",false,false,false,false,false,true,true,false,true,false,true,false); CollegeItem cornell = new CollegeItem(3.87,31,2150,"Cornell Univeristy","Ithaca, New York",false,true,false,true,true,true,true,false,true,false,true,true); CollegeItem princeton = new CollegeItem(3.87,33,2260,"Princeton University","Princeton, New Jersey",true,false,false,true,false,false,false,false,false,false,false,false); CollegeItem purdue = new CollegeItem(3.7,27,1749,"Purdue University","West Lafayette, Indiana",true,true,false,false,true,false,true,false,false,true,false,true); CollegeItem utaustin = new CollegeItem(3.72,28,1854,"University of Texas at Austin","Austin, Texas",true,false,false,true,true,true,false,false,true,false,false,true); CollegeItem northwestern = new CollegeItem(3.8,32,2155,"Northwestern University","Evanston, Illinois",false,false,false,false,false,false,false,false,false,true,true,false); CollegeItem wisconsin = new CollegeItem(3.84,28,1905,"University of Wisconsin-Madison","Madison, Wisconsin",false,false,false,true,false,false,false,false,false,true,false,false); CollegeItem calpoly = new CollegeItem(3.87,28,1838,"California Polytechnic State University, San Luis Obispo","San Luis Obispo, California",false,false,false,false,false,false,false,false,false,false,false,false); CollegeItem johnshopkins = new CollegeItem(3.72,32,2103,"Johns Hopkins University","Baltimore, Maryland",false,false,true,false,false,false,false,false,true,false,false,false); CollegeItem pennstate = new CollegeItem(3.59,27,1778,"Pennsylvania State University-University Park","University Park, Pennsylvania",false,false,false,false,false,false,false,true,false,true,true,false); CollegeItem rice = new CollegeItem(3.87,32,2155,"Rice University","Houston, Texas",false,false,true,false,false,false,false,false,false,false,false,false); CollegeItem texasam = new CollegeItem(3.6,27,1755,"Texas A&M University","College Station, Texas",false,true,false,false,false,false,false,false,false,true,false,false); CollegeItem vtech = new CollegeItem(3.77,28,1823,"Virginia Tech","Blacksburg, Virginia",false,false,false,false,true,false,false,true,false,true,false,false); #Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); collegeLists.add(michigan);collegeLists.add(purdue); collegeLists.add(berkeley);collegeLists.add(utaustin); collegeLists.add(stanford);collegeLists.add(northwestern); collegeLists.add(mit);collegeLists.add(wisconsin); collegeLists.add(cit);collegeLists.add(calpoly); collegeLists.add(git);collegeLists.add(johnshopkins); collegeLists.add(uiuc);collegeLists.add(pennstate); collegeLists.add(carnegie);collegeLists.add(rice); collegeLists.add(cornell);collegeLists.add(texasam); collegeLists.add(princeton);collegeLists.add(vtech); Collections.sort(collegeLists, compare); for(CollegeItem collegeList : collegeLists){ nameList.add(collegeList.getName()); } setListAdapter(new ArrayAdapter<String>(CollegeList.this, android.R.layout.simple_list_item_1, nameList)); } private class CollegeItem { private double gpa; private int act; private int sat; private String name; private String location; private double score; private boolean match; private double scoreDistance; private boolean uaero, uagri, ubio, uchem, ucivil, ucomp, uelec, uphys, uenvi, uindus, umate, umech; public CollegeItem(double gpa, int act, int sat, String name, String location, boolean uaero, boolean uagri, boolean ubio, boolean uchem, boolean ucivil, boolean ucomp, boolean uelec, boolean uphys, boolean uenvi, boolean uindus, boolean umate, boolean umech){ this.gpa = gpa; this.act = act; this.sat = sat; this.name = name; this.location = location; this.uaero = uaero; this.uagri = uagri; this.ubio = ubio; this.uchem = uchem; this.ucivil = ucivil; this.ucomp = ucomp; this.uelec = uelec; this.uphys = uphys; this.uenvi = uenvi; this.uindus = uindus; this.umate = umate; this.umech = umech; if(act/36.0>sat/2400.0){ this.score = 0.6*gpa*25.0+0.4*(act/36.0)*100.0; }else{ this.score = 0.6*gpa*25.0+0.4*(sat/2400.0)*100.0; } scoreDistance = Math.abs(this.score-MainActivity.scoreDouble)/MainActivity.scoreDouble; if(uaero&&ListOfMajors.aerospace) match = true; if(uagri&&ListOfMajors.agricultural) match = true; if(ubio&&ListOfMajors.biomed) match = true; if(uchem&&ListOfMajors.chem) match = true; if(ucivil&&ListOfMajors.civil) match = true; if(ucomp&&ListOfMajors.computer) match = true; if(uelec&&ListOfMajors.electrical) match = true; if(uphys&&ListOfMajors.physics) match = true; if(uenvi&&ListOfMajors.environment) match = true; if(uindus&&ListOfMajors.industrial) match = true; if(umate&&ListOfMajors.materials) match = true; if(umech&&ListOfMajors.mechanical) match = true; } public String getName(){ return this.name; } public double getScoreDistance(){ return this.scoreDistance; } CheckList Activity public class ListOfMajors extends Activity { boolean[] mItemState; public static boolean aerospace, agricultural, biomed, chem, civil, computer, electrical, physics, environment, industrial, materials, mechanical; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.majorslist); ListView mylist = (ListView) findViewById(R.id.majorslist); final String[] list={"Aerospace Engineering","Agricultural Engineering", "Biomedical Engineering","Chemical Engineering","Civil Engineering", "Computer Engineering","Electrical Engineering","Engineering Physics", "Environmental Engineering","Industrial Engineering", "Materials Engineering","Mechanical Engineering"}; mItemState = new boolean[list.length]; ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListOfMajors.this,android.R.layout.simple_list_item_multiple_choice,list); mylist.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() { #Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Toggle the state mItemState[position] = !mItemState[position]; if (mItemState[position]) switch(position){ case 0: aerospace = true; case 1: agricultural = true; case 2: biomed = true; case 3: chem = true; case 4: civil = true; case 5: computer = true; case 6: electrical = true; case 7: physics = true; case 8: environment = true; case 9: industrial = true; case 10: materials = true; case 11: mechanical = true; } else{ switch(position){ case 0: aerospace = false; case 1: agricultural = false; case 2: biomed = false; case 3: chem = false; case 4: civil = false; case 5: computer = false; case 6: electrical = false; case 7: physics = false; case 8: environment = false; case 9: industrial = false; case 10: materials = false; case 11: mechanical = false; } } } }); mylist.setAdapter(adapter); } } The variables such as uaero and uagri are boolean fields of objects. I have a quite a few objects in this class. The variables such as ListOfMajors.aerospace and ListOfMajors.agricultural are boolean values from another class which are set to true if a checkbox is clicked. All of these pairs of variables correspond with each other and would like the variable match set to true if both of the other variables are true. As of right now, the code doesn't seem to working as match doesn't appear to be changing to true. What should I do to get this to work?
Your cases are probably not doing what you think .. since there is no break a case position 0 will set all of the variables to true (or false) switch(position){ case 0: aerospace = true; break; case 1: agricultural = true;break; case 2: biomed = true;break; case 3: chem = true;break; case 4: civil = true;break; case 5: computer = true;break; case 6: electrical = true;break; case 7: physics = true;break; case 8: environment = true;break; case 9: industrial = true;break; case 10: materials = true;break; case 11: mechanical = true; break; }
Can't make instance from java class
I write code for MSN application , and this application connection with server ASP.NET this code run perfectly in my computer , but when I run this code in other computer it is giving me runtime error in this line new SigninPerson(s1,s2); Error: could not find class 'com.example.hello.Signinperson' referenced from method com.example.hello.MainActivity.GoToProfileActivity Code: public class MainActivity extends Activity { public final String URL="http://10.0.2.2:47102/ProjectTwo/Service.asmx"; public final String NAMESPACE="http://tempuri.org/"; public final String METHOD= "signin"; public final String ACTION = "http://tempuri.org/signin"; private EditText EditTextEmail; private EditText EditTextPass; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void GoToSignupActivity (View V) { Intent SignupAct = new Intent("com.example.hello.SignupActivity"); startActivity(Intent.createChooser(SignupAct, "Choose an Application")); } public void GoToProfileActivity (View V) { EditTextEmail = (EditText) findViewById(R.id.Edit_Text_Email); EditTextPass = (EditText) findViewById(R.id.Edit_Text_Pass); if (isEmptyEditText(EditTextEmail) | isEmptyEditText(EditTextPass)) { showDialog(0); } else { String s1 = EditTextEmail.getText().toString().trim(); String s2 = EditTextPass.getText().toString().trim(); SigninPerson SIPerson = new SigninPerson(s1,s2); SoapObject Req = new SoapObject(NAMESPACE, METHOD); PropertyInfo p = new PropertyInfo(); p.setName("SIPerson"); p.setValue(SIPerson); p.setType(SIPerson.getClass()); Req.addProperty(p); SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11); env.dotNet = true; env.setOutputSoapObject(Req); env.addMapping(NAMESPACE, "SigninPerson", new SigninPerson().getClass()); HttpTransportSE ahttp = new HttpTransportSE(URL); SoapObject Res = null; try { ahttp.call(ACTION, env); Res = (SoapObject) env.getResponse(); } catch (Exception ex) { ex.printStackTrace(); } if (Integer.parseInt(Res.getProperty(0).toString())==0) { showDialog(1); } else { SIPerson.Person_Id = Integer.parseInt(Res.getProperty(0).toString()); SIPerson.F_Name = Res.getPropertyAsString(1).toString(); SIPerson.L_Name = Res.getPropertyAsString(2).toString(); SIPerson.E_Mail = Res.getPropertyAsString(3).toString(); SIPerson.Password = Res.getPropertyAsString(4).toString(); Intent ProfileAct = new Intent("com.example.hello.ProfileActivity"); ProfileAct.putExtra("ReciveLogin", SIPerson); startActivity(Intent.createChooser(ProfileAct, "Choose an Application")); } } } public boolean isEmptyEditText (EditText ET) { boolean isEmpty = true; if (ET.getText().toString().trim().length() > 0) { isEmpty = false; } return isEmpty; } #Override protected Dialog onCreateDialog(int id) { switch (id) { case 0: Dialog EnterBothDialog = new Dialog(this); EnterBothDialog.setTitle("Please Enter Both E-Mail / Password"); return EnterBothDialog; case 1: Dialog InvalidEmPass = new Dialog(this); InvalidEmPass.setTitle("Invalid Email / Password"); return InvalidEmPass; } return null; } } and this is SigninPerson public class SigninPerson implements KvmSerializable, Serializable { public int Person_Id; public String F_Name; public String L_Name; public String E_Mail; public String Password; public SigninPerson () { } public SigninPerson (int id, String Fname, String Lname, String Email, String Pass) { Person_Id = id; F_Name = Fname; L_Name = Lname; E_Mail = Email; Password = Pass; } public SigninPerson (String Email, String Pass) { Person_Id = 0; F_Name = ""; L_Name = ""; } #Override public Object getProperty(int arg0) { // TODO Auto-generated method stub switch (arg0) { case 0: return Person_Id; case 1: return F_Name; case 2: return L_Name; case 3: return E_Mail; case 4: return Password; } return null; } #Override public int getPropertyCount() { // TODO Auto-generated method stub return 5; } #Override public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2) { // TODO Auto-generated method stub switch (arg0) { case 0: arg2.type = PropertyInfo.INTEGER_CLASS; arg2.name = "Person_Id"; break; case 1: arg2.type = PropertyInfo.STRING_CLASS; arg2.name = "F_Name"; break; case 2: arg2.type = PropertyInfo.STRING_CLASS; arg2.name = "L_Name"; break; case 3: arg2.type = PropertyInfo.STRING_CLASS; arg2.name = "E_Mail"; break; case 4: arg2.type = PropertyInfo.STRING_CLASS; arg2.name = "Password"; break; default:break; } } #Override public void setProperty(int arg0, Object arg1) { // TODO Auto-generated method stub switch (arg0) { case 0: Person_Id = Integer.parseInt(arg1.toString()); break; case 1: F_Name = arg1.toString(); break; case 2: L_Name = arg1.toString(); break; case 3: E_Mail = arg1.toString(); break; case 4: Password = arg1.toString(); break; default:break; } } } but when I delete implements from SigninPerson and Override public class SigninPerson{ /** * */ private static final long serialVersionUID = 1L; public int Person_Id; public String F_Name; public String L_Name; public String E_Mail; public String Password; public SigninPerson () { } public SigninPerson (int id, String Fname, String Lname, String Email, String Pass) { Person_Id = id; F_Name = Fname; L_Name = Lname; E_Mail = Email; Password = Pass; } public SigninPerson (String Email, String Pass) { Person_Id = 0; F_Name = ""; L_Name = ""; } } it is make new for SigninPerson and don't give me run time I am trying to found the problem long time but I can't find any wrong please , anyone can help me because I must send my application in the morning
You should change this line: SigninPerson SIPerson = null; new SigninPerson(s1,s2); to: SigninPerson SIPerson = new SigninPerson(s1,s2);
It'll give you a NullPointerException as you declared a reference for the SigninPerson, but you never assigned it to a new object of this class as #SOfanatic recommended for you ( +1 for him). SigninPerson SIPerson = null;// << here assign SIPerson to new SigninPerson //.... p.setValue(SIPerson); p.setType(SIPerson.getClass());