Search code examples
javaandroiddatabasesqliteandroid-sqlite

Store data in Database Android


i made a TextView that displayed value with multiple line
and i want to keep that value in a SQLite database. this is the code i use:

public void AddContact(Contact c)
{
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues cv=new ContentValues();
    cv.put("nom",c.getNom());
    Scanner s = new Scanner(String.valueOf(cv));
    while (s.hasNextLine()){
        String line = s.nextLine();
        db.insert("contact",line,cv);
        
    }

the problem is when i save the value, the whole value is inserted into one cell. i want the value to be separated per line then inserted into a single cell for each line despite I am using Scanner method with the insertion data but it dosen't function. is there any way to do that?


Solution

  • In your code, this line:

    cv.put("nom",c.getNom());
    

    assigns the full string of c.getNom() to the ContentValues object and this is what you insert in the table.
    You must assign each row of c.getNom() to cv and insert it, one at each iteration of the while loop:

    public void AddContact(Contact c) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        Scanner s = new Scanner(c.getNom());
        while (s.hasNextLine()) {
            String line = s.nextLine();
            cv.put("nom", line); 
            db.insert("contact", null, cv);
        }      
    }