Android Practical.12
Android Practical.12
12
Create an application to insert, update and delete a record from the database.
Activitymain.xml
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"/>
<Button
android:id="@+id/buttonInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextName"
android:text="Insert"/>
<Button
android:id="@+id/buttonUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonInsert"
android:text="Update"/>
<Button
android:id="@+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonUpdate"
android:text="Delete"/>
</RelativeLayout>
Mainactivity.java
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize views
editTextName = findViewById(R.id.editTextName);
buttonInsert = findViewById(R.id.buttonInsert);
buttonUpdate = findViewById(R.id.buttonUpdate);
buttonDelete = findViewById(R.id.buttonDelete);
buttonInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
insertRecord();
}
});
buttonUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateRecord();
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
@Override
return;
}
ContentValues values = new ContentValues();
values.put("name", name);
long result = database.insert("MyTable", null, values);
if (result != -1) {
Toast.makeText(this, "Record inserted successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Failed to insert record", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Failed to update record", Toast.LENGTH_SHORT).show();
}
}
@Override
}
}
}