Error message doesn't display correctly - java

I'm trying to make dialog that will display an error message whenever I make wrong move in my scrabble game. So in Problem.java, I make it like this
class Problem
{
Problem(String s)
{
message = s;
}
}
So I write code to display the warning like this :
void displayProblem(Problem p)
{
JOptionPane.showMessageDialog(this,p, "WARNING!",JOptionPane.WARNING_MESSAGE);
}
I expect error message when I don't put tile something like this :
"no tiles placed"
just like what's in the code but it ended up like this :
What's wrong with my code anyway?

You either need to pass p.message to the dialog or override Problem's toString() method and return message there. What you're seeing is the output of standard toString(), i.e. class name + instance id.
Btw, you posted a lot of irrelevant code, which might make a lot of people want to either close the question or prevent them from trying to answer. When asking questions you should try and boil it down to the relevant parts, which in your case would be how you display the dialog and what the parameters look like. For more information, have a look here: https://stackoverflow.com/help/how-to-ask

Related

How can I get programatically any single Log generated by my App?

Any Android App produces Logs in the LogCat, even those not generated by developer's source code via Log.d, Log.i, Log.w and Log.e etc. etc. etc.. Perhaps Google Developers has some "automagic" thing for this, I don't know about that...
The point is I remember, years ago, I could somehow extend the class Application, override one or several of it's methods, and then:
Add my own code to process any single Log object generated by my
App in the LogCat
Do whatever I wanted with them (getting the label and the description strings, and then send them via mail, Slack etc., basically)
And then, calling super on that method and let the system do with that Log whatever Application by default does with it...
or something like that... if I recall correctly, I could do this with any log in my app's namespace. Or maybe it was just the crash handler? I can't remember...
It's been so long since I accomplished that (several years already!), so I don't remember how could I do that anymore... I search the internet like crazy trying to recall, but I am struggling to find it again... :-S
// ...public?? oO
[¿¿??] class MyApp extends Application [...] {
// [...]
#Override
public void whateverMethodItWasIDontRemember(params) {
// My coding stuff for the error reports
/* magic :D */
sendTheLogsMyWay();
// I bet this is important
super.whateverMethodItWasIDontRemember(params);
}
// [...]
}
I am about to launch the first Beta version of a new app, so I want beta testers to have a reliable way to send me LogCat's feed if anything has to be reported due to crashes, unexpected behaviour etc.
I mean, it would be ridiculous having to fill with CustomLogs every inch of source code for the beta version, when, in most cases, default logs are more than enough to see why it crashed (errors), or what optimization problems (usually warnings) might the Beta Tester have... not to mention that, if I forget to monitor something this way, the ridiculously big effort to log every single line of my code would be useless... oO
// -__- Mmm... perhaps extending Log itself
// would be more elegant...
import android.util.Log
public final class CustomLog {
public static void d(String label, String msg) {
// AKA My code to handle it
packItForNextErrorReport(label, msg);
Log.d(label, msg);
}
/*
* ... and so on with Log.i, w and e.
* ...I think you get the idea
*/
}

Method does nothing if called within an if, if called directly from on event it works

I`m building a discord bot with jda, made a method to use mXparser to get a math operation as an input from the chat e.g: /math 5+1
wrote everything to get the message, separate the arguments from the input on the chat, everything works until I put the code inside an IF statement that checks if it actually starts with "/math", the code inside it uses mXparser to calculate everything and send it back to chat.
Tried just about everything I could think of, taking all variables off the method, rewriting everything, I don`t get any errors either as stack trace or in the code editor, it just doesnt go through, tried just printing everything and it works fine as well, printing all the values on the console, everything seems to be right.
This part is where I check for the message, get the Strings and trim everything
public void onMessageReceived(MessageReceivedEvent event) {
this.messageReceived = event;
this.prefix = Main.prefix;
checkPrefix = messageReceived.getMessage().getContentRaw().split("\\s" + prefix);
mainArg = checkPrefix[0];
checkArgs = messageReceived.getMessage().getContentRaw().split(" ");
callAllCommands();
}
Here is the command to take the actual expression from the chat input calculate it and send it back.
private void mathCommand() {
mathexp = new Expression(checkArgs[1]);
messageReceived.getChannel().sendTyping().queue();
essageReceived.getChannel().sendMessage(Double.toString(mathexp.calculate())).queue();
}
This is inside the callAllCommands() method, that is how it is supposed to work, if the command on the chat is /math then the expression e.g: /math 1+1 it will send the result back, if I take off the IF statement it works just fine but then I can't check for the command. The other commands do work fine with the IF statement
if (mainArg.contentEquals(prefix + "math")) {
mathCommand();
}
I don't really get any errors, it just does not work, sorry if I missed something really simple, i`m not that experienced yet.

Find the code that this line is referring to?

This is a batch downloader for images on Flickr. I'm curious about how the program gets the original url, so looking through the source code (Favorites.java line 271) I see this, but I wasn't able to find what it's referring to.
String originalUrl = null;
try {
originalUrl = curPhoto.getOriginalUrl();
} catch (FlickrException e) {
// if the original url just isn't available, fine. no need
// to panic.
}
https://github.com/magnusvk/flickrfaves
I'm using Netbeans right now and it's not finding anything when I click on any of the Navigate > Go To buttons on curPhoto. I'd imagine there's an easy way to find the code that it's referring to, but I don't really know what to search on google to learn how to do it.
My question is, where can I find the code for curPhoto.getOriginalUrl() and how should I be finding things like this on my own?
Looks like they are using flickrj to interface with Flickr.
curPhoto is of type Photo, and if you look in the imports, Photo is imported as import com.aetrion.flickr.photos.Photo;. I did a google search for com.aetrion.flickr and it turned up that library.
The documentation for that function can be found here

Handling non-fatal errors in Java

I've written a program to aid the user in configuring 'mechs for a game. I'm dealing with loading the user's saved data. This data can (and some times does) become partially corrupt (either due to bugs on my side or due to changes in the game data/rules from upstream).
I need to be able to handle this corruption and load as much as possible. To be more specific, the contents of the save file are syntactically correct but semantically corrupt. I can safely parse the file and drop whatever entries that are not semantically OK.
Currently my data parser will just show a modal dialog with an appropriate warning message. However displaying the warning is not the job of the parser and I'm looking for a way of passing this information to the caller.
Some code to show approximately what is going on (in reality there is a bit more going on than this, but this highlights the problem):
class Parser{
public void parse(XMLNode aNode){
...
if(corrupted) {
JOptionPane.showMessageDialog(null, "Corrupted data found",
"error!", JOptionPane.WARNING_MESSAGE);
// Keep calm and carry on
}
}
}
class UserData{
static UserData loadFromFile(File aFile){
UserData data = new UserData();
Parser parser = new Parser();
XMLDoc doc = fromXml(aFile);
for(XMLNode entry : doc.allEntries()){
data.append(parser.parse(entry));
}
return data;
}
}
The thing here is that bar an IOException or a syntax error in the XML, loadFromFile will always succeed in loading something and this is the wanted behavior. Somehow I just need to pass the information of what (if anything) went wrong to the caller. I could return a Pair<UserData,String> but this doesn't look very pretty. Throwing an exception will not work in this case obviously.
Does any one have any ideas on how to solve this?
Depending on what you are trying to represent, you can use a class, like SQLWarning from the java.sql package. When you have a java.sql.Statement and call executeQuery you get a java.sql.ResultSet and you can then call getWarnings on the result set directly, or even on the statement itself.
You can use an enum, like RefUpdate.Result, from the JGit project. When you have a org.eclipse.jgit.api.Git you can create a FetchCommand, which will provide you with a FetchResult, which will provide you with a collection of TrackingRefUpdates, which will each contain a RefUpdate.Result enum, which can be one of:
FAST_FORWARD
FORCED
IO_FAILURE
LOCK_FAILURE
NEW
NO_CHANGE
NOT_ATTEMPTED
REJECTED
REJECTED_CURRENT_BRANCH
RENAMED
In your case, you could even use a boolean flag:
class UserData {
public boolean isCorrupt();
}
But since you mentioned there is a bit more than that going on in reality, it really depends on your model of "corrupt". However, you will probably have more options if you have a UserDataReader that you can instantiate, instead of a static utility method.

How should I display a validation error detected by an ICellEditorValidator?

I have a TableViewer with an ICellModifier which seems to work fine. I set an ICellEditorValidator on one of the cell editors, though, and I can't get it to behave the way I would like. Here's my abbreviated code:
cellEditors[1] = new TextCellEditor(table);
cellEditors[1].setValidator(new ICellEditorValidator() {
public String isValid(Object value) {
try {
Integer.parseInt((String) value);
return null;
} catch(NumberFormatException e) {
return "Not a valid integer";
}
}
});
It mostly works fine. However, there are two issues:
The modify method of the cell
modifier receives a null as the new
value if the validator returns an
error. I can code to handle this,
but it doesn't seem right. Null
could be a valid value, for example,
if the user's picking a background
color and they picked transparent.
(This is a general issue, not specific to this example.)
The validator's error message is
never displayed to the user. This
is the big problem. I could also
add an ICellEditorListener and
display a dialog from the
applyEditorValue method if the
last value was invalid. Is this the
"proper" way to do it?
By the way, for reasons beyond my control, I'm limited to the Eclipse 3.0 framework.
you can add a listener to your Editor:
cellEditors[1].addListener(
public void applyEditorValue() {
page.setErrorMessage(null);
}
public void cancelEditor() {
page.setErrorMessage(null);
}
public void editorValueChanged(boolean oldValidState,
boolean newValidState) {
page.setErrorMessage(editor.getErrorMessage());
}
With page being your current FormPage, this will display the errorMessage to the user.
Regarding the second issue, the string the validator's method isValid returns becomes the error message for the CellEditor owning that validator. You can retrieve that message with CellEditor.getErrorMessage.
It appears to me that the easiest way to show the error message is through a ICellEditorListener, as Sven suggests above. Maybe the tricky thing about this listener is that the cell editor is not passed as a parameter to any of its methods, so the assumption is that the listener knows which cell editor is talking to it.
If you want the dialog, the preference page or whatever object to implement the ICellEditorListener interface you have to be sure it knows the cell editor being edited.
However, if it's the cell editor itself which implements the interface it should have a way to properly carry the error message over into the dialog, the preference page or whatever. That's the currentForm page Scott is looking for.
One last thing worth noticing if you're using EditingSupport is that the value passed into the EditingSupport.setValue method is null when ICellEditorValidator.isValue returns an error message. Don't forget to check it out.

Categories

Resources