Why equals might not return true - java
I have this string: "no_questions_by_user" in a variable named result.
than I do this check:
if ( result != null && result.equals( "no_user_id" ) )
{
Log.d( "Post execute: " , "NOOOT OKKKK - no user id" );
}
else
if ( result != null && result.equals( "database_error" ) )
{
Log.d( "Post execute: " , "NOOOT OKKKK - database error" );
}
else
if ( result != null && result.equals( "no_questions_by_user" ) )
{
Log.d( "Post execute: " , "NOOOT OKKKK - no questions by user so far" );
}
else
{
Log.d( "MyQuestionsActivity" , "In JSON parsing area.." );
}
and it always goes to the last else. But in my understanding it should really go to the block which checks result.equals( "no_questions_by_user" )
any idea why that block does not get executed?
Thanks!!
The code looks good. Your variable result must have another value.
My guess is that there are some whitespaces at the end or beginning of your result string.
Personally, I think this code is a hot mess.
I'd write one method that took in a result and looked up a message in a Map. All those if tests are making my eyes bleed:
private static final Map<String, String> LOG_MESSAGE_MAP;
static {
LOG_MESSAGE_MAP = new HashMap<String, String>();
// put all your result, message pairs in here
}
public void logResultDependentMessage(String result) {
log.debug(LOG_MESSAGE_MAP.get(result));
}
Now adding new result, message pairs just means inserting into the map. If you're using something like Spring you can do it in configuration and not touch the code.
Try:
result.trim().equals( "no_questions_by_user" )
Did you see "no_questions_by_user" in a debbugger ?
You can try to trim it before the test, as spaces are hard to detect in debuggers.
Make sure there are no white spaces in the value of the "result" variable.
Before entering the if statements, you can do a print line like this one.
System.out.println("The Value of result variable is=\"" + result + "\"");
You might as well do this
if ( result != null && result.trim().equals( "no_questions_by_user" ) )
{
Log.d( "Post execute: " , "NOOOT OKKKK - no questions by user so far" );
}
I advise you to use some static variables to store your strings, so you avoid typing errors.
Related
How to avoid multiple if else block so that the code does not smell?
There are a lot of if-else statements in my code what is the best way that I can avoid so many if-else statements. Below is the code snippet. Now again I need to check if WWW-Authenticate header returns value signature_invalid then I need to log and return a different error message and if WWW-Authenticate header returns value token_exppured then I need to log a different error message which will again add 2 more ifs. Can anyone Help me how can I avoid this?? if (e.getRawStatusCode() == NOT_FOUND) { logger.log( log, LogLevel.ERROR, MISSING_VALID_ID_ERROR_MSG + " : " + e.toString(), viewRequest); String errorDetails = createNotFoundDetails(appl, transactionId); updateIdentifier(rcvLog, true, request, identifier); return createErrorViewResponseReply(MISSING_VALID_ID_ERROR_MSG, errorDetails); } else if (e.getRawStatusCode() == UNAUTHORIZED) { logger.log( log, LogLevel.ERROR, UNABLE_TO_REACH_ERROR_MSG + " : " + e.toString(), viewRequest); if (e.getResponseHeaders() != null && e.getResponseHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE != null)) { logger.log( log, LogLevel.ERROR, INVALID_TOKEN_ERROR_MSG + " : " + e.getResponseHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE), viewRequest); } updateIdentifier(rcvLog, false, request, identifier); return createErrorViewResponseReply( UNABLE_TO_REACH_ERROR_MSG, INVALID_TOKEN_ERROR_DETAILS); }
The basic approaches one can take with this is: Create a class hierarchy with a factory to instantiate the right instance to respond to the action Do the same but in short hand with Enums Use a map of this::method() and call your methods that do the work for you For your case, since you can't really control the types of code an API sends you, and a factory method may be overkill, a map approach may be best: map.put(NOT_FOUND, this::methodA); map.put(UNAUTHORIZED, this::methodB); map.put(OTHER, this::methodC); map.computeIfAbsent( e.getRawStatusCode(), (e, rc, req, id) -> {/** NOTHING */} ).apply(e, rcvLog, request, identifier); computeIfAbsent() allows you to handle the unhandled case with basically a no-op.
Getting NMEA DATA in android
The current issue that I'm getting is that the OnNmeaListener is not returning the correct data from the NMEA using the GpsStatus.Listener therefore I tried the GNSS Status for the peace of mind, it ended up returning gibberish data , so I had to revert back to GpsStatus Listener. I also prior to using OnNmeaListener tried GpsStatus.NmeaListner and when used tried to add it to the GpsStatus Listener it would show up as an error and suggested that i typecast it to OnNmeaListener, when this is done and the app is built and all and then executed from the app, it would crash and then not work at all, and this is why i shifted to OnNmeaListener in the first place. Now to its credit the OnNmeaListener works just fine and doesn't crash at all, but the data it gives out is not at all accurate, I thought maybe this might have to be some sort of fault/error on the device side, I then proceeded to test it on two devices with different API levels of 25 and 28, On the the 25 Level device it just did not give half of the data whereas on the 28 level device the data is full but not accurate and correct. This is the method that I'm currently using: OnNmeaMessageListener nmeaMessageListener = new OnNmeaMessageListener () { #Override public void onNmeaMessage(String nmea , long timestamp) { if (trackStarted == true && trackPaused == false) { if (nmea.startsWith ( "$GPGGA" ) || nmea.startsWith ( "$GPRMC" )) { //Log.d("TrackManagerService","NMEA:" + nmea); try { // out.write(nmea.getBytes()); if (continuesMode) { dataOut.write ( nmea.getBytes () ); bufferedNMEALines++; if (bufferedNMEALines >= 10) { flushContinuesTrack (); //dataOut.reset(); bufferedNMEALines = 0; } } else { outCompressed.write ( nmea.getBytes () ); } // Log.d("TrackManagerService","NMEA:" + nmea); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace (); } if (nmea.startsWith ( "$GPGGA" )) { String[] nmeaSplit = nmea.split ( "," ); if (nmeaSplit.length > 10) { if (nmeaSplit[9].length () > 0) { try { mslAltitude = Float.parseFloat ( nmeaSplit[9] ); } catch (NumberFormatException ex) { mslAltitude = 0; } } else { mslAltitude = 0.0f; } } } } //if (markStarted && hasFix() && nmea.startsWith("$GPGGA")) { if (markStarted && hasFix () && nmea.startsWith ( "$GPRMC" )) { markProgress++; trackListener.onMarkProgress ( markProgress ); if (markProgress >= markMax) { stopMark (); } } } } }; And this is the output it gives when called: $Start,082719,260220; $GPGGA,082721.42,2654.2979,N,08056.6065,E,0,100.000,0.000,M,M,0,*44 $GPRMC,082721.42,V,2654.2979,N,08056.6065,E,0.000,0.000,260220,E,N*01 $GPGGA,082722.41,2654.2979,N,08056.6065,E,0,100.000,0.000,M,M,0,*44 $GPRMC,082722.41,V,2654.2979,N,08056.6065,E,0.000,0.000,260220,E,N*01 $End,082802,260220; $Start,082804,260220; $GPGGA,082837.42,2654.2979,N,08056.6065,E,0,100.000,0.000,M,M,0,*4C $GPRMC,082837.42,V,2654.2979,N,08056.6065,E,0.000,0.000,260220,E,N*09 $GPGGA,082838.42,2654.2979,N,08056.6065,E,0,100.000,0.000,M,M,0,*43 $GPGGA,082840.42,2654.2979,N,08056.6065,E,0,100.000,0.000,M,M,0,*4C $End,082841,260220; $Start,082921,260220; $GPGGA,082923.40,2654.2982,N,08056.6059,E,0,100.000,0.000,M,M,0,*41 $GPRMC,082923.40,V,2654.2982,N,08056.6059,E,0.000,0.000,260220,E,N*04 $GPGGA,082924.40,2654.2982,N,08056.6059,E,0,100.000,0.000,M,M,0,*46 $GPRMC,082945.40,V,2654.2982,N,08056.6059,E,0.000,0.000,260220,E,N*04 $End,082945,260220; And this is the output when called using GNSS listener: $Start,080450,260220;������������������������������������������������������������������������������������������������������������������������������������������������������������������ Any Sort of way to make this works? [EDIT] This is the response from an iOS device, which was accepted by the sever: $Start,150403,250220; $GPGGA,150403.69,2654.29986954,N,8056.60312653,E,1,00,0.0,0.0,0,0.0,0,0.0,0000*42; $GPRMC,150743.99,A,2654.29986954,N,8056.60260391,E,0.0,0.0,250220,0.0,E,A*5; $GPRMC,150844.26,A,2654.29986954,N,8056.60260391,E,0.0,0.0,250220,0.0,E,A*9; $GPRMC,150937.91,A,2654.30012894,N,8056.60312653,E,0.0,0.0,250220,0.0,E,A*e; $GPGGA,150945.04,2654.30429840,N,8056.60781097,E,1,00,0.0,0.0,0,0.0,0000*42; $GPRMC,150952.01,A,2654.29921722,N,8056.60364532,E,0.0,0.0,250220,0.0,E,A*2; $End,150953,250220; $GPGGA,150953.00,2654.29921722,N,8056.60364532,E,1,00,0.0,0.0,0,0.0,0000*42; $GPRMC,150953.00,A,2654.29921722,N,8056.60364532,E,0.0,0.0,250220,0.0,E,A*2; Now, I DO NOT have the faintest idea how this works on an iOS device,(a Senior of mine worked on that and gave me this data) but somehow it worked on that and when the same logic was implemented on Android and the data was uploaded to the server it wouldn't accept it, whereas when the iOS data was manipulated in any sort of way ( removing lines, addlines, removing semi-colons, commas,etc.) it would somehow still work.
NoraUI - "Cannot infer Type argument" error using Result.Warning<> in a custom step
I need to raise a warning during one of my scenario but i don't stop to have this error appearing : "Cannot infer type arguments for Result.Warning<>" I actually tried to raise the Warning the same way i was raising Failure until now : new Result.Warning<>(targetKey, Messages.format(TaroMessages.WARNING_RESOURCES_VALUE_DIFFERENCE_AFTER_REAFFECTATION, existing_value, new_value), true, oscarAccesClientPage.getCallBack()); The custom step i am using it inside is the following : I'm trying to go over a list of Element and checking that the existing value of them is the same or not as the one saved before. protected void checkXyResourcesValue(Integer xyIterator, List<WebElement> elements, String keyParameter) throws TechnicalException, FailureException { try { Integer resIterator = 1; for(WebElement element : elements) { String targetKey = "XY" + xyIterator + "RES" + resIterator + keyParameter; String new_value = element.getAttribute(VALUE) != null ? element.getAttribute(VALUE) : element.getText(); String existing_value = Context.getValue(targetKey) != null ? Context.getValue(targetKey) : targetKey; if (new_value != existing_value) { new Result.Warning<>(targetKey, Messages.format(TaroMessages.WARNING_RESOURCES_VALUE_DIFFERENCE_AFTER_REAFFECTATION, existing_value, new_value), true, oscarAccesClientPage.getCallBack()); } resIterator++; } } catch (Exception e) { new Result.Failure<>(e.getMessage(), Messages.format(TaroMessages.FAIL_MESSAGE_ACCES_CLIENT_XY_CHECK_RESOURCES_VALUE, keyParameter, xyIterator), true, oscarAccesClientPage.getCallBack()); } } For the method to check and saved value I actually inspired myself for the piece of code from NoraUI to save a value on Context or read it from. I'm using Eclipse Luna 4.4.2 and i try to compile using JDK1.8.0_131. It may be more related to me not knowing how this work in Java than a real problem so thank you in advance for your help or insights. Don't hesitate to ask if you need more information on the piece of code or the context.
new Result.Warning<>(targetKey, Messages.format(TaroMessages.WARNING_RESOURCES_VALUE_DIFFERENCE_AFTER_REAFFECTATION, existing_value, new_value), true, 0); use 0 if you do not use any Model (data serialized) or use id of your Object in the serial.
How to solve lua errors: "attempt to index ? (a nil value)" [duplicate]
This question already has an answer here: Attempt to index local 'v' (a nil value) (1 answer) Closed 5 years ago. There has been a lot of post about this kind of error and most people say it is related to table and array indexing problems. But I am not using tables at all, I am just trying to call a library function I made and I get this error. Here is the lua script called from java: String script = new String ( "function event_touch ( )" + " pb.open_form ('view_monster');" + " print ('I ran the lua script');" + "end"); PBLUAengine.run_script(script, "event_touch"); This gives me the following error when trapping the exception: "function event_touch ( ) pb.open_form ('view_monster'); print ('I ran the lua script');end:1 attempt to index ? (a nil value)" The run_script() function calls the script like this( I am using luaj): public static LuaValue run_script ( String script ) { try { LuaValue chunk = s_globals.load( script ); return chunk.call(); } catch ( Exception e) { Gdx.app.error ("PBLUAengine.run_script()", e.getMessage() ); } return null; } The library method goes like this and the same piece of code works when called from java: static class open_form extends OneArgFunction { public LuaValue call (LuaValue formname) { String tmpstr = (String ) CoerceLuaToJava.coerce(formname, java.lang.String.class ); try { PBscreen_game.hide_subscreen(PBscreen_game.MENU_SUBS); PBscreen_game.show_subscreen ( PBscreen_game.FORM_SUBS); PBsubscreen_form.open_form ( new PBform_regular ( tmpstr ) ); } catch (Exception e) { Gdx.app.error("PBLUAlibrary.open_form", e.getMessage()); } return valueOf ( 0 ); } } It basically convert the lua parameter to string, create a new from and pass in parameter the string. The declaration of the library functions goes like this: public LuaValue call( LuaValue modname, LuaValue env ) { LuaValue library = tableOf(); library.set( "open_form", new open_form() ); library.set( "open_system_form", new open_system_form() ); env.set( "pb", library ); return library; } Which could be the only "table" I can see in the whole system. This is generally used link the right class with the right function name. Anybody have an idea?
most people say it is related to table and array indexing problems It's related to table and array indexing. If you try to index an object and that object is nil, you'll get that error: I am not using tables at all [..] Here is the lua script: pb.open_form pb is being indexed. It's probably nil.
I seems that I solved the problem by adding a require line to include the library. So the new script is: String script = new String ( "require 'com.lariennalibrary.pixelboard.library.PBLUAlibrary'" + "function event_touch ( )" + " pb.open_form ('view_monster');" + " print ('I ran the next button lua script');" + "end"); It ask to include my library class which will add all the "pb.*" functions. I probably deleted the line by error, or managed to make it work somehow without it. Since this library will be required by all script, I might append it by default before each script I try to run. Thanks Again
Create a Spooled File from Java with a specified Job name on iSeries
Is there a way to specifiy the JOB name when creating a spooled file? So that my created s.f. doesn't have the default "QPRTJOB". My method that creates a spooled file with the default QPRTJOB job: public static SpooledFile createSpoolFile( com.ibm.as400.access.AS400 as, PrinterFile pPrinterFile, OutputQueue outq, String msg ) { SpooledFile result = null; try { PrintParameterList parms = new PrintParameterList(); // create a PrintParameterList with the values that we want // to override from the default printer file...we will override // the output queue and the copies value. parms.setParameter( PrintObject.ATTR_PRINTER_FILE, pPrinterFile.getPath() ); parms.setParameter( PrintObject.ATTR_JOBUSER, AS400.getUser().getUserProfileName() ); parms.setParameter( PrintObject.ATTR_JOBNAME, "NASAOBRJVA" ); parms.setParameter( PrintObject.ATTR_OUTPUT_QUEUE, outq.getPath() ); parms.setParameter( PrintObject.ATTR_CHAR_ID, "*SYSVAL" ); SpooledFileOutputStream spool = new SpooledFileOutputStream( as, parms, pPrinterFile, outq ); SCS5256Writer scsWtr = new SCS5256Writer( spool, pPrinterFile.getSystem().getCcsid(), pPrinterFile.getSystem() ); String[] redovi = msg.split( "\n" ); for ( int i = 0; i < redovi.length; i++ ) { if (redovi[i].equals( "" ) || redovi[i].equals( " " )) { continue; } scsWtr.write( redovi[i].trim() ); if (i < redovi.length - 1) { scsWtr.newLine(); } } scsWtr.close(); result = spool.getSpooledFile(); System.out.println("Spool is in Job: " + result.getJobNumber() + "/" + result.getJobUser() + "/" + result.getJobName()); } catch ( Exception e ) { LOG.error( e ); } return result; }
ATTR_JOBUSER and ATTR_JOBNAME are read-only attributes for a spooled file. I've noticed that whenever my Java programs talk to the AS/400--even those that are running natively on the AS/400--they talk to host server jobs and not necessarily the job that submitted the Java call. In this case, you are talking to a print server job on the 400 and all of your spooled files will get a QPRTJOB job name. An elaborate work-around would be to have your Java program submit a new job named NASAOBRJVA with a command to call some simple RPG program with the message text as a parameter. That's probably a lot of effort for a job name on a spooled file, but you know your project enough to know if it's worth that effort.
Job, user and job number are assigned by the system and cannot be changed. To the best of my knowledge anyway.