简体   繁体   中英

passing data from an activity to an listactivity or listview

need help on passing data from an activity to an listactivity or listview for an android app. im having problems on passing data to a listview.

what the app do is from addact class the user can input things to do and in the viewact class this will display the activies add by the user in 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();
                }

            }
        });

    }

}

You cannot access your Intent until inside onCreate() and you should perform some checks to make sure your app won't crash if the data doesn't exist:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM