I have a simple question (may be very dumb), however I did not find an answer goggling around.
I'm trying to save a simple preference say "high score" on my game that I'm using libgdx to build.
Here is my sample code -
Preferences prefs2;
prefs2= Gdx.app.getPreferences("MyPreferences");
prefs2.putString("name", "Donald Duck");
String name = prefs2.getString("name", "No name stored");
font.draw(textBatcher, name, 55, 55);
Everything in the code (reading and writing to the xml file MyPreferences) works as expected except one thing; the high score stored on the file doesn't work when I restart the game. I definitely know that I'm missing something that is very simple but don't know what it is :)
Can any one please help me ?
I have also tried this -
Preferences prefs2;
if (prefs2 == null){
prefs2= Gdx.app.getPreferences("MyPreferences");
}
However it doesn't seem to work.
You're lacking a call to prefs2.flush() after you added the highscore item to the preferences object.
Straight from the libgdx docs:
http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/Preferences.html#flush()
Related
I want to save the highscore created in the game and can be seen in the main menu when the player hits the highscore button, can someone help me?
you can use SQLITE to save the highscore to database another way is make a file that write the score to a Text File and save it to the directory of the system
You can solve your problem in a easier way..
Just declare a Variable for the Score like this..
local score=0
Then Increment the score variable by 1 whenever it hits the paddle. So Insert the coding in Collision Function as given below:
local function onCollision(event)
{
score=score+1
}
ball.collision=onCollision
ball:addEventListener("collision",ball)
Finally When you need to save your highscore (after gameover), You can use Preference instead of json which makes the larger coding.
local preference= require "preference"
local highscore=0
preference.save{highscore=score}
If you want to display the Highscore, then use the following:
highscore_value=preference.getValue("highscore")
display.newText(highscore_value,0,0,nil,30)
This might be useful for your problem !!
Multiple libraries exist for this purpose.
GGScore is an open source library built by GlitchGames which can easily allow you to do this: GlitchGames/GGScore
All the documentation you need is in the main page (README.md) so there isn't really a need for me to explain the code. But it's really easy to use.
My problem is all the texts comes from webservices. So, at the beginning, I call the webservice and I have to set the texts in strings.xml. I know writing in strings.xml it's impossible but we had the same problem on iOs and a solution has been found here http://iosapplove.com/archive/2013/01/localizable-strings-how-to-load-translations-dynamically-and-use-it-inside-your-iphone-app/.
So my question is : Is there a similar way on android ? (I think no)
It exists alternative way like using database or sharedPreferences but these solutions won't be very effective. Moreover, the application will contain many languages.
So my second question : What is the best way to do this ?
As you already know, the strings.xml files will not exist in the APK. This means that there is no way to change what getResources().getString(R.string.mystring) will return.
You say that "it's a request from customer". My suggestion is that you tell the customer "this is a bad idea". Because it really is.
If the customer persists I guess your only option is to download the texts in whatever language it is that you need and store it in your apps external file storage. The suggestion to use a properties file is good. Load it as an InputStream and get strings from it.
Have you considered what will happen if the app is in flight mode or does not have a network available when started? Will you provide default values?
Also, with this solution you will not be able to set any texts in TextViews or similar in XML since the system won't have access to your downloaded translations in the properties files.
If you still go ahead with this I'd also suggest that you wrap the Properties file into some other class and fall back to whatever texts you have in your strings.xml if a text doesn't exist in the properties file or if it wasn't downloaded for some reason:
class TextRetriever {
// the downloaded texts go here
private Properties properties;
private Context context;
public String getString(String key) {
String s = properties.getProperty(key);
// not found in properties file
if(s == null) {
// fall back to value in strings.xml
s = context.getResources().getIdentifier(key, "string", context.getPackageName())
}
return s;
}
}
I am creating a multiple choice quiz game where there is an option to continue the game from where the user has left. Example, if user stopped the application at Question Number 4, then by pressing the continue option will resume the quiz game from Question Number 4 itself. I am not able to understand how should I move ahead by coding way? What is the right way to continue a multiple choice quiz game? Any help would be appreciated.
As an example, you could use JDOM. Just include the .jar file in your projects build path and then you'll have access to the JDOM library methods.
An example of using the JDOM libraries:
// Create a new XML document in memory
Document doc = new Document();
Element root = new Element("child");
doc.setRootElement(root); // set ^ above element as the root element
root.addContent(new Element( "childname" )); // add a data element to the root
root.getChild("childname").setText("SOME INFO"); // give some data to the element <childname>
// Save the XML file
FileWriter writer = new FileWriter("FILENAME.xml");
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat()); // sets correct tabbing/format in the file
outputter.output(doc, writer);
This would make something like:
<child>
<childname>SOME INFO</childname>
</child>
You can then access the information stored in the XML file by using some JDOM methods like:
root.getChild("SOME CHILD").getText();
Of course JDOM isn't the only option here. It's whatever seems easiest for you, not me.
Where are you getting your questions from? Try to build a sqlite db around your game. Get your questions from there. Then when the player goes out save state of the quiz in a db table, and when he comes back resume the game. Also you can store his previous performances, current performance in seperate tables. Seems like a good way to go about it.
Its a simple solution actually. A sql read will always result in the same sequence of read when you make a select call. So if you have 100 rows, and you select 10 rows of them and choose the first one, it will always be the same. Practically tested and it works. Now, you can create a "played" flag in your table and flag your quiz played. This way you will always get the same question in the same sequence as you reset.
If you want to randomize, I suggest you code that. There is no automatic way to do it.
Now for question, you should use shared preferences to save current question being played. This way you can just read that one row when you restart your application.
Hello all I'm new to android programming and I have a problem.
I created a sudoku app with preset puzzles for 3 difficulties using an e - book's directions.
The thing is that I made a puzzle generator for my puzzles to make them infinite.Now here is my problem :
To save your pre-defined puzzle in the book's example you had to use :
getPreferences(MODE_PRIVATE).edit().putString(PREF_PUZZLE,
toPuzzleString(puzzle)).commit();
toPuzzleString obviously converts the puzzle into a string(which was stored before in a 1 dimention array)
In order to load your saved settings to make the Continue option to work you had to use :
puz = getPreferences(MODE_PRIVATE).getString(PREF_PUZZLE,easyPuzzle);
BUT this works for a predefined puzzle stored in a private final string called "easypuzzle" at the beggining of the game.class . My puzzle is generated and stored in a 1 dimentional array when user clicks New Game.As a result I have to pass my generated puzzle as a reference(this is what I think) cause i tried to pass it like this :
getPreferences(MODE_PRIVATE).getString(PREF_PUZZLE,toPuzzleString(puzzle));
and when I close the game or just go back and try to Continue my game generates a new puzzle for me (or this is what I think it is) instead of loading the saved one.
What am I doing wrong? Can anyone help me , or tell me how to pass my puzzle as a reference like in c++?
Thank you all for your time any help would be appreciated....
As mentioned above, your puzzle may not be saved in preferences correctly. In order to check, change the getString(...) method to something like this:
String puzzleFromPrefs = getPreferences(MODE_PRIVATE).getString(PREF_PUZZLE, null);
if( null == puzzleFromPrefs ) {
// Then you know that it wasn't saved correctly...
}
This will cause null to be returned if the puzzle hasn't already been saved in the preferences. This will help narrow down where the issue may be.
I'm a beginner in Android, but I've done all the research I could on this problem and I just can't seem to find a way to solve it... The app worked fine until I decided to add the SharedPreferences in order to update some high scores. Now I can't seem to make it work, it always crashes at the very start (after the splash screen)
In the on Create method, below the setContentView I have the following lines:
highScores = getSharedPreferences("HighScores", 0);
hs1 = highScores.getInt("HighScore1", 0);
shs1 = highScores.getString("sHighScore1", "User1");
and a couple more, but mostle they are alternate takes on lines 2 and 3 in the prior code. I have declared the highScores as SharedPreferences in the body of the class. The only place in this class where I use the info gathered from the SharedPreferences is in editing a TextView, which uses the following code:
High1.setText(String.format("1. %04d - %s", hs1, shs1));
My guess is that I made an error somewhere in the code, but am unable to find it...
Just for additional info, I only use the SharedPreferences in one other class (which should update the high scores at the end of games) and uses a simillar code:
highScores = getSharedPreferences("HighScores", 0);
hs1 = highScores.getInt("HighScore1", 0);
shs1 = highScores.getString("sHighScore1", "User1");
The code above was for getting previous high scores, while the code below is used for updating:
prefEditor.putInt("HighScore1", hs1);
prefEditor.putString("sHighScore1", shs1);
prefEditor.commit();
I have declared the SharedPrefs editor as:
SharedPreferences.Editor prefEditor = highScores.edit();
I would really appreciate any help, as I can't seem to find what I've done wrong, probably it's a small error somewhere, but it's really driving me nuts :P I would give you more of the code, but I can't see any purpose in that, because it doesn't use the SharedPreferences and I'm pretty sure they're the cause of the issue...
Thank you in advance for your help :)