我在这里有一个非常简单的实施高分排行榜的方法,可以将用户提供的姓名与他或她的分数一起保存。 不幸的是,返回高分活动后,RecyclerView将仅显示以前填充的分数,而不是刚刚输入的新分数。我在异步任务中使用notifyDatasetChanged()方法。仍然没有成功。非常感谢任何指针。
高分活动:
Map
}
和recyclerview适配器:
公共类ScoreRecViewAdapter扩展了RecyclerView.Adapter {
public class HighscoreActivity extends AppCompatActivity implements View.OnClickListener{
SQLiteDatabase db;
ArrayList<String> nameList;
ArrayList<String> scoreList;
RecyclerView recyclerView;
ScoreRecViewAdapter scoreRecViewAdapter;
Button buttonStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_highscore);
buttonStart = findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(this);
// create lists and table
nameList = new ArrayList<>();
scoreList = new ArrayList<>();
db = this.openOrCreateDatabase("Scores", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS scores(name VARCHAR, score VARCHAR)");
//Cursor c = db.rawQuery("SELECT * FROM scores", null);
Cursor c = db.rawQuery("SELECT * FROM scores ORDER BY score DESC", null);
// Fill list
int nameIndex = c.getColumnIndex("name");
int scoreIndex = c.getColumnIndex("score");
while ( c.moveToNext() ){
nameList.add(c.getString(nameIndex));
scoreList.add(c.getString(scoreIndex));
}
// put data in rec view
recyclerView = findViewById(R.id.recView);
scoreRecViewAdapter = new ScoreRecViewAdapter(this, nameList, scoreList);
recyclerView.setAdapter(scoreRecViewAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// enter new user data
Intent getter = getIntent();
String nameExtra = getter.getStringExtra("name");
String scoreExtra = getter.getStringExtra("score");
if( nameExtra != null && scoreExtra != null) {
// perform async task
new InsertIntoDatabase().execute(nameExtra, scoreExtra);
}
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.buttonStart) {
Intent actorQuizz = new Intent(this, MainActivity.class);
startActivity(actorQuizz);
}
}
public class InsertIntoDatabase extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... strings) {
db.execSQL("INSERT INTO scores (name, score) VALUES ('" + strings[0] + "', '" + strings[1] +"')");
Log.i("score saved", "success");
return "success";
}
@Override
protected void onPostExecute(String s) {
//nameList.clear();
//scoreList.clear();
Cursor c = db.rawQuery("SELECT * FROM scores", null);
// Fill list
int nameIndex = c.getColumnIndex("name");
int scoreIndex = c.getColumnIndex("score");
while ( c.moveToNext() ){
nameList.add(c.getString(nameIndex));
scoreList.add(c.getString(scoreIndex));
}
scoreRecViewAdapter.notifyDataSetChanged();
}
}