Home > Net >  How to create an android CRUD app using SQLite database, HashMap and HashSet to perfrom crud operati
How to create an android CRUD app using SQLite database, HashMap and HashSet to perfrom crud operati

Time:05-17

I have started coding with some basic ideas and created a class called Student to create object hashmap to perform insertion and updating. And a Class called DatabaseHelper to perform SQLite operations and main activity is shown below.

Student.java is a class in which variables such as roll no,studentName, standard, course, and percentage and a parameterized constructor with all variables.

 package com.app.myapplication.Model;
    import java.io.Serializable;

    public class Student implements Serializable {
       public String rollNo;
       public String studentName;
       public String standard;
       public String course;
       public String CGPA;

       public Student(String rollNo, String studentName, String standard,String course, String CGPA) {
        this.rollNo = rollNo;
        this.studentName = studentName;
        this.standard = standard;
        this.course = course;
        this.CGPA = CGPA;
    }}

MainActivity.java

    public class MainActivity extends AppCompatActivity {

    private DatabaseHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db= new DatabaseHelper(MainActivity.this);
        HashMap<String,Student> map=new HashMap<String,Student>();
        Student student1 = new Student("101","Linet","XII","Commerce","89%");
        map.put("1",student1);
        Boolean insert_student_details = db.InsertStudentDetails(map);
        if(insert_student_details){
            Log.v("Success msg","Student details insertion success");
        }else{
            Log.v("Failure msg","Student details insertion failed");
        }
    }
    }

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 4;
    SQLiteDatabase database;
    String TBL_STUDENT = "tbl_student";

    public DatabaseHelper(@Nullable Context context) {
        super(context, "studentDb", null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS "   TBL_STUDENT  "(id INTEGER PRIMARY KEY " " AUTOINCREMENT,rollNo TEXT,studentName TEXT,standard TEXT,course TEXT,subject TEXT,CGPA TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " TBL_STUDENT);
        onCreate(db);

    }
    
    public Boolean InsertStudentDetails(HashMap<String,Student> studentMap) {
        long result = 0;
        database = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        for(HashMap.Entry<String,Student> entry : studentMap.entrySet()) {
            String key=entry.getKey();
            Student student = entry.getValue();
            contentValues.put(key, student.rollNo);
            contentValues.put(key, student.studentName);
            contentValues.put(key, student.standard);
            contentValues.put(key, student.course);
            contentValues.put(key, student.CGPA);
            Log.v("msg", "rollNo:" student.rollNo);
            Log.v("msg", "studentName:" student.studentName);
            Log.v("msg", "standard:" student.standard);
            Log.v("msg", "course:" student.course);
            Log.v("msg", "CGPA:" student.CGPA);

            result = database.insert("tbl_student", null, contentValues);
           // result = database.insert(TBL_STUDENT,null, contentValues);
        }

        
        if (result == -1) {
            Log.v("msg", "Failed");
            //Remove_all_values_in_the_table_request();
            return false;
        } else {
            Log.v("msg", "Success");
            return true;
        }
    }
    public boolean updateStudent(HashMap<String,Student> studentMap,String rollNo){
        database = this.getReadableDatabase();
        long res = 0;
        Log.v("tbl_interval_timer", "rollNo   "   rollNo);
        String query = "select * from "   TBL_STUDENT   " where rollNo ='"   rollNo   "'";
        Cursor cursor = database.rawQuery(query, null);
        int count = cursor.getCount();
        if(count>0) {
            Log.v("msg", "Data exist");
            ContentValues contentValues = new ContentValues();
            for(HashMap.Entry<String,Student> entry : studentMap.entrySet()) {
                String key = entry.getKey();
                Student student = entry.getValue();
                contentValues.put(key, student.rollNo);
                contentValues.put(key, student.studentName);
                contentValues.put(key, student.standard);
                contentValues.put(key, student.course);
                contentValues.put(key, student.CGPA);
                Log.v("msg", "rollNo:"   student.rollNo);
                Log.v("msg", "studentName:"   student.studentName);
                Log.v("msg", "standard:"   student.standard);
                Log.v("msg", "course:"   student.course);
                Log.v("msg", "CGPA:"   student.CGPA);
                res = database.update(TBL_STUDENT, contentValues, "rollNo = ? ",
                        new String[]{String.valueOf(rollNo)});
            }
            if (res == -1) {
                Log.v("updateCyclicTimer msg", "Failed");
                //Remove_all_values_in_the_table_request();
                return false;
            } else {
                Log.v("updateCyclicTimer msg", "Success");
                return true;
            }
        }else{
            Log.v("updateCyclicTimer msg", "Data does not exist");
            return false;
        }

    }

    }

I am getting errors as shown below.

com.app.myapplication E/SQLiteLog: (1) near "1": syntax error in "UPDATE tbl_student SET 1=? WHERE rollNo = ?"
android.database.sqlite.SQLiteException: near "1": syntax error (code 1 SQLITE_ERROR): , while 
compiling: UPDATE tbl_student SET 1=? WHERE rollNo = ?
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)

E/SQLiteLog: (1) near "1": syntax error in "INSERT INTO tbl_student(1) VALUES (?)"
E/SQLiteDatabase: Error inserting 1=89%
android.database.sqlite.SQLiteException: near "1": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO tbl_student(1) VALUES (?)

How to resolve this?

CodePudding user response:

            map.put("1",student1); 
            Boolean insert_student_details = db.InsertStudentDetails(map);

            String key=entry.getKey();  // Is always 1 
            Student student = entry.getValue();
            Student student = entry.getValue();
            contentValues.put(key, student.rollNo);
            contentValues.put(key, student.studentName);
            contentValues.put(key, student.standard);
            contentValues.put(key, student.course);
            contentValues.put(key, student.CGPA);


When adding something to your contentValues you need to enter the column name instead of the key, so your sql statement would look something like this: insert into table_student(1,1,1,1,1) values (...) but it needs to look like insert into table_student(rollNo,studentName,standard,course,CGPA) values (...)

Do it somehow like this at your Update and Insert Method:

            map.put("1",student1); 
            Boolean insert_student_details = db.InsertStudentDetails(map);

            String key=entry.getKey();  // Is always 1 
            Student student = entry.getValue();
            Student student = entry.getValue();
            contentValues.put('rollNo', student.rollNo);  
            contentValues.put('studentName', student.studentName);
            contentValues.put('standard', student.standard);
            contentValues.put('course', student.course);
            contentValues.put('CGPA', student.CGPA);


I dont know your column names, so i assumed they are rollNo, studentName, standard, course and CGPA.

I hope this helps ;)

  • Related