Reputation: 81
I am trying to update the contents of the list object which has been passed to the adapter inorder to create a GridView. Here is the code:
public class GameActivity extends Activity {
List<String> nums;
GridView sudoku_grid;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temp);
sudoku_grid=(GridView)findViewById(R.id.sudoku_grid);
nums= Arrays.asList("1","2","3","5","7","8","2","3","1","9","3","3","1");
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,nums);
sudoku_grid.setAdapter(adapter);
}
public void trial(View view)
{
Runnable r=new Runnable() {
@Override
public void run() {
nums.add("7");
adapter.notifyDataSetChanged();
}};
new Thread(r).start();
}
trial() executes every time a button is clicked. As soon as the thread in trial() starts, instead of the contents being updated, it results in starting the previous activity. Can anyone tell me where am I going wrong?
Upvotes: 2
Views: 53
Reputation: 6383
I think you can not run notifyDataSetChanged()
in your own thread. It needs to run on UI Thread.
Try:
GameActivity.this.runOnUiThread(new Runnable() {
...
instead.
Upvotes: 2
Reputation: 1372
You need to pass the nums
object again to the adapter.
Create a class
that extends
ArrayAdapter<String>
as follows:
class MyArrayAdapter extends ArrayAdapter<String>{
List<String> nums;
public MyArrayAdapter(Context context,int itemID,List<String> nums){
this.nums=nums;
}
@ovverride
public int getCount() {
return nums.size();
}
public void changeObjects(List<String> nums){
this.nums=nums;
this.notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent){
//.... Implement own code
}
}
Let me know if there is any more problem or queries.
Upvotes: 2