I’m pretty new to android-programming.
Can you help me, what i need to show local highscores table in this activity?
Am I need to create some TextViews in it and in xml?
Where I can found some examples to see how it works?
Highscore activity
import game.main.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class Highscores extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.highscores);
}
}
HighscoreList class
package game.objectsmain;
import android.content.Context;
import android.content.SharedPreferences;
public class HighScoresList {
private SharedPreferences preferences;
private String names[];
private long score[];
public HighScoresList(Context context)
{
preferences = context.getSharedPreferences("Highscore", 0);
names = new String[5];
score = new long[5];
for (int x=0; x<5; x++)
{
names[x] = preferences.getString("name"+x, "-");
score[x] = preferences.getLong("score"+x, 0);
}
}
public String getName(int x)
{
//get the name of the x-th position in the Highscore-List
return names[x];
}
public long getScore(int x)
{
//get the score of the x-th position in the Highscore-List
return score[x];
}
public boolean inHighscore(long score)
{
//test, if the score is in the Highscore-List
int position;
for (position=0; position<10 && this.score[position] > score; position++);
if (position==5) return false;
return true;
}
public boolean addScore(String name, long score)
{
//add the score with the name to the Highscore-List
int position;
for (position=0; position<10 && this.score[position] > score; position++);
if (position==5) return false;
for (int x=4; x > position; x--)
{
names[x]=names[x-1];
this.score[x]=this.score[x-1];
}
this.names[position] = new String(name);
this.score[position] = score;
SharedPreferences.Editor editor = preferences.edit();
for (int x=0; x<5; x++)
{
editor.putString("name"+x, this.names[x]);
editor.putLong("score"+x, this.score[x]);
}
editor.commit();
return true;
}
}
P.S.
btw is it ok to use shared preferences or use sqlite database is much better?
If you want your highscores to be available on the internet, take a look at OpenFeint.
Now, if its just a local table,
There’s nothing wrong with using eithor
SharedPreferencesor SQLite Database.I can tell you, using a SQLite Database will be much easier than SharedPreferences.
(Why? Because you wont have to manually sort, validate, check for duplicates in the case of Databases…A Simple Query/Statement can list the top 10, truncate old scores, etc instantly.
To Display your High Score Table, Use a
ListActivityand Custom List Adapter to display each Entry. Here‘s a nice relevant tutorial for the same.