将数据从活动传递到listactivity或listview

时间:2012-11-24 23:00:47

标签: android android-intent android-listview

需要帮助将数据从活动传递到Android应用程序的listactivity或listview。我在将数据传递到列表视图时遇到问题。

应用程序所做的是来自addact类,用户可以输入要做的事情 在viewact类中,这将显示用户在listview

中添加的活动
public class addact extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newact);
        Button btn1 = (Button)findViewById(R.id.btnsave);
       final EditText et1 = (EditText)findViewById(R.id.etactivity);
      btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent it = new Intent(addact.this, viewact.class);
            it.putExtra("thekey", et1.getText().toString());
            startActivity(it);
        }
    });
    }
}



public class viewact extends ListActivity {

    String addToDo =getIntent().getExtras().getString("thekey");
     String[] toDoAct = new String[] {addToDo };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewact);



        setListAdapter(new ArrayAdapter<String>(this, R.layout.viewact,toDoAct));

        ListView listView = getListView();

        listView.setTextFilterEnabled(true);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                for (int i=0; i < 2; i++)
                {
                    Toast.makeText(getApplicationContext(),
                            ((TextView) view).getText(), Toast.LENGTH_LONG).show();
                }

            }
        });

    }

}

1 个答案:

答案 0 :(得分:0)

onCreate()内部之前无法访问您的意图,您应该执行一些检查以确保在数据不存在时您的应用不会崩溃:

String addToDo = "";
String[] toDoAct;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewact);

    Intent intent = getIntent();
    if(intent != null) {
        addToDo = intent.getStringExtra("thekey", "");
    }
    toDoAct = new String[] { addToDo };