Search code examples
javaandroidsqliteandroid-sqlite

Delete data in database with the insertion function


I made a TextView that displayed value with multiple line and each line contains 3 fields as shown in the figure below: https://i.sstatic.net/fOZaC.png I want to display in the database the integers only so the idea that I deployed is that we will delete the strings " and app:" at each insertion to keep the numbers only as present in the code below :

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.next();
        cv.put("nom ",line);
        if ((line.trim().length()>0)&& (line.trim().equals("<info>")) &&(line.trim().equals("app:"))){
            db.delete("contact",null,null);
            db.insert("contact", null, cv);
        }
    }

but it dosen't function . is there any way to do that?


Solution

  • You can use substring() to remove the first 10 chars from each line

    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.next().trim();
            if (line.startsWith("<info>app:")) {
                line = line.substring(10).trim();
            }
            if (line.length() > 0) {
                cv.put("nom", line);
                db.insert("contact", null, cv);
            }
        }
    }
    

    Another way to do it is by removing all non-numeric chars:

    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.next().replaceAll("[^\\d]", "");
            if (line.length() > 0) {
                cv.put("nom", line);
                db.insert("contact", null, cv);
            }
        }
    }