Nesh_A :
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;
}
}
forpas :
The 1st parameter of the method put()
is the name of the column, but you pass the value.
Change to this (of course replace with your column names like "Name"
, "Birthdate"
, etc):
public boolean insertData(String Name,String Birthdate,String Area, String ID){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ColunNameForName, Name);
contentValues.put(ColunNameForBirthdate, Birthdate);
contentValues.put(ColunNameForArea, Area);
contentValues.put(ColunNameForID, ID);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1){
return false;
}
else{
return true;
}
}