This question already has answers here:
Serialize and Deserialize Json and Json Array in Unity
(9 answers)
Closed 3 years ago.
I'm trying to get all my lines render positions and add it to a list of vector3 then covert it to Json, so I can save it in the firebase. I'm using JsonUtility, but the problem is my jsondata is always empty even the list of vecor3 is not.
This is my code then I'm using :
public class Path : MonoBehaviour
{
[SerializeField] private List<Transform> checkpoints = new List<Transform>();
private LineRenderer linerenderer;
public Material TheLineMateriel;
public static bool _ispressed = false;
private string DATA_URL = "https://kataraproject-a233a.firebaseio.com/";
private DatabaseReference reference;
public string hello = "khraaa" ;
// Start is called before the first frame update
void Start()
{
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(DATA_URL);
reference = FirebaseDatabase.DefaultInstance.RootReference;
GameObject lineObject = new GameObject();
this.linerenderer = lineObject.AddComponent<LineRenderer>();
this.linerenderer.startWidth = 0.05f;
this.linerenderer.endWidth = 0.05f;
this.linerenderer.positionCount = checkpoints.Count;
this.linerenderer.material = TheLineMateriel;
}
// Update is called once per frame
void Update()
{
this.DrawLine();
}
private void DrawLine()
{
Vector3[] checkpointsArray = new Vector3[this.checkpoints.Count];
for (int i = 0; i < this.checkpoints.Count; i++) {
Vector3 checkpointPos = this.checkpoints[i].position;
checkpointsArray[i] = new Vector3(checkpointPos.x, checkpointPos.y, 0f);
}
Vector3[] newPos = new Vector3[linerenderer.positionCount];
this.linerenderer.SetPositions(checkpointsArray);
linerenderer.GetPositions(newPos);
//for (int i = 0; i < linerenderer.positionCount ; i++)
//{
// newPos[i] = i;
//}
if ( _ispressed == true)
{
string jsonData = JsonUtility.ToJson(checkpointsArray);
//reference.Child("Position" + Random.Range(0,1000000)).SetRawJsonValueAsync(jsonData);
Debug.Log(jsonData);
_ispressed = false;
}
}
public void Save ()
{
_ispressed = true;
}
}
can someone help me please?
You could create a simple class to handle serialization of Unity types like such :
[Serializable]
public class SerializedVector3
{
public float x;
public float y;
public float z;
public SerializedVector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
public SerializedVector3(Vector3 vector3)
{
x = vector3.x;
y = vector3.y;
z = vector3.z;
}
}
public static class Vector3Extensions
{
public static Vector3 ToVector3(this SerializedVector3 serializedVector3)
{
return new Vector3(serializedVector3.x, serializedVector3.y, serializedVector3.z);
}
public static SerializedVector3 FromVector3(this Vector3 vector3)
{
return new SerializedVector3(vector3);
}
}
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
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
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;
I know how to do it using simple recursion, but in order to complete this particular assignment I need to be able to accumulate on the stack and throw an exception that holds the answer in it.
So far I have:
public static int fibo(int index) {
int sum = 0;
try {
fibo_aux(index, 1, 1);
}
catch (IntegerException me) {
sum = me.getIntValue();
}
return sum;
}
fibo_aux is supposed to throw an IntegerException (which holds the value of the answer that is retireved via getIntValue) and accumulates the answer on the stack, but so far I can't figure it out. Can anyone help?
I don't know what your implementations for fibo_aux and IntegerException look like, but the following two implementations work with your existing code (I don't think there's anything wrong with the code you posted, so I assume something is awry in either fibo_aux or IntegerException). Maybe you'll find this helpful.
public static void fibo_aux(int index, int a, int b) throws IntegerException
{
if (--index > 0)
fibo_aux(index, b, a + b);
else
throw new IntegerException(a + b);
}
An implementation for IntegerException:
public class IntegerException extends Exception
{
private static final long serialVersionUID = -6795044518321782305L;
private Integer intValue;
public IntegerException(int i)
{
this.intValue = i;
}
public Integer getIntValue()
{
return intValue;
}
}
Here you go :
public class ExcFib {
/**
* #param args
*/
public static void main(String[] args) {
new ExcFib().fibo ( 10 );
}
class FiboException extends Throwable
{
public int n;
public FiboException(int n)
{
this.n = n;
}
private static final long serialVersionUID = 1L;
}
public void fibo(int idx) {
try {
fibo_aux(idx-1,1,1);
} catch (FiboException e) {
System.out.println ( "F(" + idx + ") = " + e.n );
}
}
private void fibo_aux(int i, int j, int k) throws FiboException {
if ( i < 1 )
{
throw new FiboException(k);
}
fibo_aux(i - 1, k, j + k );
}
}