Im in the process of learning some app building for android.
I wanna create an example of a high score system before trying to use it in a game.
Lets say that I have a timer running seconds and a stop button. If I press the stop button, the timer stops, and the number it has come to is saved (locally) to a highscore list. A top 5 for example.
How would I go about saving this highscore?
I've read a bit about SQLite and Shared preference, but I don't know what to use. Maybe there are even more options? I'm not looking for any online highscore list.
If you know of some good guides / tutorials, please link them to me.
Thanks.
I use SharedPreferences for that kind of thing although it is a bit overly complex in my opinion. Once you've got it added to your manifest and figure out how to use it, however, it's fairly simply. It looks like the usage of SharedPreferences has been covered previously here: How to use SharedPreferences in Android to store, fetch and edit values. You can, of course, just save to a file as well which might be easier, but potentially easier to hack if you care. I don't know much about SQLight to make comments on that.
Yes shared preferences would be suited for this. Here is a kick off example - but better use lists :
private static final String[] SCORES_KEYS = { "1", "2", "3", "4", "5" };
private static final int SCORES = 5;
//...
{
SharedPreferences sp = getDefaultSharedPreferences(); // in an activity,
// service or other context. DO NOT USE NAMED preferences
final long timer = getYourTimerScore();
int position = SCORES;
long[] lowerScores = new long[SCORES + 1];
for (int i = SCORES; i > 0;) {
long j = sp.getLong(SCORES_KEYS[--i], 0);
if (j < timer) {
--position;
lowerScores[i + 1] = j;
} else break;
}
if (position < SCORES) {
lowerScores[position] = timer;
Editor ed = sp.edit();
for (int i = position; i < SCORES; ++i) {
ed.putLong(SCORES_KEYS[i], lowerScores[i]);
}
ed.commit();
}
}
Related
I have given a text in mytts.speak("hi hello hi",parameter,parameter...);
But the words are continuously said without any gap or pause, I want to provide some time gap between words for more clarity.
How could I achieve this ?
If I understand your question correctly, this thread has the answer (by rushi).
Simply add a delay into the TTS queue by splitting the string and loop over the snippets via a for loop:
mytts.speak(snippet, QUEUE_ADD, null);
mytts.playSilentUtterance(2000, QUEUE_ADD, null);
Simply add a comma everywhere you want there to be pauses inserted.
For example: If you want the following web address to be said slower, enter it as a, t, t, r, s.gov
I realize this may not be suitable for some applications, but it definitely works.
This is how I put a longer pause between each word:
//initialize and declare TextToSpeech as tts
//"line" is the String you are trying to speak
char ch = '';
String temp = "";
for(int counter = 0; counter < line.length; counter++)
{
ch = charAt(counter);
temp = temp + ch;
if(ch == ' ' || counter == (line.length() - 1))
{
tts.speak(temp, TextToSpeech.QUE_ADD, null, null);
tts.playSilentUtterance(1000, TextToSpeech.QUEUE_ADD,null);
temp = "";
}
}
Try adding '/ / / / /' to your text. It should give you it some breathing room. If you want a longer pause, try adding more.
You can split you sentence in words and speak them in a for loop in a new thread. Splitting the phrase will give you a little delay, but if you want a longer one you could work on thread and make them wait.
It would be something like this:
final Handler h = new Handler();
String[] words = text.split(" ");
for (final CharSequence word : words) {
Runnable t = new Thread() {
#Override
public void run() {
m_TTS.speak(word, TextToSpeech.QUEUE_ADD, null, "TTS_ID");
}
};
h.postDelayed(t, 1000);
}
I am working with numbers, I get an int from shared preferences, I do some maths and then
I want to do something IF the result is situated between 2 numbers.
SharedPreferences settings = getApplicationContext().getSharedPreferences("shared", Context.MODE_PRIVATE);
int A = settings.getInt("A", 1);
int B = settings.getInt("B", 1);
operation = (TextView) findViewById(R.id.imc );
operation.setText(A*B);
String operation;
if (SOMETHING HERE!) { // is situated between 1 and 20
something
}
What should I do?
Any suggestin will be apreciated.
You just need a simple logic dude.Do the following,
if(A>1 && A<20)
{
//Do what ever you want.
}
I am trying to compare items out of my DB to the value of an EditText (user input). The answer can have multiple answers, seperated by a ','. I first put them into a stringarray and then compare them to the answer. The LevenshteinDistance checks if the answer is more or les good (http://en.wikipedia.org/wiki/Levenshtein_distance#Computing_Levenshtein_distance).
userAnswer = etUserAnswer.getText().toString().toLowerCase();
String[] answers = qAnswer.split(",");
for (String answer : answers) {
if (answer.equals(userAnswer)) {
Toast.makeText(getApplicationContext(), ("Answer Correct"),
Toast.LENGTH_SHORT).show();
tvMessage.setText("You smartass!");
} else {
Toast.makeText(getApplicationContext(), ("Wrong"),
Toast.LENGTH_SHORT).show();
points = points - 4;
String answerGood = answer.toLowerCase();
LevenshteinDistance lDistance = new LevenshteinDistance();
int comparisonCheck = lDistance.computeLevenshteinDistance(
userAnswer, answerGood);
if (comparisonCheck == 1) {
tvMessage.setText("Almost there, but not quite yet!");
} else if (comparisonCheck > 1) {
tvMessage.setText("Are you serious, totally wrong?!");
}
}
}
Suppose I am having the answers for a question in the DB as follows: tree,test,radio
I am having two problems:
1. When I type "radi" it gives me 'Almost there...' which is good. It should also give me this if I enter "tes", but instead it gives me the 'Are you serious,...' line. I guess it keeps comparing to the last one.
2. Every time I type in something which is not correct, I get -12 instead of -4. I suppose this is due to the fact I am having three answers and it loops three times.. but I don't know how I can make it count only once..
Anyone can help me on the way? Thanks!
Assuming you don't need to know the word which gives the least Levenshtein distance, you could modify your loop to find smallest distance only;
userAnswer = etUserAnswer.getText().toString().toLowerCase();
String[] answers = qAnswer.split(",");
LevenshteinDistance lDistance = new LevenshteinDistance();
int minDistance = lDistance.computeLevenshteinDistance(
userAnswer, answers[0].toLowerCase());
for (int i = 1; i < answers.length; ++i) {
minDistance = Math.min(minDistance, lDistance.computeLevenshteinDistance(
userAnswer, answers[i].toLowerCase()));
}
if (minDistance == 0) {
// Correct answer...
} else {
// Wrong answer...
points -= 4;
// etc etc...
}
I having developing simple application, which has just like game. When I have finished game the gave over page display, which as time and score. Now if i want to play that game again and again. How to store that previous all time and score and current finished.
I want to display, all time and score in to the list according to high to low score, after score button was clicked.
I have done shared preferences in gaveover page and that value get from score page. but why not display when i play third time. second time it is ok. third time and so on.. just replacing upward . I don't have enough idea, how to store that all information in to array and display on list. But I have try to use map, but getting not more idea.
I want to display this type of format in to the score page:
Time .............. Score
1:10 .............. 175
2:05 .............. 145
1:15 .............. 110
2:50 ............... 90
Here I have just started little code but not complete and better,
GaveOver.Java
Where just diplay socre , time and mistakes after finish game.
Score.Java
public class Scores extends Activity {
private static String strTime;
private static int intScore;
public static SharedPreferences settings;
public static final String MY_PREFS_NAME = "PrefName";
#Override
protected void onCreate(Bundle savedInstanceState) {
ImageView back, reset, score_home;
super.onCreate(savedInstanceState);
setContentView(R.layout.score);
// lv = (ListView) findViewById(R.id.listView);
getValuesFromGaveOver();
SharedPreferences pref = this.getSharedPreferences(MY_PREFS_NAME, 0);
String data=pref.getString("DATA", "Nothing");
Log.i("horror", "DATA "+data);
}
private void getValuesFromGaveOver() {
SharedPreferences pref = this.getSharedPreferences(MY_PREFS_NAME, 0);
strTime = pref.getString(TIME, "n/a");
intScore = pref.getInt(SCORE, -1);
Log.i("horror", "From Gave Over "+"Time="+strTime+" "+"Score="+intScore);
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences pref = this.getSharedPreferences(MY_PREFS_NAME, 0);
strTime = pref.getString(TIME, "");
intScore = pref.getInt(SCORE, -1);
savePreferences(intScore, strTime);
}
private void savePreferences(int s, String t) {
SharedPreferences sPref = this.getSharedPreferences(MY_PREFS_NAME, 0);
SharedPreferences.Editor edit = sPref.edit();
edit.putString("DATA", strTime+" "+intScore);
edit.commit();
}
}
please give me the good suggestion, how to do it?
The cleanest way would be to use sqlite databases.
Using SharedPreferences is much easier, especially for beginners.
You could do it like that: You save a 3rd item, the actual entry count as SharedPreference.
Everytime you save a new entry you increment this counter.
Then you append the current counter number to the TIME and SCORE keys.
// Saves a new entry | Attention: code not tested!
save(int score, int time){
SharedPreference pref = ...
SharedPreference.Editor editor = ...
int newEntryID = pref.getInt("numEntries", 0) + 1;
editor.setInt("numEntries", newEntryID);
editor.setInt("score" + newEntryID, score);
editor.setString("time" + newEntryID, time);
editor.commit();
}
Assuming "score" is the SharedPreference-Key for SCORE and same for the time.
Reading would be of the same scheme.
for(int i=0; i<numEntries; ++i){
pref.getInt("score" + i, 0);
...
}
using the shared preference you can store both,
1) first you have to store time, once this is done you have to store score mapped on the given time,
you are doing this way,
edit.putString("DATA", strTime+" "+intScore);
But you can take different approach if you have only one player playing at one time,
edit.putString("TIME", strTime);
edit.putString(strTime, strScore);
1:10 .............. 175
So here first you mapped your time with TIME and then you mapped score 175 with 1:10
Hope this will help you
Good idea would be to define Java bean holding score ( say with 2 Fields, time in seconds / points / maybe date / name / whatrever else fields you like to store). You can easily do following with them:
sort in a list and limit their amount ( you do not like to have 10000 of score entries, 100 will be anough )
marshall this list to / from JSON ( Shameless self advertising: https://github.com/ko5tik/jsonserializer )
store JSON in a shared preference or in a private application file (I store up to 100 local highscore entries, and 1000 all time scores and use files)
I have many buttons in my activity (only a subset of which are visible at a time). I currently have something ugly like this:
buttonID[0] = R.id.buttonr1b1;
buttonID[1] = R.id.buttonr1b2;
buttonID[2] = R.id.buttonr1b3;
buttonID[3] = R.id.buttonr1b4;
...
buttonID[35] = R.id.buttonr1b36;
for (int i = 0; i < 36; i++) {
button[i] = (Button) findViewById(buttonID[i]);
}
Is there a more elegant way to reference all of R.id.buttonXXX ? It just looks so wrong and ugly.
Thank you.
Your instincts are correct. It's ugly and in general if you find yourself wanting to do this you should rethink your design.
If your buttons are uniform to the point where you want to loop over them to do something like this, they're probably uniform enough to generate programmatically in the first place (and you can store references as you create them) or use some form of AdapterView. What data needs to be associated with each button? Can you associate it directly using setTag/getTag? Do you need to use IDs here at all?
I'm not sure if this is more elegant or less elegant, because you will lose compile-time checking of your IDs. However, you can construct the IDs by name:
final static String PREFIX = "buttonr1b";
...
Resources res = getResources();
for (int i = 0; i < 36; i++) {
int resID = res.getIdentifier(PREFIX + i , "id", getPackageName());
button[i] = (Button) findViewById(resID);
}
Note: make sure "getPackageName()" would return the appropriate package for your R class, otherwise specify it explicitly.