public class ClientGame extends Activity implements OnClickListener{
Button Answer1, Answer2, Answer3, Answer4;
TextView txtQuest;
DatabaseHelper dbHelper;
Cursor cur;
String qid;
String[] _ids = {};
ArrayList<String> idList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clientgame);
dbHelper = new DatabaseHelper(this);
cur = dbHelper.getRandomQuestion();
startManagingCursor(cur);
qid = cur.getString(cur.getColumnIndex(DatabaseHelper.colID));
idList = new ArrayList<String>();
idList.add(qid); // i take the current id
try
{
Intent extras = getIntent();
String ID = extras.getStringExtra("_id");
idList.add(ID); // add the previous one
_ids = (String[]) idList.toArray(new String[0]);
score = (TextView)findViewById(R.id.textView2);
score.setText("Your score is " + idList);
}
catch(Exception e)
{
}
Answer1 = (Button) findViewById(R.id.button1);
Answer1.setText(answer1);
Answer1.setOnClickListener(this);
Answer2 = (Button) findViewById(R.id.button2);
Answer2.setText(answer2);
Answer2.setOnClickListener(this);
Answer3 = (Button) findViewById(R.id.button3);
Answer3.setText(answer3);
Answer3.setOnClickListener(this);
Answer4 = (Button) findViewById(R.id.button4);
Answer4.setText(answer4);
Answer4.setOnClickListener(this);
}
@Override
public void onPause() {
super.onPause();
finish(); }
@Override
public void onClick(View view) { //correct answer check and store skore and id
if (view == findViewById(R.id.button1))
{
int i = 1;
String ID = cur.getString(cur.getColumnIndex("_id"));
Intent ini = new Intent(ClientGame.this, ClientGame.class);
ini.putExtra("_id", ID);
startActivity(ini);
}
if (view == findViewById(R.id.button2))
{
int i = 1;
String ID = cur.getString(cur.getColumnIndex("_id"));
Intent ini = new Intent(ClientGame.this, ClientGame.class);
ini.putExtra("_id", ID);
startActivity(ini);
}
if (view == findViewById(R.id.button3))
{
int i = 1;
String ID = cur.getString(cur.getColumnIndex("_id"));
Intent ini = new Intent(ClientGame.this, ClientGame.class);
ini.putExtra("_id", ID);
startActivity(ini);
}
if (view == findViewById(R.id.button4))
{
int i = 1;
String ID = cur.getString(cur.getColumnIndex("_id"));
Intent ini = new Intent(ClientGame.this, ClientGame.class);
ini.putExtra("_id", ID);
startActivity(ini);
}
}
} 这里的问题是textview上只显示两个ID。最后一个和当前。我想根据用户的需要显示所有ID。当然不是无限的。那么我怎样才能创建一个arraylist,让我们说十个值,并且每次都存储id?
答案 0 :(得分:2)
您只在列表中添加两个ID,因此行为正确。如果您的活动是多次创建的,并且您想要使用上次添加的值,则必须完成两件事:
将列表声明为静态成员:
static ArrayList idList;
改变你的分配方式:
if(idList == null){ idList = new ArrayList(); }
这将做你想要的。我建议不要再次启动活动,只需在单击按钮时更新TextView中的文本。
EDIT ------
要更新TextView而不是再次启动活动,请执行以下操作:
score.setText(score.getText().toString() + ", " + ID)
我刚刚在现有文本的末尾添加了逗号和新ID。当然,您可能希望以不同的方式对其进行格式化。显示的文本和新文本应该足以获得所需的格式。