Facebook SDK Integration - LoadPicture Method ERROR - function

So hi to #ll this is my fist post/question on stackoverflow :D
I need help # following :
So i integrated the Facebook SDk sucessfully in my game but i´dont get the profile picture working ...
So i tryied it oldshool on Facebooks "Tutotial" Way and followed all steps to implement login functions and so on ...
I´ve downloaded the "friendsmash_start" Sample and implemented that Stuff ...
My Main Problem is i don´t get ahead with this problem and can´t figure out what i´m doing wrong so i´m hoping for help.
Here´s the complete Code from the MainMenu Script from the sample which is the only i´ve changed ... like in the tutorial ...
Unity shows me this Error -> "The name 'LoadPicture' does not exist in the current context ... so the errors are on these two parts of code :
"LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);" in the "OnLoggedIn" function
"LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);" in the "MyPictureCallback" function
I don´t understand it cause i searched myself in the script for this function "LoadPicture" and find nothing that was ... according to the "Tutorial" of facebook here :
https://developers.facebook.com/docs/games/unity/unity-tutorial?locale=de_DE
the function should be there cause they wrote there :
"Take a look at the LoadPicture method also in MainMenu.cs to see how we use the Unity WWW class to load the image returned by the graph API."
But i can´t find it :(
HOPE SOMEONE CAN HELP ME I DON´T GET IT ...
Have that problem unfortunately very long time ... thats enoying. :(
HERE`S THE FULL CODE OF MAINMENU.CS :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook.MiniJSON;
using System;
public class MainMenu : MonoBehaviour
{
// Inspector tunable members //
public Texture ButtonTexture;
public Texture PlayTexture; // Texture for main menu button icons
public Texture BragTexture;
public Texture ChallengeTexture;
public Texture StoreTexture;
public Texture FullScreenTexture;
public Texture FullScreenActiveTexture;
public Texture ResourcesTexture;
public Vector2 CanvasSize; // size of window on canvas
public Rect LoginButtonRect; // Position of login button
public Vector2 ResourcePos; // position of resource indicators (not used yet)
public Vector2 ButtonStartPos; // position of first button in main menu
public float ButtonScale; // size of main menu buttons
public float ButtonYGap; // gap between buttons in main menu
public float ChallengeDisplayTime; // Number of seconds the request sent message is displayed for
public Vector2 ButtonLogoOffset; // Offset determining positioning of logo on buttons
public float TournamentStep; // Spacing between tournament entries
public float MouseScrollStep = 40; // Amount score table moves with each step of the mouse wheel
public PaymentDialog paymentDialog;
public GUISkin MenuSkin;
public int CoinBalance;
public int NumLives;
public int NumBombs;
public Texture[] CelebTextures;
public string [] CelebNames;
// Private members //
private static MainMenu instance;
private static List<object> friends = null;
private static Dictionary<string, string> profile = null;
private static List<object> scores = null;
private static Dictionary<string, Texture> friendImages = new Dictionary<string, Texture>();
private Vector2 scrollPosition = Vector2.zero;
private bool haveUserPicture = false;
private float tournamentLength = 0;
private int tournamentWidth = 512;
private int mainMenuLevel = 0; // Level index of main menu
private string popupMessage;
private float popupTime;
private float popupDuration;
void Awake()
{
Util.Log("Awake");
paymentDialog = ((PaymentDialog)(GetComponent("PaymentDialog")));
// allow only one instance of the Main Menu
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
#if UNITY_WEBPLAYER
// Execute javascript in iframe to keep the player centred
string javaScript = #"
window.onresize = function() {
var unity = UnityObject2.instances[0].getUnity();
var unityDiv = document.getElementById(""unityPlayerEmbed"");
var width = window.innerWidth;
var height = window.innerHeight;
var appWidth = " + CanvasSize.x + #";
var appHeight = " + CanvasSize.y + #";
unity.style.width = appWidth + ""px"";
unity.style.height = appHeight + ""px"";
unityDiv.style.marginLeft = (width - appWidth)/2 + ""px"";
unityDiv.style.marginTop = (height - appHeight)/2 + ""px"";
unityDiv.style.marginRight = (width - appWidth)/2 + ""px"";
unityDiv.style.marginBottom = (height - appHeight)/2 + ""px"";
}
window.onresize(); // force it to resize now";
Application.ExternalCall(javaScript);
#endif
DontDestroyOnLoad(gameObject);
instance = this;
// Initialize FB SDK
FB.Init(SetInit, OnHideUnity);
}
private void SetInit()
{
Util.Log("SetInit");
enabled = true; // "enabled" is a property inherited from MonoBehaviour
if (FB.IsLoggedIn)
{
Util.Log("Already logged in");
OnLoggedIn();
}
}
private void OnHideUnity(bool isGameShown)
{
Util.Log("OnHideUnity");
if (!isGameShown)
{
// pause the game - we will need to hide
Time.timeScale = 0;
}
else
{
// start the game back up - we're getting focus again
Time.timeScale = 1;
}
}
private void QueryScores()
{
FB.API("/app/scores?fields=score,user.limit(20)", Facebook.HttpMethod.GET, ScoresCallback);
}
private int getScoreFromEntry(object obj)
{
Dictionary<string,object> entry = (Dictionary<string,object>) obj;
return Convert.ToInt32(entry["score"]);
}
void ScoresCallback(FBResult result)
{
Util.Log("ScoresCallback");
if (result.Error != null)
{
Util.LogError(result.Error);
return;
}
scores = new List<object>();
List<object> scoresList = Util.DeserializeScores(result.Text);
foreach(object score in scoresList)
{
var entry = (Dictionary<string,object>) score;
var user = (Dictionary<string,object>) entry["user"];
string userId = (string)user["id"];
if (string.Equals(userId,FB.UserId))
{
// This entry is the current player
int playerHighScore = getScoreFromEntry(entry);
Util.Log("Local players score on server is " + playerHighScore);
if (playerHighScore < GameStateManager.Score)
{
Util.Log("Locally overriding with just acquired score: " + GameStateManager.Score);
playerHighScore = GameStateManager.Score;
}
entry["score"] = playerHighScore.ToString();
GameStateManager.HighScore = playerHighScore;
}
scores.Add(entry);
if (!friendImages.ContainsKey(userId))
{
// We don't have this players image yet, request it now
LoadPictureAPI(Util.GetPictureURL(userId, 128, 128),pictureTexture =>
{
if (pictureTexture != null)
{
friendImages.Add(userId, pictureTexture);
}
});
}
}
// Now sort the entries based on score
scores.Sort(delegate(object firstObj,
object secondObj)
{
return -getScoreFromEntry(firstObj).CompareTo(getScoreFromEntry(secondObj));
}
);
}
void OnApplicationFocus( bool hasFocus )
{
Util.Log ("hasFocus " + (hasFocus ? "Y" : "N"));
}
// Convenience function to check if mouse/touch is the tournament area
private bool IsInTournamentArea (Vector2 p)
{
return p.x > Screen.width-tournamentWidth;
}
// Scroll the tournament view by some delta
private void ScrollTournament(float delta)
{
scrollPosition.y += delta;
if (scrollPosition.y > tournamentLength - Screen.height)
scrollPosition.y = tournamentLength - Screen.height;
if (scrollPosition.y < 0)
scrollPosition.y = 0;
}
// variables for keeping track of scrolling
private Vector2 mouseLastPos;
private bool mouseDragging = false;
void Update()
{
if(Input.touches.Length > 0)
{
Touch touch = Input.touches[0];
if (IsInTournamentArea (touch.position) && touch.phase == TouchPhase.Moved)
{
// dragging
ScrollTournament (touch.deltaPosition.y*3);
}
}
if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
ScrollTournament (MouseScrollStep);
}
else if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
ScrollTournament (-MouseScrollStep);
}
if (Input.GetMouseButton(0) && IsInTournamentArea(Input.mousePosition))
{
if (mouseDragging)
{
ScrollTournament (Input.mousePosition.y - mouseLastPos.y);
}
mouseLastPos = Input.mousePosition;
mouseDragging = true;
}
else
mouseDragging = false;
}
// Button drawing logic //
private Vector2 buttonPos; // Keeps track of where we've got to on the screen as we draw buttons
private void BeginButtons()
{
// start drawing buttons at the chosen start position
buttonPos = ButtonStartPos;
}
private bool DrawButton(string text, Texture texture)
{
// draw a single button and update our position
bool result = GUI.Button(new Rect (buttonPos.x,buttonPos.y, ButtonTexture.width * ButtonScale, ButtonTexture.height * ButtonScale),text,MenuSkin.GetStyle("menu_button"));
Util.DrawActualSizeTexture(ButtonLogoOffset*ButtonScale+buttonPos,texture,ButtonScale);
buttonPos.y += ButtonTexture.height*ButtonScale + ButtonYGap;
if (paymentDialog.DialogEnabled)
result = false;
return result;
}
void OnGUI()
{
GUI.skin = MenuSkin;
if (Application.loadedLevel != mainMenuLevel) return; // don't display anything except when in main menu
GUILayout.Box("", MenuSkin.GetStyle("panel_welcome"));
if (!FB.IsLoggedIn)
{
GUI.Label((new Rect(179, 11, 287, 160)), "Login to Facebook", MenuSkin.GetStyle("text_only"));
if (GUI.Button(LoginButtonRect, "", MenuSkin.GetStyle("button_login")))
{
FB.Login("email,publish_actions", LoginCallback);
}
}
if (FB.IsLoggedIn)
{
string panelText = "Welcome ";
panelText += (!string.IsNullOrEmpty(GameStateManager.Username)) ? string.Format("{0}!", GameStateManager.Username) : "Smasher!";
if (GameStateManager.UserTexture != null)
GUI.DrawTexture( (new Rect(8,10, 150, 150)), GameStateManager.UserTexture);
GUI.Label( (new Rect(179 , 11, 287, 160)), panelText, MenuSkin.GetStyle("text_only"));
}
string subTitle = "Let's smash some friends!";
if (GameStateManager.Score > 0)
{
subTitle = "Score: " + GameStateManager.Score.ToString();
}
if (!string.IsNullOrEmpty(subTitle))
{
GUI.Label( (new Rect(132, 28, 400, 160)), subTitle, MenuSkin.GetStyle("sub_title"));
}
BeginButtons();
if (DrawButton("Play",PlayTexture))
{
onPlayClicked();
}
if (FB.IsLoggedIn)
{
// Draw resources bar
Util.DrawActualSizeTexture(ResourcePos,ResourcesTexture);
Util.DrawSimpleText(ResourcePos + new Vector2(47,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",CoinBalance));
Util.DrawSimpleText(ResourcePos + new Vector2(137,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",NumBombs));
Util.DrawSimpleText(ResourcePos + new Vector2(227,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",NumLives));
}
#if UNITY_WEBPLAYER
if (Screen.fullScreen)
{
if (DrawButton("Full Screen",FullScreenActiveTexture))
SetFullscreenMode(false);
}
else
{
if (DrawButton("Full Screen",FullScreenTexture))
SetFullscreenMode(true);
}
#endif
DrawPopupMessage();
}
public void AddPopupMessage(string message, float duration)
{
popupMessage = message;
popupTime = Time.realtimeSinceStartup;
popupDuration = duration;
}
public void DrawPopupMessage()
{
if (popupTime != 0 && popupTime + popupDuration > Time.realtimeSinceStartup)
{
// Show message that we sent a request
Rect PopupRect = new Rect();
PopupRect.width = 800;
PopupRect.height = 100;
PopupRect.x = Screen.width / 2 - PopupRect.width / 2;
PopupRect.y = Screen.height / 2 - PopupRect.height / 2;
GUI.Box(PopupRect,"",MenuSkin.GetStyle("box"));
GUI.Label(PopupRect, popupMessage, MenuSkin.GetStyle("centred_text"));
}
}
void TournamentGui()
{
GUILayout.BeginArea(new Rect((Screen.width - 450),0,450,Screen.height));
// Title box
GUI.Box (new Rect(0, - scrollPosition.y, 100,200), "", MenuSkin.GetStyle("tournament_bar"));
GUI.Label (new Rect(121 , - scrollPosition.y, 100,200), "Tournament", MenuSkin.GetStyle("heading"));
Rect boxRect = new Rect();
if(scores != null)
{
var x = 0;
foreach(object scoreEntry in scores)
{
Dictionary<string,object> entry = (Dictionary<string,object>) scoreEntry;
Dictionary<string,object> user = (Dictionary<string,object>) entry["user"];
string name = ((string) user["name"]).Split(new char[]{' '})[0] + "\n";
string score = "Smashed: " + entry["score"];
boxRect = new Rect(0, 121+(TournamentStep*x)-scrollPosition.y , 100,128);
// Background box
GUI.Box(boxRect,"",MenuSkin.GetStyle("tournament_entry"));
// Text
GUI.Label (new Rect(24, 136 + (TournamentStep * x) - scrollPosition.y, 100,128), (x+1)+".", MenuSkin.GetStyle("tournament_position")); // Rank e.g. "1.""
GUI.Label (new Rect(250,145 + (TournamentStep * x) - scrollPosition.y, 300,100), name, MenuSkin.GetStyle("tournament_name")); // name
GUI.Label (new Rect(250,193 + (TournamentStep * x) - scrollPosition.y, 300,50), score, MenuSkin.GetStyle("tournament_score")); // score
Texture picture;
if (friendImages.TryGetValue((string) user["id"], out picture))
{
GUI.DrawTexture(new Rect(118,128+(TournamentStep*x)-scrollPosition.y,115,115), picture); // Profile picture
}
x++;
}
}
else GUI.Label (new Rect(180,270,512,200), "Loading...", MenuSkin.GetStyle("text_only"));
// Record length so we know how far we can scroll to
tournamentLength = boxRect.y + boxRect.height + scrollPosition.y;
GUILayout.EndArea();
}
// React to menu buttons //
private void onPlayClicked()
{
Util.Log("onPlayClicked");
if (friends != null && friends.Count > 0)
{
// Select a random friend and get their picture
Dictionary<string, string> friend = Util.RandomFriend(friends);
GameStateManager.FriendName = friend["first_name"];
GameStateManager.FriendID = friend["id"];
GameStateManager.CelebFriend = -1;
LoadPictureURL(friend["image_url"],FriendPictureCallback);
}
else
{
//We can't access friends
GameStateManager.CelebFriend = UnityEngine.Random.Range(0,CelebTextures.Length - 1);
GameStateManager.FriendName = CelebNames[GameStateManager.CelebFriend];
}
// Start the main game
Application.LoadLevel("GameStage");
GameStateManager.Instance.StartGame();
}
public void SetFullscreenMode (bool on)
{
if (on)
{
Screen.SetResolution (Screen.currentResolution.width, Screen.currentResolution.height, true);
}
else
{
Screen.SetResolution ((int)CanvasSize.x, (int)CanvasSize.y, false);
}
}
public static void FriendPictureCallback(Texture texture)
{
GameStateManager.FriendTexture = texture;
}
delegate void LoadPictureCallback (Texture texture);
IEnumerator LoadPictureEnumerator(string url, LoadPictureCallback callback)
{
WWW www = new WWW(url);
yield return www;
callback(www.texture);
}
void LoadPictureAPI (string url, LoadPictureCallback callback)
{
FB.API(url,Facebook.HttpMethod.GET,result =>
{
if (result.Error != null)
{
Util.LogError(result.Error);
return;
}
var imageUrl = Util.DeserializePictureURLString(result.Text);
StartCoroutine(LoadPictureEnumerator(imageUrl,callback));
});
}
void LoadPictureURL (string url, LoadPictureCallback callback)
{
StartCoroutine(LoadPictureEnumerator(url,callback));
}
void LoginCallback(FBResult result)
{
Util.Log("LoginCallback");
if (FB.IsLoggedIn)
{
OnLoggedIn();
}
}
void OnLoggedIn()
{
Util.Log("Logged in. ID: " + FB.UserId);
// Reqest player info and profile picture
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, APICallback);
LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);
}
void APICallback(FBResult result)
{
Util.Log("APICallback");
if (result.Error != null)
{
Util.LogError(result.Error);
// Let's just try again
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, APICallback);
return;
}
profile = Util.DeserializeJSONProfile(result.Text);
GameStateManager.Username = profile["first_name"];
friends = Util.DeserializeJSONFriends(result.Text);
}
void MyPictureCallback(Texture texture)
{
Util.Log("MyPictureCallback");
if (texture == null)
{
// Let's just try again
LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);
return;`
}
GameStateManager.UserTexture = texture;
}
}

change the word "LoadPicture" for "LoadPictureAPI".
For reference see:
https://github.com/fbsamples/friendsmash-unity/blob/master/friendsmash_payments_start/Assets/Scripts/MainMenu.cs

Related

How to show marker with text in map in codenameone

I am doing a sample on Map and in this i want to show marker along with text.
for that i used below code.
MapContainer mapContainer = new MapContainer("xxxxxxxxxxxxxxxxxxxxxx");
Coord coord = new Coord(latitude,longitude);
mapContainer.setCameraPosition(coord);
mapContainer.addMarker(EncodedImage.createFromImage(image,false), mapContainer.getCameraPosition(), "Text", "Text", null);
but this code helps me to displaying the marker but not along with the text. so if anyone have idea to display marker with text please suggest/help me to achieve this.
Thanks in Advance.
here is the code using MapContainer and MapLayout(Below Answer)..
if(BrowserComponent.isNativeBrowserSupported()) {
MapContainer mc = new MapContainer("AIzaSyDLIu4RfdXVQPvRqOYLP6N8ocCQpPNqtIk");
mapDemo.add(mc);
Container markers = new Container();
markers.setLayout(new MapLayout(mc, markers));
mapDemo.add(markers);
Coord moscone = new Coord(37.7831, -122.401558);
Button mosconeButton = new Button("");
FontImage.setMaterialIcon(mosconeButton, FontImage.MATERIAL_PLACE);
markers.add(moscone, mosconeButton);
Coord moscone1 = new Coord(36.6139, -120.2090);
Button mosconeButton1 = new Button("");
FontImage.setMaterialIcon(mosconeButton1, FontImage.MATERIAL_PLACE);
markers.add(moscone1, mosconeButton1);
mc.zoom(moscone1, 5);
} else {
// iOS Screenshot process...
mapDemo.add(new Label("Loading, please wait...."));
}
This is a revised answer see the original answer for reference below:
With the new update this should work better, you will need to update the cn1lib for Google Maps too if you have an older version. We've also revised the MapLayout class again and added some features such as alignment:
public class MapLayout extends Layout implements MapListener {
private static final String COORD_KEY = "$coord";
private static final String POINT_KEY = "$point";
private static final String HORIZONTAL_ALIGNMENT = "$align";
private static final String VERTICAL_ALIGNMENT = "$valign";
private final MapContainer map;
private final Container actual;
private boolean inUpdate;
private Runnable nextUpdate;
private int updateCounter;
public static enum HALIGN {
LEFT {
#Override
int convert(int x, int width) {
return x;
}
},
CENTER {
#Override
int convert(int x, int width) {
return x - width / 2;
}
},
RIGHT {
#Override
int convert(int x, int width) {
return x - width;
}
};
abstract int convert(int x, int width);
}
public static enum VALIGN {
TOP {
#Override
int convert(int y, int height) {
return y;
}
},
MIDDLE {
#Override
int convert(int y, int height) {
return y + height / 2;
}
},
BOTTOM {
#Override
int convert(int y, int height) {
return y + height;
}
};
abstract int convert(int y, int height);
}
public MapLayout(MapContainer map, Container actual) {
this.map = map;
this.actual = actual;
map.addMapListener(this);
}
#Override
public void addLayoutComponent(Object value, Component comp, Container c) {
comp.putClientProperty(COORD_KEY, (Coord) value);
}
#Override
public boolean isConstraintTracking() {
return true;
}
#Override
public Object getComponentConstraint(Component comp) {
return comp.getClientProperty(COORD_KEY);
}
#Override
public boolean isOverlapSupported() {
return true;
}
public static void setHorizontalAlignment(Component cmp, HALIGN a) {
cmp.putClientProperty(HORIZONTAL_ALIGNMENT, a);
}
public static void setVerticalAlignment(Component cmp, VALIGN a) {
cmp.putClientProperty(VERTICAL_ALIGNMENT, a);
}
#Override
public void layoutContainer(Container parent) {
int parentX = 0;
int parentY = 0;
for (Component current : parent) {
Coord crd = (Coord) current.getClientProperty(COORD_KEY);
Point p = (Point) current.getClientProperty(POINT_KEY);
if (p == null) {
p = map.getScreenCoordinate(crd);
current.putClientProperty(POINT_KEY, p);
}
HALIGN h = (HALIGN)current.getClientProperty(HORIZONTAL_ALIGNMENT);
if(h == null) {
h = HALIGN.LEFT;
}
VALIGN v = (VALIGN)current.getClientProperty(VERTICAL_ALIGNMENT);
if(v == null) {
v = VALIGN.TOP;
}
current.setSize(current.getPreferredSize());
current.setX(h.convert(p.getX() - parentX, current.getWidth()));
current.setY(v.convert(p.getY() - parentY, current.getHeight()));
}
}
#Override
public Dimension getPreferredSize(Container parent) {
return new Dimension(100, 100);
}
#Override
public void mapPositionUpdated(Component source, int zoom, Coord center) {
Runnable r = new Runnable() {
public void run() {
inUpdate = true;
try {
List<Coord> coords = new ArrayList<>();
List<Component> cmps = new ArrayList<>();
int len = actual.getComponentCount();
for (Component current : actual) {
Coord crd = (Coord) current.getClientProperty(COORD_KEY);
coords.add(crd);
cmps.add(current);
}
int startingUpdateCounter = ++updateCounter;
List<Point> points = map.getScreenCoordinates(coords);
if (startingUpdateCounter != updateCounter || len != points.size()) {
// Another update must have run while we were waiting for the bounding box.
// in which case, that update would be more recent than this one.
return;
}
for (int i=0; i<len; i++) {
Component current = cmps.get(i);
Point p = points.get(i);
current.putClientProperty(POINT_KEY, p);
}
actual.setShouldCalcPreferredSize(true);
actual.revalidate();
if (nextUpdate != null) {
Runnable nex = nextUpdate;
nextUpdate = null;
callSerially(nex);
}
} finally {
inUpdate = false;
}
}
};
if (inUpdate) {
nextUpdate = r;
} else {
nextUpdate = null;
callSerially(r);
}
}
}
Original Answer:
The marker will show the text when you tap on it. If you want things to appear differently you can just use any component and place it on top of the map. The upcoming Uber tutorial will cover this in depth but I explained the basic system in this blog post: https://www.codenameone.com/blog/tip-map-layout-manager.html

Gibberish in Google Maps in Codename One

Gibberish in Google Maps
I am working on an IOS app in Codenameone (in Intellij), and programed an interface for users to use google maps within my app. However, when they start to search for places or navigate in street view, I receive a ton of gibberish on my iOS simulator (See screenshot below). Has anyone run into this issue and if so, have you found as shown?
public class PetBnBApp {
private static final String HTML_API_KEY = "AIzaSyBWeRU02YUYPdwRuMFyTKIXUbHjq6e35Gw";
private Form current;
private Resources theme;
private Form home;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature
try {
Resources theme = Resources.openLayered("/theme");
UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
Display.getInstance().setCommandBehavior(Display.COMMAND_BEHAVIOR_SIDE_NAVIGATION);
UIManager.getInstance().getLookAndFeel().setMenuBarClass(SideMenuBar.class);
} catch (IOException e) {
e.printStackTrace();
}
}
MapContainer.MapObject sydney;
public void start() {
if (current != null) {
current.show();
return;
}
Form maps = new Form("Native Maps Test");
maps.setLayout(new BorderLayout());
final MapContainer cnt = new MapContainer(HTML_API_KEY);
//final MapContainer cnt = new MapContainer();
//42.3040009,-71.5040407
cnt.setCameraPosition(new Coord(42.3040009, -71.5040407));//this breaks the code //because the Google map is not loaded yet
cnt.addMapListener(new MapListener() {
#Override
public void mapPositionUpdated(Component source, int zoom, Coord center) {
System.out.println("Map position updated: zoom="+zoom+", Center="+center);
}
});
cnt.addLongPressListener(e->{
System.out.println("Long press");
ToastBar.showMessage("Received longPress at "+e.getX()+", "+e.getY(), FontImage.MATERIAL_3D_ROTATION);
});
cnt.addTapListener(e->{
ToastBar.showMessage("Received tap at "+e.getX()+", "+e.getY(), FontImage.MATERIAL_3D_ROTATION);
});
int maxZoom = cnt.getMaxZoom();
System.out.println("Max zoom is "+maxZoom);
Button btnMoveCamera = new Button("Move Camera");
btnMoveCamera.addActionListener(e->{
cnt.setCameraPosition(new Coord(-33.867, 151.206));
});
Style s = new Style();
s.setFgColor(0xff0000);
s.setBgTransparency(0);
FontImage markerImg = FontImage.createMaterial(FontImage.MATERIAL_PLACE, s, 3);
Button btnAddMarker = new Button("Add Marker");
btnAddMarker.addActionListener(e->{
cnt.setCameraPosition(new Coord(41.889, -87.622));
cnt.addMarker(EncodedImage.createFromImage(markerImg, false), cnt.getCameraPosition(), "Hi marker", "Optional long description", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Bounding box is "+cnt.getBoundingBox());
ToastBar.showMessage("You clicked the marker", FontImage.MATERIAL_PLACE);
}
});
});
Button btnAddPath = new Button("Add Path");
btnAddPath.addActionListener(e->{
cnt.addPath(
cnt.getCameraPosition(),
new Coord(-33.866, 151.195), // Sydney
new Coord(-18.142, 178.431), // Fiji
new Coord(21.291, -157.821), // Hawaii
new Coord(37.423, -122.091) // Mountain View
);
});
Button panTo = new Button("Pan To");
panTo.addActionListener(e->{
//bounds.extend(new google.maps.LatLng('66.057878', '-22.579047')); // Iceland
//bounds.extend(new google.maps.LatLng('37.961952', '43.878878')); // Turkey
Coord c1 = new Coord(42.3040432, -71.5045936);
Coord c2 = new Coord(49.2577142, -123.1941149);
//Coord center = new Coord(c1.getLatitude()/2 + c2.getLatitude() / 2, c1.getLongitude()/2 + c2.getLongitude()/2 );
Coord center = new Coord(49.1110928, -122.9414646);
float zoom = cnt.getZoom();
boolean[] finished = new boolean[1];
cnt.addMapListener(new MapListener() {
#Override
public void mapPositionUpdated(Component source, int zoom, Coord c) {
if (Math.abs(c.getLatitude() - center.getLatitude()) > .001 || Math.abs(c.getLongitude() - center.getLongitude()) > .001) {
return;
}
finished[0] = true;
synchronized(finished) {
final MapListener fthis = this;
Display.getInstance().callSerially(()->{
cnt.removeMapListener(fthis);
});
finished.notify();
}
}
});
cnt.zoom(center, (int)zoom);
while (!finished[0]) {
Display.getInstance().invokeAndBlock(()->{
while (!finished[0]) {
Util.wait(finished, 100);
}
});
}
BoundingBox box = cnt.getBoundingBox();
if (!box.contains(c1) || !box.contains(c2)) {
while (!box.contains(c1) || !box.contains(c2)) {
if (!box.contains(c1)) {
System.out.println("Box "+box+" doesn't contain "+c1);
}
if (!box.contains(c1)) {
System.out.println("Box "+box+" doesn't contain "+c2);
}
zoom -= 1;
final boolean[] done = new boolean[1];
final int fzoom = (int)zoom;
cnt.addMapListener(new MapListener() {
#Override
public void mapPositionUpdated(Component source, int zm, Coord center) {
if (zm == fzoom) {
final MapListener fthis = this;
Display.getInstance().callSerially(()->{
cnt.removeMapListener(fthis);
});
done[0] = true;
synchronized(done) {
done.notify();
}
}
}
});
cnt.zoom(center, (int)zoom);
while (!done[0]) {
Display.getInstance().invokeAndBlock(()->{
while (!done[0]) {
Util.wait(done, 100);
}
});
}
box = cnt.getBoundingBox();
System.out.println("Zoom now "+zoom);
}
} else if (box.contains(c1) && box.contains(c2)) {
while (box.contains(c1) && box.contains(c2)) {
zoom += 1;
final boolean[] done = new boolean[1];
final int fzoom = (int)zoom;
cnt.addMapListener(new MapListener() {
public void mapPositionUpdated(Component source, int zm, Coord center) {
if (zm == fzoom) {
final MapListener fthis = this;
Display.getInstance().callSerially(()->{
cnt.removeMapListener(fthis);
});
done[0] = true;
synchronized(done) {
done.notify();
}
}
}
});
cnt.zoom(center, (int)zoom);
while (!done[0]) {
Display.getInstance().invokeAndBlock(()->{
while (!done[0]) {
Util.wait(done, 100);
}
});
}
box = cnt.getBoundingBox();
}
zoom -= 1;
cnt.zoom(center, (int)zoom);
cnt.addTapListener(null);
}
});
Button testCoordPositions = $(new Button("Test Coords"))
.addActionListener(e->{
Coord topLeft = cnt.getCoordAtPosition(0, 0);
System.out.println("Top Left is "+topLeft+" -> "+cnt.getScreenCoordinate(topLeft) +" Should be (0,0)");
Coord bottomRight = cnt.getCoordAtPosition(cnt.getWidth(), cnt.getHeight());
System.out.println("Bottom right is "+bottomRight+" -> "+cnt.getScreenCoordinate(bottomRight) + " Should be "+cnt.getWidth()+", "+cnt.getHeight());
Coord bottomLeft = cnt.getCoordAtPosition(0, cnt.getHeight());
System.out.println("Bottom Left is "+bottomLeft+" -> "+cnt.getScreenCoordinate(bottomLeft) + " Should be 0, "+cnt.getHeight());
Coord topRight = cnt.getCoordAtPosition(cnt.getWidth(), 0);
System.out.println("Top right is "+topRight + " -> "+cnt.getScreenCoordinate(topRight)+ " Should be "+cnt.getWidth()+", 0");
Coord center = cnt.getCoordAtPosition(cnt.getWidth()/2, cnt.getHeight()/2);
System.out.println("Center is "+center+" -> "+cnt.getScreenCoordinate(center)+", should be "+(cnt.getWidth()/2)+", "+(cnt.getHeight()/2));
EncodedImage encImg = EncodedImage.createFromImage(markerImg, false);
cnt.addMarker(encImg, topLeft,"Top Left", "Top Left", null);
cnt.addMarker(encImg, topRight, "Top Right", "Top Right", null);
cnt.addMarker(encImg, bottomRight, "Bottom Right", "Bottom Right", null);
cnt.addMarker(encImg, bottomLeft, "Bottom Left", "Bottom Left", null);
cnt.addMarker(encImg, center, "Center", "Center", null);
})
.asComponent(Button.class);
Button toggleTopMargin = $(new Button("Toggle Margin"))
.addActionListener(e->{
int marginTop = $(cnt).getStyle().getMarginTop();
if (marginTop < Display.getInstance().getDisplayHeight() / 3) {
$(cnt).selectAllStyles().setMargin(Display.getInstance().getDisplayHeight() / 3, 0, 0, 0);
} else {
$(cnt).selectAllStyles().setMargin(0,0,0,0);
}
$(cnt).getComponentForm().revalidate();
})
.asComponent(Button.class);
Button btnClearAll = new Button("Clear All");
btnClearAll.addActionListener(e->{
cnt.clearMapLayers();
});
MapContainer.MapObject mo = cnt.addMarker(EncodedImage.createFromImage(markerImg, false), new Coord(-33.866, 151.195), "test", "test", e->{
System.out.println("Marker clicked");
cnt.removeMapObject(sydney);
});
sydney = mo;
System.out.println("MO is "+mo);
mo = cnt.addMarker(EncodedImage.createFromImage(markerImg, false), new Coord(-18.142, 178.431), "test", "test",e->{
System.out.println("Marker clicked");
});
System.out.println("MO is "+mo);
cnt.addTapListener(e->{
if (tapDisabled) {
return;
}
tapDisabled = true;
TextField enterName = new TextField();
Container wrapper = BoxLayout.encloseY(new Label("Name:"), enterName);
InteractionDialog dlg = new InteractionDialog("Add Marker");
dlg.getContentPane().add(wrapper);
enterName.setDoneListener(e2->{
String txt = enterName.getText();
cnt.addMarker(EncodedImage.createFromImage(markerImg, false), cnt.getCoordAtPosition(e.getX(), e.getY()), enterName.getText(), "", e3->{
ToastBar.showMessage("You clicked "+txt, FontImage.MATERIAL_PLACE);
});
dlg.dispose();
tapDisabled = false;
});
dlg.showPopupDialog(new Rectangle(e.getX(), e.getY(), 10, 100));
enterName.startEditingAsync();
});
Button showNextForm = $(new Button("Next Form"))
.addActionListener(e->{
Form form = new Form("Hello World");
Button b1 = $(new Button("B1"))
.addActionListener(e2->{
ToastBar.showMessage("B1 was pressed", FontImage.MATERIAL_3D_ROTATION);
})
.asComponent(Button.class);
Button back = $(new Button("Back to Home"))
.addActionListener(e2->{
home.showBack();
})
.asComponent(Button.class);
form.add(b1);
})
.asComponent(Button.class);
FloatingActionButton nextForm = FloatingActionButton.createFAB(FontImage.MATERIAL_ACCESS_ALARM);
nextForm.addActionListener(e->{
Form form = new Form("Hello World");
Button b1 = $(new Button("B1"))
.addActionListener(e2->{
ToastBar.showMessage("B1 was pressed", FontImage.MATERIAL_3D_ROTATION);
})
.asComponent(Button.class);
Button back = $(new Button("Back to Home"))
.addActionListener(e2->{
home.showBack();
})
.asComponent(Button.class);
form.add(b1).add(back);
form.show();
});
Container root = LayeredLayout.encloseIn(
BorderLayout.center(nextForm.bindFabToContainer(cnt)),
BorderLayout.south(
FlowLayout.encloseBottom(panTo, testCoordPositions, toggleTopMargin, btnMoveCamera, btnAddMarker, btnAddPath, btnClearAll )
)
);
maps.add(BorderLayout.CENTER, root);
maps.show();
Form hi = new Form("Native Maps Test");
hi.setLayout(new BorderLayout());
System.out.println("Read...");
ReadParseJson x = new ReadParseJson();
GoogleMapsTestApp e = new GoogleMapsTestApp();
System.out.println(Arrays.toString(x.getArray()));
//create and build the home Form
home = new Form("Home", BoxLayout.y());
home.add(new Label("PetBnB: AirBnB for Pets!"));
home.add(new Button("Search for Local Stay"));
home.add(new Button("Payment"));
TextField txt = new TextField("", "Enter Pet Animal here:");
home.add(txt)
.add(new CheckBox("New Users in Your Area!"));
RadioButton rb1 = new RadioButton("Bnb Area 2");
RadioButton rb2 = new RadioButton("Bnb Area 3");
rb1.setGroup("group");
rb2.setGroup("group");
home.addAll(rb1, rb2);
final Slider a = new Slider();
a.setText("50$");
a.setProgress(50);
a.setEditable(true);
a.setRenderPercentageOnTop(true);
home.add(a);
Button b1 = new Button("WARNING: MUST READ");
b1.addActionListener(evt -> Dialog.show("Warning!", "If Pet dies, it is not Bnb owner's responsibility", "Ok", "Cancel"));
home.add(b1);
//Create Form1 and Form2 and set a Back Command to navigate back to the home Form
Form form1 = new Form("Search For Stay");
setBackCommand(form1);
Form form2 = new Form("Help");
setBackCommand(form2);
//Add navigation commands to the home Form
NavigationCommand homeCommand = new NavigationCommand("Home");
homeCommand.setNextForm(home);
home.getToolbar().addCommandToSideMenu(homeCommand);
NavigationCommand cmd1 = new NavigationCommand("Search For Stay");
cmd1.setNextForm(maps);
home.getToolbar().addCommandToSideMenu(cmd1);
NavigationCommand cmd2 = new NavigationCommand("Help");
cmd2.setNextForm(form2);
home.getToolbar().addCommandToSideMenu(cmd2);
//Add Edit, Add and Delete Commands to the home Form context Menu
Image im = FontImage.createMaterial(FontImage.MATERIAL_MODE_EDIT, UIManager.getInstance().getComponentStyle("Command"));
Command edit = new Command("Edit", im) {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Editing");
}
};
home.getToolbar().addCommandToOverflowMenu(edit);
im = FontImage.createMaterial(FontImage.MATERIAL_LIBRARY_ADD, UIManager.getInstance().getComponentStyle("Command"));
Command add = new Command("Add", im) {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Adding");
}
};
home.getToolbar().addCommandToOverflowMenu(add);
im = FontImage.createMaterial(FontImage.MATERIAL_DELETE, UIManager.getInstance().getComponentStyle("Command"));
Command delete = new Command("Delete", im) {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Deleting");
}
};
home.getToolbar().addCommandToOverflowMenu(delete);
home.show();
}
protected void setBackCommand(Form f) {
Command back = new Command("") {
#Override
public void actionPerformed(ActionEvent evt) {
home.showBack();
}
};
Image img = FontImage.createMaterial(FontImage.MATERIAL_ARROW_BACK, UIManager.getInstance().getComponentStyle("TitleCommand"));
back.setIcon(img);
f.getToolbar().addCommandToLeftBar(back);
f.getToolbar().setTitleCentered(true);
f.setBackCommand(back);
}
boolean tapDisabled = false;
public void stop() {
current = Display.getInstance().getCurrent();
}
public void destroy() {
}
}

Mobile Vision Searching cameraSource detections for items in a list

I am currently trying to write an android app in which a user can blacklist any food ingredients he or she wants to avoid. The user should then be able to scan a label and instantly be told whether or not any blacklisted ingredients are found via text recognition.
I am using a cameraSource to detect the text in real time which appears to somewhat work, but only when very few words are present on screen. When there are too many words on screen, it cannot find anything.
What is going wrong when larger amounts of words are present?
private SurfaceView cameraView;
private TextView textView;
private CameraSource cameraSource;
private const int RequestCameraPermissionID = 1001;
public JavaList<string> userIngredients;
public ISharedPreferences pref;
public ISharedPreferencesEditor edit;
public Bitmap imageBitmap;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.ScanLayout);
cameraView = FindViewById<SurfaceView>(Resource.Id.surface_view);
textView = FindViewById<TextView>(Resource.Id.text_view);
pref = Application.Context.GetSharedPreferences("UserPrefs", FileCreationMode.Private);
edit = pref.Edit();
var preferences = pref.GetStringSet("UserPrefs", new JavaList<string>());
userIngredients = new JavaList<string>(preferences);
var bitmapOptions = new BitmapFactory.Options();
TextRecognizer textRecognizer = new TextRecognizer.Builder(ApplicationContext).Build();
if (!textRecognizer.IsOperational)
{
Log.Error("Main Activity", "Detector dependancies are not yet available");
}
else
{
cameraSource = new CameraSource.Builder(ApplicationContext, textRecognizer)
.SetFacing(CameraFacing.Back)
.SetRequestedFps(2.0f)
.SetAutoFocusEnabled(true)
.Build();
cameraView.Holder.AddCallback(this);
textRecognizer.SetProcessor(this);
}
}
public void SurfaceCreated(ISurfaceHolder holder)
{
if (ActivityCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.Camera) != Android.Content.PM.Permission.Granted)
{
//Request Permission
ActivityCompat.RequestPermissions(this, new string[] {
Android.Manifest.Permission.Camera
}, RequestCameraPermissionID);
return;
}
cameraSource.Start(cameraView.Holder);
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
cameraSource.Stop();
}
public void ReceiveDetections(Detections detections)
{
bool blackListedFound = false;
SparseArray items = detections.DetectedItems;
if (items.Size() != 0)
{
textView.Post(() =>
{
for (int i = 0; i < items.Size(); ++i)
{
for (int j = 0; j < userIngredients.Size(); j++)
{
if (((TextBlock)items.ValueAt(i)).Value.Equals(userIngredients[j]))
{
blackListedFound = true;
textView.Text = "Not reccomended\nIngredient Found: " + userIngredients[j];
}
}
}
});
}
else if (blackListedFound == false)
textView.Post(() =>
{
textView.Text = "No Ingredients found";
});
}
}
}
Here are some example images of my current problem;
Here is an example of the app failing to find a blacklisted ingredient (Water);

Cross fade page transitions Windows phone 8 toolkit

I'm implementing the NavigationTransition with the TransitionService provided by the Windows Phone 8 toolkit and Microsoft.Phone.Controls. I was expecting the pages to cross fade during the transition but they don't crossfade by default.
For instance if I'm going back to a previous page using a fade out transition, the origin page fades to full opacity before the target page appears, producing a "popping" effect.
I hoping that someone could provide guidance on getting that effect to happen.
Please check the type of your RootFrame in App.xaml.cs, it must be TransitionFrame if want to use NavigationTransition.
I ended up using some slight-of-hand with screen shots and the far background plane to make the phone pages appear to "cross-fade" - here with edited out biz-details:
public class FormPage : PhoneApplicationPage {
public FormPage() {
InitializeComponent();
PrepareAnimationIn(FormApp.frameTransition);
}
void PrepareAnimationIn(string pageAnimation) {
AnimatedPageFactory.SetNavigationInTransition(pageAnimation, this);
}
public void PrepareAnimationOut(string pageAnimation) {
AnimatedPageFactory.SetNavigationOutTransition(pageAnimation, this);
}
void StoreScreenShot(string name, WriteableBitmap bitmap) {
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
string path = Path.Combine(screenshotDir, name + screenFileType);
store.CreateDirectory(screenshotDir);
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, FileMode.Create, store)) {
using (BinaryWriter writer = new BinaryWriter(stream)) {
int count = bitmap.Pixels.Length * sizeof(int);
byte[] pixels = new byte[count];
Buffer.BlockCopy(bitmap.Pixels, 0, pixels, 0, count);
writer.Write(pixels, 0, pixels.Length);
}
}
}
}
WriteableBitmap FetchScreenShot(string name) {
WriteableBitmap bitmap = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
string path = Path.Combine(screenshotDir, name + screenFileType);
if (store.FileExists(path)) {
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, FileMode.Open, store)) {
using (BinaryReader reader = new BinaryReader(stream)) {
int count = bitmap.Pixels.Length * sizeof(int);
byte[] pixels = new byte[count];
reader.Read(pixels, 0, count);
Buffer.BlockCopy(pixels, 0, bitmap.Pixels, 0, count);
}
}
store.DeleteFile(path);
}
}
return bitmap;
}
WriteableBitmap ScreenShot() {
WriteableBitmap bmpCurrentScreenImage = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
bmpCurrentScreenImage.Render(_canvas, new MatrixTransform());
bmpCurrentScreenImage.Invalidate();
return bmpCurrentScreenImage;
}
ImageBrush ImageBrushFromBitmap(WriteableBitmap bitmap) {
return new ImageBrush { ImageSource = bitmap };
}
static Stack<string> formImages = new Stack<string>();
static string screenFileType = ".frmscn";
static string screenshotDir = "frmscrn";
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) {
var app = Application.Current as App;
if (e.NavigationMode == NavigationMode.New &&
e.Uri.ToString().Contains("FormPage.xaml")) {
WriteableBitmap screenShot = ScreenShot();
app.RootFrame.Background = ImageBrushFromBitmap(screenShot);
formImages.Push(Name);
StoreScreenShot(Name, screenShot);
} else if (e.NavigationMode == NavigationMode.Back) {
if (formImages.Count > 0)
app.RootFrame.Background = ImageBrushFromBitmap(FetchScreenShot(formImages.Pop()));
else {
//we're backing out of the last form so reset the background
app.RootFrame.Background = null;
RemoveCachedScreenshots();
}
}
}
public static void RemoveCachedScreenshots() {
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
string path = Path.Combine(screenshotDir, "*" + screenFileType);
try {
string[] fileList = store.GetFileNames(path);
foreach (string f in fileList) {
store.DeleteFile(Path.Combine(screenshotDir, f));
}
} catch {
}
}
}
}

IllegalStateException BlackBerry

public class show extends MainScreen {
private String date1;
private long date1l;
private long date2l;
private LabelField curDate = new LabelField();
private LabelField toDate = new LabelField();
private LabelField diffe = new LabelField();
// private LabelField info;
// private LabelField empty;
// private InvokeBrowserHyperlinkField hello;
ButtonField activate = null;
ButtonField disactivate = null;
Timer timer;
Timer timer2;
public String date1s[];
int d, m, y;
int x = 1;
String day, hour, minute;
Date date = new Date();
Calendar calendar = Calendar.getInstance();;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy HH mm");
public show() {
add(curDate);
add(toDate);
add(new SeparatorField());
add(diffe);
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTick(), 0, 1000);
}
private class TimerTick extends TimerTask {
public void run() {
if (x != 0) {
date1l = date.getTime();
try {
date1 = dateFormat.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT+7:00"));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DATE, 1);
cal.set(Calendar.YEAR, 2012);
date2l = cal.getTime().getTime();
date1s = StringUtilities.stringToWords(date1);
d = Integer.parseInt(date1s[0]);
m = Integer.parseInt(date1s[1]);
y = Integer.parseInt(date1s[2]);
display();
} else {
timer.cancel();
}
}
}
public void display() {
String monw = convertToWords(m);
curDate.setText("Current Date = " + d + " " + monw + " " + y + " "
+ date1s[3] + ":" + date1s[4]);
toDate.setText("To Date = 1 February 2012 00:00");
long diffms = date2l - date1l;
long ds = diffms / 1000;
long dm = ds / 60;
long dh = dm / 60;
long dd = dh / 24;
long q = dd;
long h = (ds - (dd * 24 * 60 * 60)) / (60 * 60);
long m = (ds - (dh * 60 * 60)) / 60;
diffe.setText("Remaining Time : \n" + Long.toString(q) + " day(s) "
+ Long.toString(h) + " hour(s) " + Long.toString(m)
+ " minute(s)");
day = Long.toString(q);
hour = Long.toString(h);
minute = Long.toString(m);
showMessage();
}
/*
* private void link() { empty = new LabelField("\n\n"); add(empty); hello =
* new InvokeBrowserHyperlinkField("Click here",
* "http://indri.dedicated-it.com/wordpress/?page_id=17"); add(hello); info
* = new LabelField("\n\nPress menu then choose \"Get Link\" to access");
* add(info); }
*/
void showMessage() {
activate = new ButtonField("Activate", FIELD_HCENTER) {
protected boolean navigationClick(int action, int time) {
if (activate.isFocus()) {
Dialog.alert("Started!!");
Start();
}
return true;
}
};
add(activate);
disactivate = new ButtonField("Disactivate", FIELD_HCENTER) {
protected boolean navigationClick(int action, int time) {
if (disactivate.isFocus()) {
Dialog.alert("Stopped!!");
timer2.cancel();
}
return true;
}
};
add(disactivate);
/*
* UiEngine ui = Ui.getUiEngine(); Screen screen = new
* Dialog(Dialog.D_OK, data, Dialog.OK,
* Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION),
* Manager.VERTICAL_SCROLL); ui.queueStatus(screen, 1, true);
*/
}
public void Start() {
timer2 = new Timer();
timer2.scheduleAtFixedRate(new TimerTick2(), 0, 6000);
}
private class TimerTick2 extends TimerTask {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
synchronized (Application.getEventLock()) {
UiEngine ui = Ui.getUiEngine();
Screen screen = new Dialog(Dialog.D_OK, "Hello!",
Dialog.OK,
Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION),
Manager.VERTICAL_SCROLL);
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
}
});
}
}
private String convertToWords(int m) {
String w = "";
switch (m) {
case 1:
w = "January";
break;
case 2:
w = "February";
break;
case 3:
w = "March";
break;
case 4:
w = "April";
break;
case 5:
w = "May";
break;
case 6:
w = "June";
break;
case 7:
w = "July";
break;
case 8:
w = "August";
break;
case 9:
w = "September";
break;
case 10:
w = "October";
break;
case 11:
w = "November";
break;
case 12:
w = "December";
break;
}
return w;
}
public boolean onClose() {
UiApplication.getUiApplication().requestBackground();
return true;
}
}
What actually is JVM 104 IllegalStateException? This program is a countdown program, which counts the remaining time from today until February 1st. Also, I implement a timer function that appears even if the application is closed. Can u please help me locate the problem? Thank you
As Richard said, you are trying to update LabelField from another thread. Try the following code snippet:
synchronized (UiApplication.getEventLock()) {
labelField.setText();
}
Try this below code and change according to your requirement;
public class FirstScreen extends MainScreen implements FieldChangeListener
{
LabelField label;
Timer timer;
TimerTask timerTask;
int secs=0;
long start,end;
String startDate="2012-01-28",endDate="2012-01-29";
ButtonField startCountDown;
public FirstScreen()
{
createGUI();
}
private void createGUI()
{
startCountDown=new ButtonField("Start");
startCountDown.setChangeListener(this);
add(startCountDown);
}
public void fieldChanged(Field field, int context)
{
if(field==startCountDown)
{
start=System.currentTimeMillis();
//this is the current time milliseconds; if you want to use two different dates
//except current date then put the comment for "start=System.currentTimeMillis();" and
//remove comments for the below two lines;
//Date date=new Date(HttpDateParser.parse(startDate));
//start=date.getTime();
Date date=new Date(HttpDateParser.parse(endDate));
end=date.getTime();
int difference=(int)(end-start);
difference=difference/1000;//Now converted to seconds;
secs=difference;
Status.show("Seconds: "+secs,100);
callTheTimer();
}
}
public void callTheTimer()
{
label=new LabelField();
add(label);
timer=new Timer();
timerTask=new TimerTask()
{
public void run()
{
synchronized (UiApplication.getEventLock())
{
if(secs!=0)
{
label.setText(""+(secs--)+" secs");
}
else
{
timer.cancel();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
label.setText("");
Dialog.alert("Times Up");
}
});
}
}
}
};
timer.schedule(timerTask, 0, 1000);
}
protected boolean onSavePrompt()
{
return true;
}
public boolean onMenu(int instance)
{
return true;
}
public boolean onClose()
{
UiApplication.getUiApplication().requestBackground();
return super.onClose();
}
}
In this code I am taking taking two different dates and start the countdown by taking their difference(in seconds); See the comments in the code;