What does XmlPullParser "eventType" indicate? - java

I am documenting some code using JD-GUI. Currently working on class that utilizes "XMLPullParser". I have read some documentation, but not really getting a clear picture.
The following is a snippet from a method, I want to know what this "eventType" is indication before and in the switch statement cases. What is the significance of it? The "parser" variable below is of type "XmlPullParser"
while (!poComplete)
{
int eventType = this.parser.next();
if (1 == eventType) {
break;
}
switch (eventType)
{
case 2:
String name = this.parser.getName();
if ("purchaseOrder".equals(name)) {
bufferingData = true;
}
if (bufferingData) {
buf.append("<").append(name).append(">");
}
break;
case 3:
if (bufferingData)
{
String name = this.parser.getName();
buf.append("</").append(name).append(">");
if ("purchaseOrder".equals(name))
{
poComplete = true;
bufferingData = false;
}
}
break;
case 4:
if (bufferingData) {
buf.append(quoteXmlData(this.parser.getText()));
}
break;
}
}

next() method returns eventType of integer.
it is one of the constants defined in XMLPullParser.
see javadoc

Related

My switch statement is not returning anything?

Im selecting a "Left" from alert dialog and after putting it into convertStatusToCode function should retrun "4" but its not?
final String[] status = {"Left"};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Pick a Status");
builder.setItems(status, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
BookingStatus = convertStatusToCode(status[which]);
HERE IS MY convertStatusToCode FUNCTION but it is not retruning "4" which it should return.
private String convertStatusToCode(String status) {
switch (status) {
case "Processing":
i = "0";
break;
case "Room is Allotted":
i = "1";
break;
case "Sorry All Rooms Are Full":
i = "2";
break;
case "Living":
i = "3";
break;
case "Left":
i = "4";
break;
}
return i;
}
it should look something like this
String getStatusCode(String status) {
switch (status) {
case "Processing":
return "0";
case "Room is Allotted":
return "1";
case "Sorry All Rooms Are Full":
return "2";
case "Living":
return "3";
case "Left":
return "4";
default:
return "default_value";
}
}
Based upon what you've added in the comments, your Switch statement (albeit incomplete) shouldn't be the cause of your problem as the other posters are assuming.
You may have a problem with the completness of your switch cases, but that shouldn't stop the switch to work as intended.
You're saying that you DEBUG this and that i has the value of "" which I cannot understand unless you are not having a return value in scope.
The answer posted by Antonis Radz is how I would write that switch if I had to.
If you write your Convert function to return like so, then you don't need the extra i variable, which we don't know where you declared.
If you debug this line of code (like you said you did)
switch(value) and you're telling us that value == "Left" then the switch is receiving the correct value at runtime.
Now your "Case" is executed (when you set a breakpoint in case "Left". So the switch is, again, performing its function so far.
Then I assume you added another breakpoint in the following line(s):
i = "4";
break;
to see what is going on.
The first breakpoint would hit in the assignment i=... and so the variable i which I assume is declared somewhere in scope as String i (At the very least), is either null or contains an old value. Doesn't matter because the next breakpoint (in the break line) would be reached after i is assigned the value of the String "4". So if you add a watch to i and inspect it right there, it must have the value of "4".
Then you return this i so, again, it should still be "4".
If you did all this, you would have been able to tell much closer where the variable is not being assigned.
Do like this.
public String getstatuscode(String status){
String i="";
switch (status) {
case "Processing":
i = "0";
break;
case "Room is Allotted":
i = "1";
break;
case "Sorry All Rooms Are Full":
i = "2";
break;
case "Living":
i = "3";
break;
case "Left":
i = "4";
break;
default:
i = "-1";
}
return i;
}
Declare i as String or int as your requirement. Method is same.Don't forget to remove quotes if you want to assign i as int.
Another thought to use enum rather than switch-case here which gives more flexibility & reusability.
public enum BookingStatus
{
PROCESSING("Processing", 1),
ALLOTED_ROOM("Room is Allotted", 2),
ALL_FULL("Sorry All Rooms Are Full", 3),
LIVING("Living", 4),
LEFT("LEFT", 5);
private String status;
private int code;
BookingStatus(String status, int code)
{
this.status = status;
this.code = code;
}
public static BookingStatus getCodeFromStatus(String status)
{
for (BookingStatus e : values()) {
if (e.status.equals(status)) {
return e;
}
}
return null;
}
public static void main(String args[]) {
System.out.printf("Code for this status is %s", BookingStatus.getCodeFromStatus("Sorry All Rooms Are Full").code);
}
}
switch (status) {
case "Processing":
i = "0";
break;
case "Room is Allotted":
i = "1";
break;
case "Sorry All Rooms Are Full":
i = "2";
break;
case "Living":
i = "3";
break;
case "Left":
i = "4";
// return "4";
break;
}
return i;
}
use return "4"; you don't print anything in switch cases so switch can't return anything if you want to print in switch cases output then use the print method or return in any programming language.

Switch case error on libs

I have an error on implementing a library module to my Android apps.
it says:
Constant expression required Resource IDs cannot be used in a switch statement in Android library modules less... (Ctrl+F1)
Validates using resource IDs in a switch statement in Android library module. Resource IDs are non final in the library projects since SDK tools r14, means that the library code cannot treat these IDs as constants.
and here is my code:
private void changeWeekStart(#IdRes int selection) {
switch (selection) {
case R.id.action_week_start_saturday:
CalendarUtils.sWeekStart = Calendar.SATURDAY;
break;
case R.id.action_week_start_sunday:
CalendarUtils.sWeekStart = Calendar.SUNDAY;
break;
case R.id.action_week_start_monday:
CalendarUtils.sWeekStart = Calendar.MONDAY;
break;
}
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putInt(CalendarUtils.PREF_WEEK_START, CalendarUtils.sWeekStart)
.apply();
supportInvalidateOptionsMenu();
mCoordinator.reset();
}
Please help me to change from switch-case to if-else code.
thanks.
Everywhere you have a case, that will become the condition of an if statement; a break statement will correspond with a closing } on an if statement.
if (selection == R.id.action_week_start_saturday) {
CalendarUtils.sWeekStart = Calendar.SATURDAY;
} else if (selection == R.id.action_week_start_sunday) {
CalendarUtils.sWeekStart = Calendar.SUNDAY;
} else if (selection == R.id.action_week_start_monday) {
CalendarUtils.sWeekStart = Calendar.MONDAY;
}
Note that you do not supply a default case in your switch-case block so it is possible that CalendarUtils.sWeekStart is not modified if the selection parameter has a value different from the ones you've considered.

How to simplify my java code function?

How to make this code simplified? I'm having doubt on having two switch statements in my function.
private String getKeyword(String id) {
String keyword = "";
switch (id.substring(1, 2)) {
case "E":
keyword = "英語";
break;
case "M":
keyword = "数学";
break;
case "W":
keyword = "統合";
break;
}
switch (id.substring(4,5)){
case "W":
keyword = "統合";
break;
}
return keyword;
}
You could use just if else if statements.
It would be less verbose.
Besides, the before last and the last condition have similarities.
So you could put them in a single statement by combining them with an OR operator. Both return "統合".
At last, you could return directly the value instead of valuing a local variable in each matched case.
But as the second switch statement overwrites the value to return,
you should move it as the first condition to test. It would make things much clearer :
private String getKeyword(String id) {
char c = id.substring(1, 2).charAt(0);
if (c == 'W' || id.substring(4,5).charAt(0) == 'W'){
return "統合";
}
else if (c == 'E'){
return "英語";
}
else if (c == 'M'){
return "数学";
}
return "";
}
private String getKeyword(String id) {
String keyword = "";
switch (id.substring(1, 2)) {
case "E":
keyword = "英語";
break;
case "M":
keyword = "数学";
break;
case "W":
keyword = "統合";
break;
}
if ("W".equals(id.substring(4, 5))) keyword = "統合";
return keyword;
}
You could use an Enumeration.
Each of them would contain one or multiple id and the corresponding keyword: easier to read and maintain.
Finally, declare a static method in the Enumeration to retrieve the expected element depending on a provided id.
You can make a keyword map and use it instead. As this is static, you can make this map an instance variable and just use it when that method is called.
//do this in something like a constructor
Map<String, String> keywordMap = new HashMap<>;
keywordMap.put("E", "英語");
//more put calls
//and in your method, you'll only need
return keywordMap.get(id.substring(1, 2));
Pay attention to the logic implemented using two switch. As matches in the first switch don't cause the method to return, matches in the second switch can overwrite the keyword variable.
Use a map:
private static final Map<String, String> letterToKeyword =
Map.of("E", "英語", "M", "数学", "W", "統合");
private String getKeyword(String id) {
if (id.substring(4,5).equals("W")) return "統合";
return letterToKeyword.getOrDefault(id.substring(1, 2), "");
}
Prior to Java 9 building the map would be a little more verbose (but could be assisted with a helper method, if so desired):
private static final Map<String, String> letterToKeyword;
static {
Map<String, String> map = new HashMap<>();
map.put("E", "英語");
map.put("M", "数学");
map.put("W", "統合");
letterToKeyword = Collections.unmodifiableMap(map);
}
You could move the body of the switches in separately functions.
you could also remove the break's and return instantly in the cases, if you want it shorter.
You could also use enums
One of your switches can be replaced by a simple if statement.
private String getKeyword(String id)
{
if(id.substring(4,5).equals("W"))
{
return "統合";
}
else
{
switch (id.substring(1, 2)) {
case "E":
return "英語";
case "M":
return "数学";
case "W":
return "統合";
}
}
return "";
}

How to use String in switch?

IDE throws an NullPointerException when I'm trying to do this. I want to have only 2 genders to choose
public String typeOfGender
{
switch (typeOfGender)
{
case "Male":
typeOfGender = "Male";
break;
case "Female":
typeOfGender = "Female";
break;
default:
System.out.println(" Unrecognized gender." );
}
}
You have not initialized typeOfGender. It is null. That is why. Try
typeOfGender="Male";
By the way your code does not make sense. If typeOfGender equals "Male", you assign "Male" to it??
I use them often with no problems, example below. The only reason yours would throw that is if you are passing null to it.
private string GetMailBody(string regionCode)
{
switch(regionCode)
{
case "qc":
//Do some stuff
break;
default:
//If not specified, we assume US, so we do that.
break;
}
return "String we should have edited above";
}
The NullPointerExeption is caused because your string is null.
However, for future reference, here's an example of as switch-case with a string:
String string = "foo";
switch (string) {
case "foo":
System.out.println("foo");
break;
case "bar":
System.out.println("bar");
break;
default:
System.out.println("Mushroom Stew!");
break;
}

Java Switch Case return type

Hi I have a Switch case like
#Override
public <RERURN_TYPE...???> convert(Object argToken, Object argFieldToken) {
Object obj = Precondition.ensureNotNull(argToken, "Input Object");
Field field = (Field) Precondition
.ensureNotNull(argFieldToken, "Field");
Type type = Type.valueOf(field.getType().getName());
switch (type) {
case BYTE:
break;
case SHORT:
break;
case INTEGER:
return Integer.parseInt(argToken.toString());
break;
case LONG:
break;
case FLOAT:
break;
case DOUBLE:
break;
case CHARACTER:
break;
case BOOLEAN:
break;
case STRING:
break;
case BIGINT:
break;
default:
break;
}
return null;
}
Here I am converting the "argToken" value depends on the type of the field. Finally the return value will change according to that field type. So how can I maintain the return type which accepts all the return types.
Can anyone please explain this. I stuck over here...
Please...
Amar
You could design the switch part a lot easier like that:
if(argToken instanceof Integer) {
return (int) argToken;
} else if(/* some other types */) {
//cast and return the other types
} else {
return null;
}
But this would only work with the return type Object. The only alternative would be to write methods for each primitive type.
So there is no real solution.

Categories