简体   繁体   中英

Save data from Main activity to a ListView activity

I have a MainAtivity which has some EditText and 2 button. Save button will save user input to ListView and List button to show ListView (which I display in second activity). Is there anyway to collect data from multiple inputs then pass it to other activity. And after get that data how to combine it to a List item. Please show me some code and explain cause I'm a beginner.

I have read some post and they suggest use startActivityForResult, intent, bundles but I still don't understand.

This is my Main class:

public class MainActivity extends AppCompatActivity {

String str, gender, vaccine, date;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button okay = (Button) findViewById(R.id.btnOk);
    Button list = (Button) findViewById(R.id.btnList);

    EditText name = (EditText) findViewById(R.id.inputName);
    EditText address = (EditText) findViewById(R.id.inputAdd);
    EditText phone = (EditText) findViewById(R.id.inputPhone);

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
    RadioButton female = (RadioButton) findViewById(R.id.inputFemale);
    RadioButton male = (RadioButton) findViewById(R.id.inputMale);

    CheckBox first = (CheckBox)findViewById(R.id.inputFirst);
    CheckBox second = (CheckBox)findViewById(R.id.inputSecond);
    CheckBox third = (CheckBox)findViewById(R.id.inputThird);

    EditText datefirst = (EditText) findViewById(R.id.dateFirst);
    EditText datesecond = (EditText) findViewById(R.id.dateSecond);
    EditText datethird = (EditText) findViewById(R.id.dateThird);

    TextView result = (TextView)findViewById(R.id.textResult);


    okay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(female.isChecked()) gender = female.getText().toString();
            if(male.isChecked()) gender = male.getText().toString();
            if(first.isChecked()) {
                vaccine = first.getText().toString();
                date = datefirst.getText().toString();
            }
            if(second.isChecked()) {
                vaccine = second.getText().toString();
                date = datesecond.getText().toString();
            }
            if(third.isChecked()) {
                vaccine = third.getText().toString();
                date = datethird.getText().toString();
            }

            str = name.getText().toString() + "\n" + address.getText().toString() + "\n" + phone.getText().toString() + "\n" +
                    gender + "\n" + vaccine + "\n" + date;


            result.setText(str);
            Toast.makeText(getApplicationContext(),result.getText().toString(),Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(MainActivity.this, PersonView.class);
            intent.putExtra("NAME",name.getText().toString());
            startActivity(intent);

        }
    });

    list.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, PersonView.class);
            startActivity(intent);
        }
    });

}

}

This is my ListView class: public class PersonView extends AppCompatActivity {

ArrayList<Person> listPerson;
PersonListViewAdapter personListViewAdapter;
ListView listViewPerson;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

    Intent intent = getIntent();
    String message = intent.getStringExtra("NAME");


    Button back = (Button) findViewById(R.id.btnBack);

    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(PersonView.this, MainActivity.class);
            //startActivityForResult(intent,2);
        }
    });

    listPerson = new ArrayList<>();
    listPerson.add(new Person("Lieu Mai","25 Mac Dinh Chi", "0786867073", "female","3 injection", "24/07/2000"));

    personListViewAdapter = new PersonListViewAdapter(listPerson);

    listViewPerson = findViewById(R.id.listPerson);
    listViewPerson.setAdapter(personListViewAdapter);
}


class Person {
    String name, address, phone, gender, vaccine, date;

    public Person( String name, String address, String phone, String gender, String vaccine, String date) {
        this.name = name;
        this.address = address;
        this.phone = phone;
        this.gender = gender;
        this.vaccine = vaccine;
        this.date = date;
    }
}

class PersonListViewAdapter extends BaseAdapter {

    final ArrayList<Person> listPerson;

    PersonListViewAdapter(ArrayList<Person> listPerson) {
        this.listPerson = listPerson;
    }

    @Override
    public int getCount() {

        return listPerson.size();
    }

    @Override
    public Object getItem(int position) {

        return listPerson.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View viewPerson;
        if (convertView == null) {
            viewPerson = View.inflate(parent.getContext(), R.layout.person_view, null);
        } else viewPerson = convertView;


        Person person = (Person) getItem(position);
        ((TextView) viewPerson.findViewById(R.id.txtName)).setText(String.format("Name: %s", person.name));
        ((TextView) viewPerson.findViewById(R.id.txtAddress)).setText(String.format("Address : %s", person.address));
        ((TextView) viewPerson.findViewById(R.id.txtPhone)).setText(String.format("Phone number: %s", person.phone));
        ((TextView) viewPerson.findViewById(R.id.txtGender)).setText(String.format("Gender: %s", person.gender));
        ((TextView) viewPerson.findViewById(R.id.txtVaccine)).setText(String.format("Vaccine: %s", person.vaccine));
        ((TextView) viewPerson.findViewById(R.id.txtDate)).setText(String.format("Date: %s", person.date));

        return viewPerson;
    }
}

}

You should look into the Singleton pattern. It is very simple as there is no external DB. What it essentially is a class that manages the data and lets other classes and activities use the data while not allowing duplication.

You have a model Person

public class Person {
    private String name;
    public String address;
    ...
    constructors and getters and setters

Create a class PersonsSingelton something like this.

public class PersonManagerSingleton {
    private PersonManagerSingleton() {
        loadPersonsDataSet();
    }

    private static PersonManagerSingleton instance = null;

    public static PersonManagerSingleton getInstance() { 
        // if there is a instance already created use that instance of create new instance
        // instance created in MainActivity and you try to create a new instance in Details 
        // should not happen as that will cause data duplication.
        if (instance == null) {
            instance = new PersonManagerSingleton();
        }
        return instance;
    }

    private ArrayList<Person> personList = new ArrayList<Person>();

    private void loadPersonsDataSet() {
        this.personList.add(new Person(...));
        this.personList.add(new Person(...));
        this.personList.add(new Person(...));
        this.personList.add(new Person(...));
    }

    public ArrayList<Person> getpersonList() {
        return personList;
    }

    public Person getPersonByID(int PersonNumber) {
        for (int i = 0; i < this.personList.size(); i++) {
            Person curPerson = this.personList.get(i);
            if (curPerson.getNumber() == PersonNumber) {
                return curPerson;
            }
        }
        return null;
    }
    // methods for adding a new person used in Activity with the form.
    // other methods ...
}

This would be like a state in React. of the State Manager. Your person adapter constructor has to accept an ArrayList<Person> listPerson . So modify the activity passing the data to pass only the position of the ListView clicked. You need to modify your Adapter for that.

Use the Singleton created to access the data.

PersonManagerSingleton personSingelton = PersonManagerSingleton.getInstance();
ArrayList<Person> listPerson = personSingelton.getPersonList();
PersonAdapter Person = new PersonAdapter(listPerson);

So now only things left is to modify the Persons adapter to pass position using Intent and nothing else. and then you can use the instance of Singleton in other files to access the data using the listPerson.get(position) and using getters and setters.

Link to a project like this. https://github.com/smitgabani/anroid_apps_using_java/tree/main/pokemon_app

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