Search code examples
androidandroid-edittextandroid-sharedpreferences

how to store values of dynamically added edit text in shared preferences


My issue is, I am creating below view dynamically.

  1. Edit Text (Organization Name)
  2. Linear Layout with Vertical Orientation which contains Edit Text(Job 1), Edit Text(Job 2), Edit Text(Job 3),... and so on depending upon user click on Add Job button.
  3. Button (Add Job) Clicking on this button adds a Edit Text for job in the above linear layout which is containing all the jobs for a specific organization.
  4. Button (Add Organization) clicking on this button creates above three views again ie. Organization Name(Edit Text), Linear Layout(Edit Text(Job 1), Edit Text(Job 2), Edit Text(Job 3)...and so on), Button (Add Job).

My problem is how do I store the values of each edit text in a structured way in shared preferences like below.

Organization 1

  1. Job 1
  2. Job 2
  3. Job 3
  4. .....
  5. .....
  6. .....

Organization 2

  1. Job 1
  2. Job 2
  3. .....
  4. .....

etc.

Why I want to store the values in the shared preferences is because, Once the user navigates to some other page after entering all the details about organization and jobs, and then if he/she returns back to the same page, all the previously entered details(Organization and Job details) must be there.

Please suggest me how to do it, any ideas will be highly appreciated.

Thanks.


Solution

  • I would create an Organization Class which will look something likse this:

    Class Organization {
    
          String name;
          ArrayList<String> jobsList;
    }
    

    Then I would add the needed info from your UI, serialize the object and save it to SharedPerfrences:

          Gson gson = new Gson();
          String dataToSave = gson.toJson(organization);
          //save the data using SharedPerfrences