Changing variable values from object fields - java

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;
}

Related

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());
}
}

ksoap2 android web services complextype byte[]

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.

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());

SQLite with android error

i am relatively new to programming and android,and i am working on a little notepad app. I learned how to use SQLite from a tutorial on the web,but something is wrong..when i am running the app,it keeps telling me that there are no columns in the name... but there are! what am i doing wrong? i checked the syntax a dozens of times,and i did it like the tutorial did one by one. I know this question was here before more than one time,but when reading the answers, i still couldnt find a solution to my specific problem. basically i just added 2 notes with title and text and wanted to present them in the main activity in a ListView,but nothing is showing up because of the database problem.
Help is very very appreciated :) thx in advance
this is the classes:
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseManager extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "notesDb";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "notes";
private static final String NOTE_ID = "_id";
private static final String NOTE_TITLE = "title";
private static final String NOTE_TEXT = "text";
private static final String NOTE_CREATION_DATE = "creationDate";
public DatabaseManager(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_NOTES_TABLE = "CREATE TABLE "+TABLE_NAME+"(" + NOTE_ID +" INTEGER PRIMARY KEY,"+ NOTE_TITLE + "TEXT,"
+ NOTE_TEXT + "TEXT," + NOTE_CREATION_DATE + "TEXT" + ")";
db.execSQL(CREATE_NOTES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
public void addNote(Note note){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NOTE_TITLE, note.getTitle());
values.put(NOTE_TEXT, note.getText());
values.put(NOTE_CREATION_DATE, note.getCurrentTime());
db.insert(TABLE_NAME, null, values);
db.close();
}
public void deleteNote(Note note){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, NOTE_ID + "?=",new String[]{String.valueOf(note.getId())} );
db.close();
}
public String[] listNotes(){
ArrayList<String> tempArray = new ArrayList<String>();
String[]notesArray = new String[0];
String sqlQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(sqlQuery,null);
if(c.moveToFirst()){
do{
tempArray.add(c.getString(c.getColumnIndex(NOTE_TITLE)));
}
while(c.moveToNext());
}
c.close();
notesArray = tempArray.toArray(notesArray);
return notesArray;
}
}
the note object:
import java.util.Calendar;
public class Note {
private int id;
private String text;
private String title;
private String creationTime;
private String currentTime;
public Note(){
}
public String getCurrentTime(){
return getDayOfMonth()+"/"+getMonth()+"/"+getYear()+" "+getDay()+", "+getHour()+":"+getMinutes();
}
public String getMonth(){
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
String month = new String();
switch(currentMonth){
case 0:
month = "01";
break;
case 1:
month = "02";
break;
case 3:
month = "04";
break;
case 4:
month = "05";
break;
case 5:
month = "06";
break;
case 6:
month = "07";
break;
case 7:
month = "08";
break;
case 8:
month = "09";
break;
case 9:
month = "10";
break;
case 10:
month = "11";
break;
case 11:
month = "12";
break;
}
return month;
}
public String getDayOfMonth(){
int currentDayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
String dayOfMonth = new String();
if(currentDayOfMonth<10){
dayOfMonth = "0"+currentDayOfMonth;
}
else{
dayOfMonth = ""+currentDayOfMonth;
}
return dayOfMonth;
}
public String getYear(){
String year = ""+Calendar.getInstance().get(Calendar.YEAR);
return year;
}
public String getDay(){
int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
String day = new String();
switch(currentDay){
case 1:
day = "Sun";
break;
case 2:
day = "Mon";
break;
case 3:
day = "Tue";
break;
case 4:
day = "Wed";
break;
case 5:
day = "Thu";
break;
case 6:
day = "Fri";
break;
case 7:
day = "Sat";
break;
}
return day;
}
public String getHour(){
int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
String hour = new String();
if(currentHour<10){
hour = "0"+currentHour;
}
else{
hour = ""+currentHour;
}
return hour;
}
public String getMinutes(){
int currentMinutes = Calendar.getInstance().get(Calendar.MINUTE);
String minutes = new String();
if(currentMinutes<10){
minutes = "0"+currentMinutes;
}
else{
minutes = ""+currentMinutes;
}
return minutes;
}
public void setText(String text){
this.text = text;
}
public String getText(){
return this.text;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return this.id;
}
}
the main activity:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseManager db = new DatabaseManager(this);
Note n1 = new Note();
Note n2 = new Note();
n1.setTitle("n1 title");
n1.setText("n1 text");
n2.setTitle("n2 title");
n2.setText("n2 text");
db.addNote(n1);
db.addNote(n2);
String[]notes = db.listNotes();
ArrayAdapter<String>adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,notes);
ListView lv = (ListView)findViewById(R.id.notes_list);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and the xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/board"
android:scaleType="fitXY"/>
<ImageButton
android:id="#+id/add_note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:src="#drawable/note"
android:background="#android:color/transparent"/>
<ListView
android:id="#+id/notes_list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentTop="true"/>
A semi colon inside the query is missing for your table creation string CREATE_NOTES_TABLE string. Include a semicolon (;) inside the string just after the final ")"; ie. Make it ");";

Categories