Error on Toast.LENGTH_SHORT.show(); - show

new to the forum and to Android. Jet I am super starting and this forum has already been a great help.
Since I couldn't find a solution to my problem on the net, here it goes. It basically displays a Toast message:
private void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.listViewSettings);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> paret, View viewClicked, int position, long id) {
TextView textView = (TextView) viewClicked;
String message = "You clicked #" + position + ", which is string: " + textView.getText().toString();
Toast.makeText(Configurations.this, message, Toast.LENGTH_SHORT.show();
}
});
}
I am getting two errors from this line:
Toast.makeText(Configurations.this, message, Toast.LENGTH_SHORT.show();
Cannot invoke show() on the primitive type int
Syntax error, insert ")" to complete Expression
Any ideas why ? I have used this expression just like that again with no errors...
Thanks everyone !

Its really simple. You forgot a ) after Toast.LENGTH_SHORT ( happens to me too ;) ). So you are calling the method show() on Toast.LENGTH_SHORT which is an integer. So your code will look like:
Toast.makeText(Configurations.this, message, Toast.LENGTH_SHORT).show();
Hope I could help you!

Related

MRTK and Grip Press

I'm using MRTK 2.3.0 trying to catch a "Grip Press" event from the Mixed Reality motion controller.
I've setup the Input Action in the MRTK Toolkit in the Hierarchy of Unity. I've also assigned the action to the controller's grip button in the Controller Definitions. I'm using the following code and made sure the Grip variable is assigned to the Grip Press event. Nothing happens... I'm able to catch touchpad and joystick, menu button press, but not Grip? Why?
According to this documentation: https://microsoft.github.io/MixedRealityToolkit-Unity/Documentation/MixedRealityConfigurationGuide.html the Grip should be a "float" as it's designed as single axis (I wonder why, since it's a button and not a trigger...). However, I'm trying to catch the event where I can... not working...
Anyone understand what the heck I'm trying to say here? (sorry, the code below also includes other events that I can catch without a hickup).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit;
public class TestInput : MonoBehaviour, IMixedRealityBaseInputHandler,
IMixedRealityInputHandler<Vector2>, IMixedRealityInputHandler
{
public MixedRealityInputAction Trigger, Grip, Scroll, Swipe, Joystick, DPad, TouchPadClicked, TouchPadTouched, MenuPressed;
public MixedRealityInputAction DPadUp, DPadDown, DPadLeft, DPadRight, JoystickUp, JoystickDown, JoystickLeft, JoystickRight;
private bool TouchpadPressed, MenuButtonPressed, GrabPressed, TouchDialogPadPressed, TouchpadClicked, Thouchpadtouched,
ThumbstickActive, ThumbstickPressed, VRManipulationStarted, ScrubStarted, PlayPause = false;
private void OnEnable()
{
IMixedRealityInputSystem inputSystem;
if (MixedRealityServiceRegistry.TryGetService<IMixedRealityInputSystem>(out inputSystem))
{
inputSystem?.RegisterHandler<IMixedRealityBaseInputHandler>(this);
inputSystem?.RegisterHandler<IMixedRealityInputHandler<Vector2>>(this);
inputSystem?.RegisterHandler<IMixedRealityInputHandler>(this);
inputSystem?.RegisterHandler<IMixedRealityInputHandler<float>>(this);
}
}
private void OnDisable()
{
IMixedRealityInputSystem inputSystem;
if (MixedRealityServiceRegistry.TryGetService<IMixedRealityInputSystem>(out inputSystem))
{
inputSystem?.UnregisterHandler<IMixedRealityBaseInputHandler>(this);
inputSystem?.UnregisterHandler<IMixedRealityInputHandler<Vector2>>(this);
inputSystem?.UnregisterHandler<IMixedRealityInputHandler>(this);
inputSystem?.UnregisterHandler<IMixedRealityInputHandler<float>>(this);
}
}
public void OnInputChanged(InputEventData<Vector2> ed)
{
Debug.Log("InputChanged");
if (ed.MixedRealityInputAction == DPad)
{
Debug.Log("Touched Touchpad at:" + ed.InputData.x.ToString() + "," + ed.InputData.y.ToString());
}
if (ed.MixedRealityInputAction == Joystick)
{
Debug.Log("Touched Joystick at:" + ed.InputData.x.ToString() + "," + ed.InputData.y.ToString());
}
}
public void OnInputChanged(InputEventData ed)
{
if (ed.MixedRealityInputAction == MenuPressed)
{
Debug.Log("Menu button pressed");
//ActionText.text = "Grab pressed";
}
}
public void OnInputChanged(InputEventData<float> ed)
{
Debug.Log("Float Changed");
if (ed.MixedRealityInputAction == Grip)
Debug.Log("Grab Pressed");
}
Ok... I got this..... It's a BUG in MRTK.
I have 18 actions defined (when you have DPad left, up, down etc it goes by fast!).
When I try to assign my MixedRealityInputAction to an InputAction in the Inspector, when I try to select GrabPressed (which is the 18th action), I get
IndexOutOfRangeException: Index was outside the bounds of the array.
Microsoft.MixedReality.Toolkit.Input.Editor.InputActionPropertyDrawer.OnGUI
Therefore the action does not work....
I tried to use another InputAction instead and assign it to the grab button (I used Select in this case) and it works like a charm....
Beware....
Try
Input.GetAxisRaw(ControllerMappingLibrary.AXIS_11) > 0 || Input.GetAxisRaw(ControllerMappingLibrary.AXIS_12) > 0;
AXIS_11 is grip press for the left controller while 12 is for the right controller

how to catch minor errors?

I have a little ANTLR v4 grammer and I am implementing a visitor on it.
Lets say it is a simple calculator and every input must be terminated with a ";"
e.g. x=4+5;
If I do not put the ; at the end, then it is working too but I get a output the teminal.
line 1:56 missing ';' at '<EOF>'
Seems it can find the rule and more or less ignores the missing terminal ";".
I would prefer a strict error or an exception instead of this soft information.
The output is generated by the line
ParseTree tree = parser.input ()
Is there a way I can intensify the error-handling and check for that kind of error?
Yes, you can. Like you, I wanted a 100% perfect parse from user-submitted text and so created a strict error handler that prevents recovery from even simple errors.
The first step is in removing the default error listeners and adding your own STRICT error handler:
AntlrInputStream inputStream = new AntlrInputStream(stream);
BailLexer lexer = new BailLexer(inputStream); // TALK ABOUT THIS AT BOTTOM
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
LISBASICParser parser = new LISBASICParser(tokenStream);
parser.RemoveErrorListeners(); // UNHOOK ERROR HANDLER
parser.ErrorHandler = new StrictErrorStrategy(); // REPLACE WITH YOUR OWN
LISBASICParser.CalculationContext context = parser.calculation();
CalculationVisitor visitor = new CalculationVisitor();
visitor.VisitCalculation(context);
Here's my StrictErrorStrategy class. It inherits from the DefaultErrorStrategy class and overrides the two 'recovery' methods that are letting small errors like your semicolon error be recoverable:
public class StrictErrorStrategy : DefaultErrorStrategy
{
public override void Recover(Parser recognizer, RecognitionException e)
{
IToken token = recognizer.CurrentToken;
string message = string.Format("parse error at line {0}, position {1} right before {2} ", token.Line, token.Column, GetTokenErrorDisplay(token));
throw new Exception(message, e);
}
public override IToken RecoverInline(Parser recognizer)
{
IToken token = recognizer.CurrentToken;
string message = string.Format("parse error at line {0}, position {1} right before {2} ", token.Line, token.Column, GetTokenErrorDisplay(token));
throw new Exception(message, new InputMismatchException(recognizer));
}
public override void Sync(Parser recognizer) { }
}
Overriding these two methods allows you to stop (in this case with an exception that is caught elsewhere) on ANY parser error. And making the Sync method empty prevents the normal 're-sync after error' behavior from happening.
The final step is in catching all LEXER errors. You do this by creating a new class that inherits from your main lexer class; it overrides the Recover() method like so:
public class BailLexer : LISBASICLexer
{
public BailLexer(ICharStream input) : base(input) { }
public override void Recover(LexerNoViableAltException e)
{
string message = string.Format("lex error after token {0} at position {1}", _lasttoken.Text, e.StartIndex);
BasicEnvironment.SyntaxError = message;
BasicEnvironment.ErrorStartIndex = e.StartIndex;
throw new ParseCanceledException(BasicEnvironment.SyntaxError);
}
}
(Edit: In this code, BasicEnvironment is a high-level context object I used in the application to hold settings, errors, results, etc. So if you decide to use this, either do as another reader commented below, or substitute your own context/container.)
With this in place, even small errors during the lexing step will be caught as well. With these two overridden classes in place, the user of my app must supply absolutely perfect syntax to get a successful execution. There you go!
Because my ANTLR is in Java I add the answer here too. But it is the same idea as the accepted answer.
TempParser parser = new TempParser (tokens);
parser.removeErrorListeners ();
parser.addErrorListener (new BaseErrorListener ()
{
#Override
public void syntaxError (final Recognizer <?,?> recognizer, Object sym, int line, int pos, String msg, RecognitionException e)
{
throw new AssertionError ("ANTLR - syntax-error - line: " + line + ", position: " + pos + ", message: " + msg);
}
});

Selenium - Java - How to check button is enabled or not?

I have tried so many times isenabled property but it always return "true" as the button is disabled on the page but it still return "True"
Please suggest the workaround to handle this?
Here is the code:
public void OpenSearchPage_and_verifyaddtofavoriteslink() throws InterruptedException
{
try
{
driver.navigate().to(favouritepagelink);
driver.findElement(FavoritesCheckBoxSelectAll).click();
//verify condition if product exist on favorites page
if(driver.findElement(FavoritesDelConditionCheck).isEnabled())
{
System.out.println("Enter in condition");
}
else
{
System.out.println("Out of condition");
}
}
catch(Exception ex)
{
System.out.println("SearchPage not opened: " +ex.getMessage());
}
}
Suggestions:
There can two reasons for getting this issue:
i) Issue with object
ii) Issue with the property
I) Issue with object: We can ensure we are using the right object for the button
and refresh the object before performing the operation
ii) Issue with property: Please check if some other property other then enabled is indicating this behaviour by verifying the html code behaviour.
Problem resolved :)
I have used getattribute to get class name then apply condition based on class attribute and its working fine.
Thank you all for the help :)

How to tell IDEA/Studio that the null check has been done?

I'm developing with Android Studio/IntelliJ IDEA.
I have enabled the inspection check called "Constant conditions & exceptions" that shows a warning if I am risking a NPE, such as:
String foo = foo.bar(); // Foo#bar() is #nullable
if (foo.contains("bar")) { // I'm living dangerously
...
}
I have the following in my code:
String encoding = contentEncoding == null ? null : contentEncoding.getValue();
if (!TextUtils.isEmpty(encoding) && encoding.equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(entity.getContent());
} else {
inputStream = entity.getContent();
}
Here's the source code of TextUtils#isEmpty(String):
/**
* Returns true if the string is null or 0-length.
* #param str the string to be examined
* #return true if str is null or zero length
*/
public static boolean isEmpty(CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}
I'm not risking any NPE because TextUtils#isEmpty(String) would return true to a null pointer.
However I'm still getting the little Method invocation 'encoding.equalsIgnoreCase("gzip")' may produce 'java.lang.NullPointerException' warning, which can be annoying.
Is it possible to make this check smarter and ignore the NPE warning if there's already a null-check done?
You can look into the link that Peter Gromov mention in his answer.
Created some simple classes that resemble your setup:
A class with a method annotated with #Nullable:
The TextUtil class with it's isEmpty method:
And finally the main class calling the TextUtil#isEmpty:
Now if you enter the File -> Settings... and go to Inspections ->Constant conditions & exceptions part you can change the Configure Assert/Check Methods to cater for your isEmpty method:
Add a new IsNull check method:
Enter the TextUtil class, isEmpty method and CharSequence parameter:
This gives this Assert/Check Method Configuration window:
Press Ok and then Ok again to go back to the editor view and you'll see that the inspection disappeared:
You are actually telling IntelliJ that the isEmpty method is doing a null check on the str parameter.
You could use //noinspection ConstantConditions that will remove the NPE warning for the following line, like this:
String encoding = contentEncoding == null ? null : contentEncoding.getValue();
//noinspection ConstantConditions
if (!TextUtils.isEmpty(encoding) && encoding.equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(entity.getContent());
} else {
inputStream = entity.getContent();
}
You can use #SuppressWarnings("ConstantConditions") annotation.
#SuppressWarnings("ConstantConditions")
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int indexViewType) {
if (inflater == null) {
inflater = LayoutInflater.from(parent.getContext());
}
ItemViewProvider provider = getProviderByIndex(indexViewType);
provider.adapter = MultiTypeAdapter.this;
return provider.onCreateViewHolder(inflater, parent);
}
Select "TextUtils.isEmpty".
Right Click -> Show Context Actions -> Add Method Contract.
Enter "null -> true".
Save the configuration xml.
Please check the details here
See http://www.jetbrains.com/idea/webhelp/configuring-check-assert-methods.html for IDEA 12.
In IDEA 13 EAP, you can add method contract: http://youtrack.jetbrains.com/issue/IDEA-93372
Unfortunately marked as "right answer" solution is of date. But I found equivalent for me solution.
The new versions of IDE work correctly with static methods. So the example from the question won't throw warning anymore.
TextUtils#isEmpty(String);
public static boolean isEmpty(CharSequence str) {
// your checks
}

How do I get the Event.Complete event in a file upload to fire in Flash Builder

The file is getting uploaded properly and my ProgessEvent.Progress method is showing 100% complete, but my Event.Complete method does not fire. Do I have to send something specific back from the server? I am simply sending back a success message. I am not getting any errors.
I suppose I could just proceed when the progress method hits 100%. Shouldn't the Event.Complete method be firing after the data is sent and a response is received from the server?
**Update: I am getting an error with my Event.Complete method....
TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event#1277971f1 to flash.events.DataEvent.
* I fixed the problem by changing my onLoadComplete(event:DataEvent) method to onLoadComplete(event:Event). The error went away and I my method is now firing. I will answer my own question when the system allows me to.
Relative code follows:
fileRef = new FileReference();
fileRef.addEventListener(Event.SELECT, onFileSelected);
fileRef.addEventListener(Event.COMPLETE, onUploadComplete);
fileRef.addEventListener(ProgressEvent.PROGRESS,onUploadProgress);
fileRef.addEventListener(IOErrorEvent.IO_ERROR, onUploadError);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadError);
private function onUploadProgress(event:ProgressEvent):void {
status = ((event.bytesLoaded * 100) / event.bytesTotal).toString();
}
private function onUploadComplete(event:DataEvent): void {
status = "Complete";
}
private function onUploadError(event:Event):void {
if (event is IOErrorEvent) {
Alert.show((event as IOErrorEvent).text.toString());
} else if (event is SecurityErrorEvent) {
Alert.show((event as SecurityErrorEvent).text.toString());
} else {
status = "Unknown error";
}
}
I changed ...
private function onUploadComplete(event:DataEvent):void {
status = "Complete: "+event.toString();
}
To...
private function onUploadComplete(event:Event):void {
status = "Complete: "+event.toString();
}
I am guessing this is because I am not sending data back, only a simple xml block. Hope this helps someone else.