我正在尝试创建一个国家/地区列表,用户可以在运行时添加这些国家/地区。
我使用意图&适配器和listview显示国家。
当活动开始" MyCountries"用户点击按钮添加国家/地区时,将启动一项新活动"添加国家",我的问题是为什么我无法在列表中看到任何国家/地区?我发送和接收是否正确? MyCountries的代码:
public class MyCountries extends Activity {
private ListView lv;
private ArrayAdapter<String> adapter;
private ArrayList<String>list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_countries);
//Button compute=(Button)findViewById(R.id.cancel);
lv=(ListView)findViewById(R.id.listView1);
list=new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
Intent i = getIntent();
list = i.getStringArrayListExtra("country&year");
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my_countries, menu);
return true;
}
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), AddCountry.class);
startActivityForResult(intent,1);
}
&#34; AddCountry&#34;
的代码public class AddCountry extends Activity {
private EditText name;
private EditText year;
public String country_name;
public int visited_year;
public ArrayList<String>arr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_country);
name = (EditText) findViewById(R.id.country);
year = (EditText) findViewById(R.id.year);
arr= new ArrayList<String>();
Button button=(Button)findViewById(R.id.add);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
//Toast.makeText(this, "Add was clicked", Toast.LENGTH_LONG).show();
//new activity
Intent sending = new Intent();
country_name = name.getText().toString();
visited_year = Integer.parseInt(year.getText().toString());
for(int i=0;i<arr.size();i++){
arr.add(country_name+""+visited_year);
//startActivity(sending);
}
sending.putStringArrayListExtra("country&year", arr);
}
}
答案 0 :(得分:1)
您要将空列表发送到适配器:
list=new ArrayList<String>();// empty list
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
//在初始化适配器之前从意图(到列表)获取数据并且您不需要通知
list = i.getStringArrayListExtra("country&year");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);