1

Hi i cannot add more than one user in the database.I want to add all the users present in my arrayLits . My code is:

ArrayList < User > u = new ArrayList <  > ();
User user1 = new User("hely", "rrr", "wdssa", "2");
User user2 = new User("jess", "rrr", "sds", "2");
User user3 = new User("mark", "merinos", "dfgrh", "2");
u.add(user1);
u.add(user2);
u.add(user3);
ArrayList < User > user = u;
new Thread(new Runnable() {
     @ Override
    public void run() {
        Model_user.getInstance(getApplicationContext()).addUsers(user.toArray(new User[0]));
        Log.d("main_activity_user", "ok user add");
    }
}).start();

And My model is:

public class Model_user {
    private static Model_user theinstance = null;
    private ArrayList<User> user_list;
    private static AppDatabase userDAOs = null;
    public static synchronized Model_user getInstance() {
        if (theinstance == null) {
            theinstance = new Model_user();
        }
        return theinstance;
    }

    public static synchronized Model_user getInstance(Context c) {
        if (theinstance == null) {
            userDAOs = Room.databaseBuilder(c, AppDatabase.class, "userdb").build();
            theinstance = new Model_user();
        }
        return theinstance;
    }

    private Model_user() {
        user_list = new ArrayList<User>();

    }
    public void addUsers(User[] s) {
        Log.d("main_activity_uid", "ok sta partendo");
        userDAOs.userDAO().insertAll(s);
        user_list.addAll(Arrays.asList(s));
        Log.d("main_activity_uid", "ok hai inserito crrettamente");
        return;
    }

So i add only the first user to the database and not the others. How can I add all users in the database?

Robert
  • 39,162
  • 17
  • 99
  • 152
Elly
  • 345
  • 1
  • 8

1 Answers1

-1

Remove "new User[0]" from addUsers(user.toArray(new User[0]))

It should be addUsers(user.toArray())

Harsh Mishra
  • 1,975
  • 12
  • 15
  • Arraylist.toArray() will only return an `Object[]` not an `User[]`. As I don't think `addUsers` willa ccept `Object[]` your answer is wrong. `user.toArray(new User[0])` is a common way to tell `toArray` to create an `User[]` array https://stackoverflow.com/a/9572820/150978 – Robert Jun 11 '22 at 16:36