Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert data to sqlite through user input?

I am a beginner in mobile application building. I have tried to put insert data function in my android studio but it seems that those insert function doesn't work and the input data can't be inserted. Please help.

I put some code in MainActivity.java and DatabaseHelper.java. It doesn't give me any error report but when I have tried to run the emulator and input data, my input can be inserted to sqlite database.

//oncreateMainActivity

super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myDb = new DatabaseHelper(this);

        name2 = findViewById(R.id.name2);
        birthdate2 = findViewById(R.id.birthdate2);
        area2 = findViewById(R.id.area2);
        receiver2 = findViewById(R.id.receiver2);

        submit2 = findViewById(R.id.submit2);
        submit2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v)
            {
                name = name2.getText().toString();
                birth = birthdate2.getText().toString();
                area = area2.getText().toString();
                receiver = receiver2.getText().toString();
...
        insertData2 (name, birth, area, receiver);
...

public void insertData2 (String name,String birth,String area, String receiver){
        boolean add_data = myDb.insertData(name,birth,area,receiver);

        if (!add_data){
            Toast.makeText(MainActivity.this,"Something went wrong><", Toast.LENGTH_LONG).show();
        }
        else{
            Toast.makeText(MainActivity.this,"Success to add data!", Toast.LENGTH_LONG).show();
        }

    }

//DatabaseHelper.java

public boolean insertData(String childname ,String bornday, String areaprogram, String receiverid){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL1, childname);
        contentValues.put(COL2, bornday);
        contentValues.put(COL3, areaprogram);
        contentValues.put(COL4, receiverid);

        long result = db.insert(TABLE_NAME, null, contentValues);

        if(result == -1){
            return false;
        }
        else{
            return true;
        }
    }
like image 323
Nesh_A Avatar asked Dec 10 '25 22:12

Nesh_A


1 Answers

It doesn't give me any error report

You should use try and catch block to see what is happening.

try{
   boolean add_data = myDb.insertData(name,birth,area,receiver);
   Toast.makeText(MainActivity.this,"Success to add data!", Toast.LENGTH_LONG).show();
}catch(Exception e){
   e.printStackTrace();
}
like image 138
John Joe Avatar answered Dec 12 '25 12:12

John Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!