AS3/AIR Load/Save Username progress - android

I am creating an Android application created using Flash AS3. The user will input his/her name(instance namenameField), click the previous (btnPrev) and next (btnNext) button and press save (btnPrev). After restarting the application, the last frame saved was loaded (with the name). However if I want to input 2nd user with different name and save it in different frame, will the 2nd user's save progress be retained (without deleting the progress of the 1st user?). The problem, when I type the previous user name progress and press load (btnLoad), his saved progress doesn't load. Please help.
I am a newbie in programming. Here is my code so far:
*import flash.events.MouseEvent;
var savedstuff:SharedObject = SharedObject.getLocal("myStuff");
btnSave.addEventListener(MouseEvent.CLICK, SaveData);
btnLoad.addEventListener(MouseEvent.CLICK, LoadData);
btnNext.addEventListener(MouseEvent.CLICK, pageNext);
btnPrev.addEventListener(MouseEvent.CLICK, pagePrev);
function pageNext (e:MouseEvent){
nextFrame();
}
function pagePrev (e:MouseEvent){
prevFrame();
}
function SaveData(MouseEvent){
savedstuff.data.username = nameField.text
savedstuff.flush();
}
function LoadData(MouseEvent){
if(savedstuff.size>0){
nameField.text = savedstuff.data.username}
gotoAndStop(savedstuff.data.saveData);
}
if(savedstuff.size>0){
nameField.text = savedstuff.data.username}*

If I understood it correctly you want to save and load savedstuff for two different users, right ?
Since you always saving everything with the name "myStuff" data will be overwritten every time you save. If you want that per user you might want to add the username to the SharedObject name:
var savedstuff:SharedObject;
function SaveData(e:MouseEvent)
{
var userName:String = nameField.text;
savedstuff = SharedObject.getLocal(userName + "myStuff");
savedstuff.data.username = userName;
savedstuff.flush();
}
function LoadData(e:MouseEvent)
{
var userName:String = nameField.text;
savedstuff = SharedObject.getLocal(userName + "myStuff");
if(savedstuff.size > 0)
{
nameField.text = savedstuff.data.username}
gotoAndStop(savedstuff.data.saveData);
}
}

Related

Image view not changing/Shared prefs not updating (android)

My app utilizes a Image view that changes daily. It runs a receiver every 24 hours which should send a notification and change the shared preferences value (this being the image to display). The notification runs fine at the correct time so I know the receiver works correctly. When you launch the activity the image that needs to be changed is located, the app gets the shared preferences value and then sets the imageView to display that image. The default value is set to 0, and if the value is 0 it sets the image to a "something went wrong" style of image. How come the notification works but my image view doesn't change? It stays as the "something went wrong image"?
My code:
The Reciever:
val quotes = arrayOf(R.drawable.i1, R.drawable.i2, R.drawable.i3, R.drawable.i5, R.drawable.i6, R.drawable.i7, R.drawable.i8, R.drawable.i9, R.drawable.i10, R.drawable.i11, R.drawable.i12, R.drawable.i13, R.drawable.i14, R.drawable.i15, R.drawable.i16, R.drawable.i17, R.drawable.i18, R.drawable.i19, R.drawable.i20, R.drawable.i21, R.drawable.i22, R.drawable.i23, R.drawable.i24, R.drawable.i25)
val quote = quotes.random()
val prefquotes = context.getSharedPreferences("save", AppCompatActivity.MODE_PRIVATE).edit()
prefquotes.putInt("Quotes", quote)
prefquotes.apply()
Qinsperation:
val quote = sharedPreferences.getInt("Quote", 0)
setContentView(R.layout.qinsperational)
val imageView = findViewById<ImageView>(R.id.daily_image)
if (quote == 0) {
imageView.setImageResource(R.drawable.oh_no)
}else{
Log.d("Quote", "good")
imageView.setImageResource(quote)
}
There is no crashes or anything in the logs. All help is much appreciated as I can't figure this one out

How do you call a variable created earlier in a when in kotlin?

I'm trying to list the first 100 of a shuffled list. I'm telling it to shuffle if the list is at 0 and then increment. I then am trying to call that list in another section of the when but it's not working. How can I accomplish this?
when (countF) {
0 -> {
//shuffle at 0
val randomChaos = chaosList.asSequence().shuffled().take(chaosList.count()).toList()
cResult.text = randomChaos.elementAt(countF) + countF + "\n\n\n\n\n\n\n\n" + this.cResult.text
countF++
}
1-99 -> {
//show 1-99
cResult.text = randomChaos.elementAt(countF) + countF + "\n\n\n\n\n\n\n\n" + this.cResult.text
countF++
}
100 -> countF = 0
You would need to create the val randomChaos before the when enclosure for it to be available in the scope of multiple branches of the when statement.
That said, the way you're getting a random element is very convoluted. take(chaosList.count()) is completely redundant. And since you don't use multiple sequence operators, creating a sequence is also redundant. Finally, you are only pulling a single item from the random list, so it's unnecessary to create a shuffled list in the first place. Using elementAt() on a shuffled list is no different than picking any element out of that shuffled list, or simply picking a random item out of a list that isn't shuffled at all.
Also, the first two branches of your when statement currently would produce exactly the same results so they can be merged.
Based on what you described, I'm guessing you had this when statement inside a loop that tries to run it 100 times so you can list all the items. For that to work, you would need to shuffle the list one time outside the loop, and then you could iterate its elements in the loop.
However, there are functions that can make it easier to do what you're suggesting. Here's an example:
val randomChaos = chaosList.shuffled()
cResult.text = randomChaos.asSequence()
.take(100)
.withIndex()
.joinToString("\n") { (i, value) ->
"$value-$i"
}
In this case, using a Sequence helps avoid creating an intermediate list to hold the first 100 values.
var randomChaos = chaosList.shuffled()
fun cShuf() { randomChaos = chaosList.shuffled() }
cRoll.setOnClickListener() {
cResult.movementMethod = ScrollingMovementMethod()
if (countF < 1) { cShuf() }
cResult.text = randomChaos.elementAt(countF) + "\n\n\n\n\n\n\n\n" + this.cResult.text
countF++
if (countF > 100) countF = 0
}
I have figured out how to use a function to generate a new shuffe of the list once I've hit > 100 shown.
My issue with making it a function was I was trying to use val variable in the function but the variable already existed so I didn't need to use val, just the name of the variable.

how to get the user's input in kotlin on android studio

I have an android project that shows a summary of you car efficiency on which you enter your information and it shows in a listView your summary, but how do I get the user's input, so I can do the math, and show the sum on a different activity?
fun getTotalGallons() : Double {
// add all of the gallons together from the list
// return that total
return ....
}
val editText = EditText() //Here you can use instantiate it or use kotlin
//extensions to used it directly
val stringText = editText.text //do something

Saving the value of a stepper in Corona SDK to a json file

I want to be able to pass the value from a stepper widget in corona into a json file. So far I've got my stepper to display and increment and decrement and display the current value on screen. I've written a function to save the value to a file as json, but i'm having trouble calling that function. I want to be able to have other setting on screen which have their values save to json. Here the code I have to save the setting:
local function saveSettings (e)
-- body
print("testtesttest")
if (file) then
local content = file:read("*a")
else
settings = {}
settings.houses = StepperNo
file = io.open(path, "w")
local json_setting = json.encode(settings)
file:write(json_setting)
io.close(file)
end
end
and then the code to display the stepper:
local StepperNo = 1
local displayNoOfHouses = display.newText("Number of houses: "..StepperNo,180,135, native.systemFontBold,16)
local function onStepperPress( e )
if ("increment" == e.phase) then
StepperNo = StepperNo + 1
elseif ("decrement") == e.phase then
StepperNo = StepperNo - 1
end
displayNoOfHouses.text = "Number of houses: "..StepperNo
end
local HouseStepper = widget.newStepper {left = 100, top = 100, minimumValue = 0, maximumValue = 9, onPress = onStepperPress}
I dont know how to call the savesetting function after the stepper is pressed. I think I might have done this incorrectly or may be missing something obvious, I am very new to Lua...
There is a very simple to implement table saver and loader presented in this tutorial:
http://coronalabs.com/blog/2014/10/14/tutorial-saving-and-loading-lua-tables-with-json/
It uses JSON to encode a Lua table to save and when needed, read the JSON back in and decode it to a Lua table.

How to fetch own best score using gameNetwork.request( "loadScores" )?

does someone use gameNetwork provided by Google Play? Im having a little problem with it, im trying to fetch personal best score and its not working well.
Here is the code that i use
function loadScoreCallback(event)
oldScore = event.data[5].formattedValue
end
gameNetwork.request( "loadScores",
{
leaderboard =
{
category = "thecategory id",
playerScope = "Global", -- Global, FriendsOnly
timeScope = "AllTime", -- AllTime, Week, Today
range = {1,5},
playerCentered = true,
},
listener = loadScoreCallback
})
I also tried something like
function loadScoreCallback(event)
oldScore = event.data
end
gameNetwork.request( "loadScores",
{
leaderboard =
{
playerID = playerName,
category = "CgkIptXi1qgCEAIQAw",
playerScope = "Global", -- Global, FriendsOnly
timeScope = "AllTime", -- AllTime, Week, Today
playerCentered = true,
},
listener = loadScoreCallback
})
Also didnt work :/
I had some trouble figuring this out, but I found a solution that works for me.
this is the listener that is called when the user submits a score.
local function onGameNetworkRequestResult( event )
if event.type == "setHighScore" then
local function tempScoresFct(event)
if event.data then
local playerRank = event.data[1].rank
local currentValue = event.data[1].value
if lb.tempScore <= event.data[1].value then
native.showAlert("Score submitted", "You score is lower or equal than your current score in the leaderboard("..currentValue.."), nothing changed. Your global, all time rank is:\n" .. playerRank .. "\nTo see how you are doing among your friends and in other time scales, click the button \"show leaderboard\".", {"Ok"})
else
native.showAlert("Score submitted", "Your score was successfully uploaded to the leaderboard. Your global, all time rank is:\n" .. playerRank .. "\nTo see how you are doing among your friends and in other time scales, click the button \"show leaderboard\".", {"Ok"})
end
end
end
gameNetwork.request( "loadScores",
{
leaderboard =
{
category = event.data.category,
playerScope = "Global", -- Global, FriendsOnly
timeScope = "AllTime", -- AllTime, Week, Today
range = {1,1}, --Just get one player
playerCentered = true, -- and this player is the player that is logged in
},
listener = tempScoresFct
})
end
end
and this ist the function that submits the score:
function lb.submitScoreFct(event)
if event.phase == "ended" then
if gameNetwork.request("isConnected") then
--show leaderboards
print("submitting score")
local myCategory
local categoryName
if event.target.category == 1 then
myCategory = "ategoryID" --palo alto
categoryName = "Palo Alto"
elseif event.target.category == 2 then
myCategory = "ategoryID" --groningen
categoryName = "Groningen"
elseif event.target.category == 3 then
myCategory = "ategoryID" --sp2
categoryName = "SP2"
end
--local score = mRand(100,1000)
local score = event.target.score
lb.tempScore = score -- i use this to verify if the uploaded score was higher or lower then the value that is already there
print("Added " .. score .. " to " .. categoryName)
gameNetwork.request( "setHighScore",
{
localPlayerScore = { category=myCategory, value=tonumber(score) },
listener = lb.onGameNetworkRequestResult
})
end
else
print("user needs to log in")
-- Tries to login the user, if there is a problem then it will try to resolve it. eg. Show the log in screen.
gameNetwork.request("login",
{
listener = loginListener,
userInitiated = true -- if that is false, than this process is silent ie dont pop up a log in if the user is not logged in
})
end
return true
end
Oh and one thing I figured out, is that this listener functions are fragile. If there is one error inside, they quit and sometimes dont give any error.
For example if you try to print(event.data.rank) (instedt of print(event.data[1].rank)) there is no error but the function ends at this point and the rest of the function is not executed...
Well so i found a better idea, since not everyone is online all the time i made my own saving system, and it fetches high score from there. But i still dont know why it doesnt work, well at least i solved it with this.

Categories

Resources