Switch while loop - java

I have a basic method that implements controlling of application menu using switch
public void applicationMenu(String input) {
switch (input) {
case "1":
findGroups();
break;
case "2":
findStudentsByCourseName();
break;
case "3":
addNewStudent();
break;
case "4":
deleteStudentById();
break;
case "5":
addStudentToCourse();
break;
case "6":
removeStudentCourse();
break;
default:
printDefault();
break;
}
}
I use this method with a while loop to call my application menu
public void callMenu() {
boolean exit = false;
while (!exit) {
viewProvider.printMainMenu();
String input = viewProvider.readString();
if (input.equals("7")) {
exit = true;
}
applicationMenu(input);
}
}
How can I trigger exit from switch case but keep the structure of two methods at the same time?

This should work:
public boolean applicationMenu(String input) {
boolean shouldContinue = true;
switch (input) {
case "1":
findGroups();
break;
case "2":
findStudentsByCourseName();
break;
case "3":
addNewStudent();
break;
case "4":
deleteStudentById();
break;
case "5":
addStudentToCourse();
break;
case "6":
removeStudentCourse();
break;
case "7":
shouldContinue = false;
break;
default:
printDefault();
break;
}
return shouldContinue;
}
...
public void callMenu() {
while (true) {
viewProvider.printMainMenu();
String input = viewProvider.readString();
if (!applicationMenu(input)) {
break;
}
}
}

As stated in comments, you could throw an Exception, but I typically don't like to do that if i'm not in an actual error state. It makes more sense to me to use a return value and evaluate the result to determine if the program should terminate:
public void callMenu() {
boolean exit = false;
while (!exit) {
viewProvider.printMainMenu();
exit = applicationMenu(viewProvider.readString());
}
}
public boolean applicationMenu(String input) {
switch (input) {
case "1":
findGroups();
return false;
case "2":
findStudentsByCourseName();
return false;
case "3":
addNewStudent();
return false;
case "4":
deleteStudentById();
return false;
case "5":
addStudentToCourse();
return false;
case "6":
removeStudentCourse();
return false;
case "7":
return true;
default:
printDefault();
}
return false;
}

Related

How to set the ListObject in RecyclerView

I just started combining json data with recyclerView. After checking ArrayList can completed save key and value
public class test extends AppCompatActivity {
//set Attributes and storage List for json
public String jsonData = "myurl";
ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
...
private void loadingData() {//the method is called in onCreate
ProgressDialog dialog = ProgressDialog.show(this, "update",
"Loading Data", true);
//using Thread and Dialog while loading the data
new Thread(() -> {
try {
//use GetData(AsyncTask) & parse json
String jsonOpendata = new GetData().execute(jsonData).get();
JSONArray jsonArray = new JSONArray(jsonOpendata);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Set key & value for Hashmap
String Date = jsonObject.getString("date");
String[] dateFormat = Date.split("-");
switch (dateFormat[1]) {
case "1":
dateFormat[1] = "Jan.";
break;
case "2":
dateFormat[1] = "Feb.";
break;
case "3":
dateFormat[1] = "Mar.";
break;
case "4":
dateFormat[1] = "Apr.";
break;
case "5":
dateFormat[1] = "May.";
break;
case "6":
dateFormat[1] = "Jun.";
break;
case "7":
dateFormat[1] = "Jul.";
break;
case "8":
dateFormat[1] = "Aug.";
break;
case "9":
dateFormat[1] = "Sep.";
break;
case "10":
dateFormat[1] = "Oct.";
break;
case "11":
dateFormat[1] = "Nov.";
break;
case "12":
dateFormat[1] = "Dec.";
break;
}
String dateFormat = jsonObject.getString(String.valueOf(dateFormat)));
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("date", dateFormat);
...
arrayList.add(hashMap);
}
//loading completed Thread
runOnUiThread(() -> {
dialog.dismiss();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new GridLayoutManager(this,4));
recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter();
recyclerView.setAdapter(recyclerAdapter);
});
//catch....
And my recyclerView can read adapter and display the data successfully.
However, I found out the way more efficient and useful to save the data in arrayList is to put it into ListObject,so I've attempted it as follows
public class test extends AppCompatActivity {
//replacement
public String jsonData = "myurl";
**List<Book> bList = new ArrayList<>();**
...
private void loadingData() {//the method is called in onCreate
//using Thread and Dialog while loading the data
//use GetData(AsyncTask) & parse json
...
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Set key & value in Object
**Book book = new Book();**
String Date = jsonObject.getString("date");
String[] dateFormat = Date.split("-");
switch (dateFormat[1]) {
case "1":
dateFormat[1] = "Jan.";
break;
case "2":
dateFormat[1] = "Feb.";
break;
case "3":
dateFormat[1] = "Mar.";
break;
case "4":
dateFormat[1] = "Apr.";
break;
case "5":
dateFormat[1] = "May.";
break;
case "6":
dateFormat[1] = "Jun.";
break;
case "7":
dateFormat[1] = "Jul.";
break;
case "8":
dateFormat[1] = "Aug.";
break;
case "9":
dateFormat[1] = "Sep.";
break;
case "10":
dateFormat[1] = "Oct.";
break;
case "11":
dateFormat[1] = "Nov.";
break;
case "12":
dateFormat[1] = "Dec.";
break;
}
**astro.setDate(jsonObject.getString(String.valueOf(dateFormat)));**
...
**bList.add(book);**
}
//loading completed Thread
runOnUiThread(() -> {
dialog.dismiss();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new GridLayoutManager(this,4));
recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(**this,bList**);
recyclerView.setAdapter(recyclerAdapter);
});
//catch....
Then add a Book class
public class Book {
String date;
public Book(String date) {
this.date = date;
}
public Book() {
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date= date;
}
And the errors occur said
W/System.err: org.json.JSONException: No value for [Ljava.lang.String;#1b3da99
I will really appreciate if someone could give me any solution or direction to solve this problem
I found the solution.The reason why the error tells
W/System.err: org.json.JSONException: No value for [Ljava.lang.String;#1b3da99
is because that I shouldn't get jsonObject data and transfer the formation at the same time.
book.setDate(jsonObject.getString(String.valueOf(dateFormat)));
the key of value was named 'date' in my json data.However, I thought it would be fine to run through the argument in dateformat and parse the value to string as an jsonObject value. jsonObject didn't have the key 'dateformat' ,so there was no clue can find my value.The ide can only find automatic-generated id in dateformat and transfer it to String #1b3da99 during the runtime.
the solution just seperate the procedure.
get the jsonObject in the main class
book.setDate(jsonObject.getString("date"));
bList.add(book)
and put the argument in the setDate.
public void setDate(String date) {//dateFormat argument}

Calling a method to return a different int from a switch

I'm trying to call a method and based on the input, return that value to a switch I have in another class. So if I were to choose the "1" element in my array, I would get reply returned as "4" back into my other class and make it run switch "4".
In the other class I have the switch "4" set to another method. However, I keep getting the int value "1" returned from my method as it keeps calling that method (switch "1"). Which makes sense since it's the "1" element in my array, it should then run switch "1", but I thought that by setting "reply = 4", it would return an int "4" into my other class and thus invoke switch "4".
How do I get my methods to return the value I want so I can put into my switch?
Here's my first class where I'm doing the calling:
package bunnyhunt;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class Messages {
//Objects
public Rooms roomCall = new Rooms();
//Instance Variables
public static boolean gameOver = false;
public static int roomNum;
public static int reply;
boolean visitedOtherRoom = false;
//Constructors
//Methods
public void start() {
//while loop
while (gameOver == false) {
//do-while loop
do {
String[] parkEntrance = {"Spring Meadow", "Aeryn's Overlook", "Garden Gate"};
reply = JOptionPane.showOptionDialog(null, "You're at the Park Entrance! What do you want to do?", "Bunny Adventure", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, parkEntrance, parkEntrance[0]);
switch (reply) {
case 0:
System.out.println("oh man...Spring");
visitedOtherRoom = true;
roomCall.springMeadow();
break;
case 1:
System.out.println("oh man...Aeryn");
visitedOtherRoom = true;
roomCall.aerynsOverlook();
break;
case 2:
System.out.println("oh man...Garden");
visitedOtherRoom = true;
roomCall.gardenGate();
break;
default:
System.out.println("error");
}
} while (visitedOtherRoom == false);
switch (reply) {
case 0:
System.out.println("second 0!!!");
visitedOtherRoom = true;
roomCall.parkEntrance();
break;
case 1:
visitedOtherRoom = true;
System.out.println("yes man!");
roomCall.aerynsOverlook();
break;
case 2:
visitedOtherRoom = true;
roomCall.gardenGate();
break;
case 3:
visitedOtherRoom = true;
roomCall.peacefulPond();
break;
case 4:
visitedOtherRoom = true;
roomCall.readingNook();
break;
default:
System.out.println("default");
}
}
JOptionPane.showMessageDialog(null,
"Game Over!!!");
}
}
and my second where the things I call reside:
package bunnyhunt;
import javax.swing.JOptionPane;
public class Rooms {
public static int reply;
public int springMeadow() {
String[] springMeadow = {"Park Entrance", "Reading Nook", "Search"};
Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Spring Meadow! What do you want to do?", "Spring Meadow", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, springMeadow, springMeadow[0]);
switch (reply) {
case 0:
reply = 0;
break;
case 1:
reply = 4;
break;
case 2:
JOptionPane.showMessageDialog(null,
"You searched!");
break;
default:
System.out.println("error");
}
return reply;
}
public int aerynsOverlook() {
String[] aerynsOverlook = {"Park Entrance", "Peaceful Pond", "Search"};
Messages.reply = JOptionPane.showOptionDialog(null, "You're in Aeryn's Overlook! What do you want to do?", "Aeryn's Overlook", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, aerynsOverlook, aerynsOverlook[0]);
return reply;
}
public int gardenGate() {
String[] gardenGate = {"Park Entrance", "Rose Gardent", "Butterfly Garden", "Flowering Forest"};
return reply;
}
public int readingNook() {
String[] readingNook = {"Spring Meadow", "Search"};
Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Reading Nook! What do you want to do?", "Reading Nook", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, readingNook, readingNook[0]);
return reply;
}
public int parkEntrance() {
String[] parkEntrance = {"Spring Meadow", "Aeryn's Overlook", "Search"};
Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Park Entrance! What do you want to do?", "Park Entrance", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, parkEntrance, parkEntrance[0]);
return reply;
}
public int peacefulPond() {
String[] peacefulPond = {"Raven's Tower", "Aeryn's Overlook", "Search"};
Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Peaceful Pond! What do you want to do?", "Peaceful Pond", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, peacefulPond, peacefulPond[0]);
return reply;
}
}
You are not returning a reply value from the start() method since this method is void AND switch statements inside don't return anything, despite they contain calls to appropriate methods like int aerynsOverlook(). You should modifystart` method like this:
public int start() {
...
switch (reply) {
case 0:
System.out.println("oh man...Spring");
visitedOtherRoom = true;
return roomCall.springMeadow();
...
Secondly, I don't see how you are calling start() method to get its return value and use it in the second switch. Your MEssages class doesn't have any connection with the Rooms

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

Abstract Table Model isCellEditable() Overriding did not make cells editable

I am implementing a JTable with a TableModel.
I've got a problem to make cells editable on this specific one.
Here is my isCellEditable overriding of the TableModel
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
The Jtable instanciate with this TableModel doesn't make cells editable.
First I instanciate my JScrollPane with The JTable in it :
caseTM = new CaseTableModel(factory,caseList);
caseListTable = new JTable(caseTM);
caseScrollPanel = new JScrollPane(caseListTable);
Here is the code of the CaseTableModel :
public class CaseTableModel extends AbstractTableModel {
Factory f;
ArrayList<Case> cList;
public CaseTableModel(Factory f,ArrayList<Case> caseList) {
this.f=f;
cList=caseList;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return cList.get(0).getClass();
}
#Override
public int getColumnCount() {
return 14;
}
#Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0:
return "Numéro d'Affaire";
case 1:
return "Client";
case 2:
return "Projet";
case 3:
return "Position";
case 4:
return "Status";
case 5:
return "Date Début";
case 6:
return "Date Fin";
case 7:
return "Nombre de jours facturés";
case 8:
return "Daily Rate";
case 9:
return "IGD";
case 10:
return "Autres Conditions";
case 11:
return "Echeance de paiement";
case 12:
return "Date de paiment";
case 13:
return "Montant HT";
case 14:
return "Montant TTC";
default:
return "FAUX!";
}
}
#Override
public int getRowCount() {
return cList.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return cList.get(rowIndex).getNumber();
case 1:
return cList.get(rowIndex).getClient();
case 2:
return cList.get(rowIndex).getProject();
case 3:
return cList.get(rowIndex).getPositon();
case 4:
return cList.get(rowIndex).getStatus();
case 5:
return cList.get(rowIndex).getStartDate();
case 6:
return cList.get(rowIndex).getEndDate();
case 7:
return cList.get(rowIndex).getNumberOfDayInvoice();
case 8:
return cList.get(rowIndex).getDailyRate();
case 9:
return cList.get(rowIndex).getDailyIndemnity();
case 10:
return cList.get(rowIndex).getOtherConditions();
case 11:
return cList.get(rowIndex).getPaymentDueDate();
case 12:
return cList.get(rowIndex).getPaymentDate();
case 13:
return cList.get(rowIndex).getAmountTaxFree();
case 14:
return cList.get(rowIndex).getAmountWithTax();
default:
return "FAUX!";
}
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
cList.get(rowIndex).setNumber((String) aValue);
break;
case 1:
cList.get(rowIndex).setClient((String) aValue);
break;
case 2:
cList.get(rowIndex).setProject((String) aValue);
break;
case 3:
cList.get(rowIndex).setPositon((String) aValue);
break;
case 4:
cList.get(rowIndex).setStatus((String) aValue);
break;
case 5:
cList.get(rowIndex).setStartDate((Integer) aValue);
break;
case 6:
cList.get(rowIndex).setEndDate((Integer) aValue);
break;
case 7:
cList.get(rowIndex).setNumberOfDayInvoice((Integer) aValue);
break;
case 8:
cList.get(rowIndex).setDailyRate((Double) aValue);
break;
case 9:
cList.get(rowIndex).setDailyIndemnity((Double) aValue);
break;
case 10:
cList.get(rowIndex).setOtherConditions((String) aValue);
break;
case 11:
cList.get(rowIndex).setPaymentDueDate((Integer) aValue);
break;
case 12:
cList.get(rowIndex).setPaymentDate((Integer) aValue);
break;
case 13:
cList.get(rowIndex).setAmountTaxFree((Double) aValue);
break;
case 14:
cList.get(rowIndex).setAmountWithTax((Double) aValue);
break;
default:
break;
}
f.updateCase(cList.get(rowIndex));
}
public void fireTableDataChangedForThisEmployee(Employee e){
cList = f.getCasesForThisEmployee(e);
super.fireTableDataChanged();
}
}

Drag and Drop switch case, unreachable code?

Why is this code unreachable and how do I fix it?
public void draggingEvent() {
image15();
final int thisLetter = currentLetter;
mImageView15.getDrawable();
mImageView15 = (ImageView) findViewById(R.id.imageView15);
mImageView15.setOnDragListener(new OnDragListener() {
public boolean onDrag(View v, DragEvent de) {
// TODO Auto-generated method stub
final int action = de.getAction();
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
if (de.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
v.invalidate();
return (true);
}
break;
case DragEvent.ACTION_DRAG_ENTERED:
v.invalidate();
return (true);
break; //un reachable here
case DragEvent.ACTION_DRAG_LOCATION:
//ignore even for now
if (de.getX() == 250 && de.getY() == 195) {
mImageView17.setImageResource(thisLetter);
v.invalidate();
return (true);
}
if (de.getX() == 300 && de.getY() == 195) {
mImageView17.setImageResource(thisLetter);
return (true);
}
break;// here
case DragEvent.ACTION_DRAG_EXITED:
de.getResult();
break; //here
case DragEvent.ACTION_DROP:
ClipData.Item item = de.getClipData().getItemAt(thisLetter);
v.invalidate();
return (true);
break; // here
case DragEvent.ACTION_DRAG_ENDED:
v.invalidate();
if (de.getResult()) {
Log.e("it worked", "worked");
} else {
Log.e("failed", "sorry failed drag and drop");
return (true);
}
break; //here
default:
Log.e("Drag drop", "Failed to find area");
break; // and here
};
return false;
};
});
You cannot execute any Java statement after return:
return (true);
break; //un reachable here
just have return statement. (you have two such occurrences)
In general, statements after a return statement in Java will not be executed.
This is almost correct; there is an important exception which helps program stability, that being the finally block. For example
try {
doSomething();
return;
} finally {
cleanUp();
}
the function cleanUp() will be executed.
Because you do return (true) before your break the break will never be called.

Categories