使用意图发送和接收Arraylist?安卓

杰森

我正在尝试创建一个国家/地区列表,该列表将由用户在运行时添加。

我正在使用意图和适配器以及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);
}

“ AddCountry”的代码

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);

    }
}
纳文·拉杰·潘迪(NavinRaj Pandey)

您正在向适配器发送空列表:

list=new ArrayList<String>();// empty list

adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);

//在初始化适配器之前从intent(到您的列表)中获取数据,而无需通知

  list = i.getStringArrayListExtra("country&year");

       adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
        lv.setAdapter(adapter);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章