это фрагмент моего файла AndroidManifest.xml:
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools">
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name = "android.permission.INTERNET" />
<application
android:allowBackup = "true"
android:dataExtractionRules = "@xml/data_extraction_rules"
android:fullBackupContent = "@xml/backup_rules"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:supportsRtl = "true"
android:theme = "@style/Theme.Androidstudio"
tools:targetApi = "31">
<activity
android:name = ".MainActivity"
android:exported = "true">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Я уже проверил файл Styles.xml моего проекта, чтобы убедиться, что @style/Theme.Androidstudio определен правильно и существует. Однако Android Studio, похоже, не может разрешить этот символ.
Я пробовал очистить и пересобрать проект, синхронизировать файлы Gradle и даже перезапустить Android Studio, но ошибка не устранена.
Помимо устранения этой ошибки, мне также нужны рекомендации по реализации операций CRUD в моем приложении Kotlin для Android. Мы будем очень признательны за любые советы, ресурсы или примеры, связанные с операциями CRUD в Котлине.
Обратитесь к решению ниже. Я также предоставил пошаговую процедуру реализации операций CRUD в Kotlin:
CRUD ОПЕРАЦИЯ С SQLITE
Перейдите в AndroidManifest.xml.
добавить эти разрешения -
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name = "android.permission.INTERNET" />
под тегом и над тегом
как здесь
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools">
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name = "android.permission.INTERNET" />
<application
android:allowBackup = "true"
android:dataExtractionRules = "@xml/data_extraction_rules"
android:fullBackupContent = "@xml/backup_rules"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:supportsRtl = "true"
android:theme = "@style/Theme.Androidstudio"
tools:targetApi = "31">
<activity
android:name = ".MainActivity"
android:exported = "true">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
}
После class MainActivity : AppCompatActivity() {
добавьте эту строку
private lateinit var db:SQLiteDatabase
после setContentView(R.layout.activity_main)
добавьте эту строку
db = openOrCreateDatabase("employeemanager.db", MODE_PRIVATE,null)
Создание таблицы
val createTableQuery = "CREATE TABLE IF NOT EXISTS employee(employeeid INT PRIMARY KEY, name TEXT, phonenumber INT, country TEXT)"
db?.execSQL(createTableQuery)
Вставка в таблицу
val insertQuery = "INSERT INTO employee VALUES("+idtext+",'"+nametext+"',"+phonenumber+",'"+country+"')"
db?.execSQL(insertQuery)
Toast.makeText(this@MainActivity, "Inserted Data Successfully!",Toast.LENGTH_SHORT).show()
Добавление извлеченных данных в счетчик
val fetchdata = "SELECT DISTINCT country FROM employee"
val cursor = db?.rawQuery(fetchdata,null)
val countries = ArrayList<String>()
while(cursor!!.moveToNext()) {
val country1 = cursor.getString(0)
countries.add(country1)
}
cursor?.close()
var spinner = findViewById<Spinner>(R.id.spinner)
val spinneradapter = ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,countries)
spinneradapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = spinneradapter
spinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
selectedItem = parent.getItemAtPosition(position).toString();
Toast.makeText(this@SecondActivity, "$selectedItem",Toast.LENGTH_SHORT).show()
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
Выбор данных и их отображение
search.setOnClickListener {
val searchcountrydata = "SELECT * FROM employee WHERE country = " +"'$selectedItem'";
val cursor2 = db?.rawQuery(searchcountrydata,null)
val displayString = StringBuilder()
while(cursor2!!.moveToNext()) {
val id = cursor2.getString(0)
val name = cursor2.getString(1)
val phonenumber = cursor2.getString(2)
val country = cursor2.getString(3)
displayString.append("ID: $id, Name: $name, PhoneNumber: $phonenumber, Country: $country" +"\n")
}
display2.text = displayString.toString()
}
Сортировка данных
sort.setOnClickListener {
val newquery = "SELECT * FROM employee ORDER BY employeeid DESC"
val cursor3 = db?.rawQuery(newquery,null)
val displayString2 = StringBuilder()
while(cursor3!!.moveToNext()) {
val id = cursor3.getString(0)
val name = cursor3.getString(1)
val phonenumber = cursor3.getString(2)
val country = cursor3.getString(3)
displayString2.append("ID: $id, Name: $name, PhoneNumber: $phonenumber, Country: $country" +"\n")
}
display2.text = displayString2.toString()
}
Обновление данных
updatebutton.setOnClickListener {
val empval = empid.text.toString()
val countryval = country.text.toString()
val updatequery = "UPDATE employee SET country = " + "'$countryval'"+" WHERE employeeid = $empval"
db?.execSQL(updatequery)
Toast.makeText(this@ThirdActivity, "Updated Successfully",Toast.LENGTH_SHORT).show()
}
УДАЛЕНИЕ ДАННЫХ
delete.setOnClickListener {
val rollval = rollno.text.toString();
val deletequery = "DELETE FROM STUDENT WHERE ROLLNO=$rollval";
db?.execSQL(deletequery)
Toast.makeText(this@MainActivity,"Deleted Data Successfully!",Toast.LENGTH_SHORT).show()
}
НАЙДЕНИЕ максимума и минимума в данных
maxandmin.setOnClickListener {
val selectquery1 = "SELECT productid, name, price FROM PRODUCTS p WHERE p.price IN (SELECT MAX(price) FROM PRODUCTS)"
val selectquery2 = "SELECT productid, name, price FROM PRODUCTS p WHERE p.price IN (SELECT MIN(price) FROM PRODUCTS)"
val cursor1 = db?.rawQuery(selectquery1, null)
val cursor2 = db?.rawQuery(selectquery2, null)
val str = StringBuilder()
str.append("Maximum Priced Product Details: \n")
while(cursor1!!.moveToNext()) {
val id = cursor1.getString(0)
val name = cursor1.getString(1)
val price = cursor1.getString(2)
str.append("Product ID: $id, Product Name: $name, Product Price: $price")
}
str.append("\n\nMinimum Priced Product Details: \n")
while(cursor2!!.moveToNext()) {
val id = cursor2.getString(0)
val name = cursor2.getString(1)
val price = cursor2.getString(2)
str.append("Product ID: $id, Product Name: $name, Product Price: $price")
}
Нахождение общего количества
str.append("\n\nTotal No Of Products: ")
val findtotproducts = "SELECT COUNT(*) FROM PRODUCTS"
val totprice = "SELECT SUM(PRICE) FROM PRODUCTS"
val cursor4 = db?.rawQuery(findtotproducts,null)
val cursor5 = db?.rawQuery(totprice, null)
while(cursor4!!.moveToNext()) {
val countprod = cursor4.getString(0)
str.append(countprod)
}
Нахождение общей цены
str.append("\n\nTotal Price of Products: ")
while(cursor5!!.moveToNext()) {
val countprod2 = cursor5.getString(0)
str.append(countprod2)
}
display.text = str;
Ниже я написал полный процесс реализации операций CRUD. Я объяснил это с помощью listview
БАЗА ДАННЫХ
Перейдите в AndroidManifest.xml.
добавить эти разрешения -
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name = "android.permission.INTERNET" />
below <manifest> tag and above <application> tag
like here
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools">
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name = "android.permission.INTERNET" />
<application
android:allowBackup = "true"
android:dataExtractionRules = "@xml/data_extraction_rules"
android:fullBackupContent = "@xml/backup_rules"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:supportsRtl = "true"
android:theme = "@style/Theme.Androidstudio"
tools:targetApi = "31">
<activity
android:name = ".MainActivity"
android:exported = "true">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Создайте новый класс DatabaseHelper и добавьте код ниже:
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
private const val DATABASE_VERSION = 1
private const val DATABASE_NAME = "StudentManager.db"
// Table name and columns
private const val TABLE_NAME = "students"
private const val COLUMN_ROLL_NUMBER = "roll_number"
private const val COLUMN_NAME = "name"
private const val COLUMN_MARKS = "marks"
}
override fun onCreate(db: SQLiteDatabase?) {
val createTableQuery = "CREATE TABLE $TABLE_NAME (" +
"$COLUMN_ROLL_NUMBER TEXT PRIMARY KEY," +
"$COLUMN_NAME TEXT," +
"$COLUMN_MARKS INTEGER)"
db?.execSQL(createTableQuery)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
onCreate(db)
}
fun addStudent(rollNumber: String, name: String, marks: Int): Boolean {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put(COLUMN_ROLL_NUMBER, rollNumber)
contentValues.put(COLUMN_NAME, name)
contentValues.put(COLUMN_MARKS, marks)
val result = db.insert(TABLE_NAME, null, contentValues)
return result != -1L
}
fun readAllStudents(): Cursor {
val db = this.readableDatabase
return db.rawQuery("SELECT * FROM $TABLE_NAME", null)
}
fun updateStudent(rollNumber: String, name: String, marks: Int): Boolean {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put(COLUMN_NAME, name)
contentValues.put(COLUMN_MARKS, marks)
val result = db.update(TABLE_NAME, contentValues, "$COLUMN_ROLL_NUMBER = ?", arrayOf(rollNumber))
return result != -1
}
fun deleteStudent(rollNumber: String): Boolean {
val db = this.writableDatabase
val result = db.delete(TABLE_NAME, "$COLUMN_ROLL_NUMBER = ?", arrayOf(rollNumber))
return result != -1
}
}
In the Main Activity
do this
package com.example.androidstudio
import DatabaseHelper
import android.content.Context
import android.database.Cursor
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
fun showAlert(context: Context, title: String, message: String) {
val builder = AlertDialog.Builder(context)
builder.setTitle(title)
builder.setMessage(message)
builder.setPositiveButton("OK") { dialog, _ ->
dialog.dismiss()
}
val dialog = builder.create()
dialog.show()
}
private lateinit var databaseHelper: DatabaseHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
databaseHelper = DatabaseHelper(this)
val rollNumberEditText = findViewById<EditText>(R.id.rollNumberEditText)
val nameEditText = findViewById<EditText>(R.id.nameEditText)
val marksEditText = findViewById<EditText>(R.id.marksEditText)
val addButton = findViewById<Button>(R.id.addButton)
val displayButton = findViewById<Button>(R.id.displayButton)
val updatestudent = findViewById<Button>(R.id.updatestudent)
val deletestudent = findViewById<Button>(R.id.deletestudent)
updatestudent.setOnClickListener {
val rollNumber = rollNumberEditText.text.toString()
val name = nameEditText.text.toString()
val marks = marksEditText.text.toString()
if (rollNumber.isNotEmpty() && name.isNotEmpty() && marks.isNotEmpty()) {
if (databaseHelper.updateStudent(rollNumber, name, marks.toInt())) {
Toast.makeText(this, "Updated Student Successfully", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Failed to update student", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show()
}
}
deletestudent.setOnClickListener {
val rollNumber = rollNumberEditText.text.toString()
if (rollNumber.isNotEmpty()) {
if (databaseHelper.deleteStudent(rollNumber)) {
Toast.makeText(this, "Deleted Student Successfully", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Failed to delete student", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Please fill in roll number field", Toast.LENGTH_SHORT).show()
}
}
addButton.setOnClickListener {
val rollNumber = rollNumberEditText.text.toString()
val name = nameEditText.text.toString()
val marks = marksEditText.text.toString()
if (rollNumber.isNotEmpty() && name.isNotEmpty() && marks.isNotEmpty()) {
if (databaseHelper.addStudent(rollNumber, name, marks.toInt())) {
Toast.makeText(this, "Student added successfully", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Failed to add student", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show()
}
}
displayButton.setOnClickListener {
val cursor: Cursor = databaseHelper.readAllStudents()
if (cursor.count == 0) {
Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
val displayString = StringBuilder()
while (cursor.moveToNext()) {
val rollNumber = cursor.getString(0)
val name = cursor.getString(1)
val marks = cursor.getInt(2)
displayString.append("Roll Number: $rollNumber, Name: $name, Marks: $marks\n")
}
showAlert(this,"Selected Items", displayString.toString())
}
}
override fun onDestroy() {
databaseHelper.close()
super.onDestroy()
}
}
ПОИСК КОНКРЕТНОГО ВХОДА
displayButton.setOnClickListener {
val name2 = nameEditText.text.toString()
val cursor2: Cursor = databaseHelper.findtotstudents(name2)
if (cursor2.count == 0) {
Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
val displayString2 = StringBuilder()
while (cursor2.moveToNext()) {
val count = cursor2.getString(0)
displayString2.append("Count is $count")
}
showAlert(this,"Count Items", displayString2.toString())
}
}
FUNCTION IN databaseHelper is
fun findtotstudents(name: String): Cursor {
val db = this.readableDatabase
return db.rawQuery("SELECT COUNT(roll_number) FROM $TABLE_NAME WHERE name= + \"$name\"", null)
}
ВЫБОР СЧЕТА РОЛИКОВ С ПОХОЖИМИ НАЗВАНИЯМИ
MainActivity.kt
displayButton.setOnClickListener {
val cursor2: Cursor = databaseHelper.checkeachcount()
if (cursor2.count == 0) {
Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
val displayString2 = StringBuilder()
while (cursor2.moveToNext()) {
val count = cursor2.getString(1)
val name = cursor2.getString(0)
displayString2.append("Name : $name, Count: $count")
}
showAlert(this,"Name and Count", displayString2.toString())
}
DatabaseHelper
fun checkeachcount(): Cursor {
val db = this.readableDatabase
return db.rawQuery("SELECT name, COUNT(roll_number) FROM $TABLE_NAME GROUP BY name", null)
}
ВЫБОР ИМЯ И ОТЧЕТ СТУДЕНТА С НАИБОЛЬШИМИ ОТМЕТКАМИ И СТУДЕНТА С НАИБОЛЬШИМИ ОТМЕТКАМИ
База данныхПомощник
fun findmaxstudent(): Cursor {
val db = this.readableDatabase
return db.rawQuery("SELECT name, marks FROM $TABLE_NAME a WHERE a.marks = (SELECT MAX(MARKS) FROM $TABLE_NAME)",null)
}
fun findminstudent(): Cursor {
val db = this.readableDatabase
return db.rawQuery("SELECT name, marks FROM $TABLE_NAME a WHERE a.marks = (SELECT MIN(MARKS) FROM $TABLE_NAME)",null)
}
MainActivity
displayButton.setOnClickListener {
val cursor2: Cursor = databaseHelper.findmaxstudent()
if (cursor2.count == 0) {
Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
val displayString2 = StringBuilder()
while (cursor2.moveToNext()) {
val maxmarks = cursor2.getString(1)
val name = cursor2.getString(0)
displayString2.append("Name : $name, Max Marks: $maxmarks\n")
}
val cursor: Cursor = databaseHelper.findminstudent()
if (cursor.count == 0) {
Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
while (cursor.moveToNext()) {
val minmarks = cursor.getString(1)
val name = cursor.getString(0)
displayString2.append("Name : $name, Min Marks: $minmarks\n")
}
showAlert(this,"Name and Count", displayString2.toString())
}
ОТОБРАЖЕНИЕ БАЗЫ ДАННЫХ В LISTVIEW
displayall.setOnClickListener {
var arr = emptyArray<String>()
val cursor: Cursor = databaseHelper.readAllStudents()
if (cursor.count == 0) {
Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
while (cursor.moveToNext()) {
val rollNumber = cursor.getString(0)
val name = cursor.getString(1)
val marks = cursor.getInt(2)
arr+= rollNumber + " "+name+" "+marks
}
var adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,arr)
ls.adapter = adapter
}
ДОБАВЛЕНИЕ ЗНАЧЕНИЙ В SPINNER ИЗ БД
var spinner = findViewById<Spinner>(R.id.spinner)
var ls = findViewById<ListView>(R.id.ls)
var arr = emptyArray<String>()
val cursor: Cursor = databaseHelper.getcountries()
if (cursor.count == 0) {
Toast.makeText(this, "Nothing to display", Toast.LENGTH_SHORT).show()
}
while (cursor.moveToNext()) {
val countrytemp = cursor.getString(0)
arr+= countrytemp
}
var adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,arr)
spinner.adapter = adapter
var selectedItem = ""
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
selectedItem = parent?.getItemAtPosition(position).toString()
Toast.makeText(this@SecondActivity, selectedItem, Toast.LENGTH_SHORT).show()
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("Not yet implemented")
}
}
Ознакомьтесь с этим ответом для получения помощи по счетчику: Код Kotlin сообщает: «Ни одна из следующих функций не может быть вызвана с предоставленными аргументами»
база данных
введите код сюда
package com.example.labp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class databasehelper extends SQLiteOpenHelper {
private static final String DB_NAME = "student";
// below int is our database version
private static final int DB_VERSION = 1;
// below variable is for our table name.
private static final String TABLE_NAME = "students";
// below variable is for our id column.
private static final String Stud_id = "stud_id";
// below variable is for our course name column
private static final String NAME_COL = "name";
private static final String Marks = "marks";
// below variable id for our course duration column.
// creating a constructor for our database handler.
public databasehelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + " ("
+ Stud_id + " INTEGER PRIMARY KEY, "
+ NAME_COL + " TEXT,"
+ Marks + " INTEGER)";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addNewStudent(int roll_no, String name, int marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Stud_id,roll_no);
values.put(NAME_COL, name);
values.put(Marks,marks);
db.insert(TABLE_NAME, null, values);
db.close();
}
public String display(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("Select * from " + TABLE_NAME,null);
StringBuilder stringBuilder = new StringBuilder();
while(cur.moveToNext()){
int roll_no = cur.getInt(0);
String name = cur.getString(1);;
int marks = cur.getInt(2);
stringBuilder.append("Roll No: ").append(roll_no)
.append(", Name: ").append(name)
.append(", Marks: ").append(marks)
.append("\n");
}
return stringBuilder.toString();
}
}
main java
package com.example.labp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText rollno,name1,marks;
private TextView tv;
private Button btn,disp;
private databasehelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rollno = findViewById(R.id.editTextText);
name1 = findViewById(R.id.editTextText2);
marks = findViewById(R.id.editTextText3);
btn = findViewById(R.id.button);
disp = findViewById(R.id.button2);
db = new databasehelper(MainActivity.this);
tv = findViewById(R.id.textView2);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String roll_no_txt = rollno.getText().toString();
int roll_no = Integer.parseInt(roll_no_txt);
String name = name1.getText().toString();
String marks_no_txt = marks.getText().toString();
int mrks = Integer.parseInt(marks_no_txt);
db.addNewStudent(roll_no,name,mrks);
Toast.makeText(MainActivity.this, "Student has been added.", Toast.LENGTH_SHORT).show();
}
});
disp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String studentData = db.display();
tv.setText(studentData);
}
});
}
}
Возможно, попробуйте добавить это в свой код.
val intent= Intent(this,thirda::class.java)
intent.putExtra("score",cnt)
startActivity(intent)
val score = intent.getIntExtra("score", 0)
Основная деятельность:
package com.example.dbhelper;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.concurrent.Callable;
public class MainActivity extends AppCompatActivity {
private EditText CourseName, CourseTracks, CourseDuration,CourseDescription ;
private Button submit;
private DBHandler dbHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CourseName = findViewById(R.id.editTextText);
CourseTracks = findViewById(R.id.editTextText2);
CourseDuration = findViewById(R.id.editTextText3);
CourseDescription = findViewById(R.id.editTextText4);
submit = findViewById(R.id.submit);
dbHandler = new DBHandler(MainActivity.this);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// below line is to get data from all edit text fields.
String courseName = CourseName.getText().toString();
String courseTracks = CourseTracks.getText().toString();
String courseDuration = CourseDuration.getText().toString();
String courseDescription = CourseDescription.getText().toString();
// validating if the text fields are empty or not.
if (courseName.isEmpty() && courseTracks.isEmpty() && courseDuration.isEmpty() && courseDescription.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter all the data..", Toast.LENGTH_SHORT).show();
return;
}
dbHandler.addNewCourse(courseName, courseDuration, courseDescription, courseTracks);
// after adding the data we are displaying a toast message.
Toast.makeText(MainActivity.this, "Course has been added.", Toast.LENGTH_SHORT).show();
CourseName.setText("");
CourseDuration.setText("");
CourseTracks.setText("");
CourseDescription.setText("");
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
}
});
}
}
ДБХЕЛПЕР.JAVA:
package com.example.dbhelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHandler extends SQLiteOpenHelper {
private static final String DB_NAME = "coursedb";
// below int is our database version
private static final int DB_VERSION = 1;
// below variable is for our table name.
private static final String TABLE_NAME = "mycourses";
// below variable is for our id column.
private static final String ID_COL = "id";
// below variable is for our course name column
private static final String NAME_COL = "name";
// below variable id for our course duration column.
private static final String DURATION_COL = "duration";
// below variable for our course description column.
private static final String DESCRIPTION_COL = "description";
// below variable is for our course tracks column.
private static final String TRACKS_COL = "tracks";
// creating a constructor for our database handler.
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY, "
+ NAME_COL + " TEXT,"
+ DURATION_COL + " TEXT,"
+ DESCRIPTION_COL + " TEXT,"
+ TRACKS_COL + " TEXT)";
// at last we are calling a exec sql
// method to execute above sql query
db.execSQL(query);
}
public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME_COL, courseName);
values.put(DURATION_COL, courseDuration);
values.put(DESCRIPTION_COL, courseDescription);
values.put(TRACKS_COL, courseTracks);
// after adding all values we are passing
// content values to our table.
db.insert(TABLE_NAME, null, values);
// at last we are closing our
// database after adding database.
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
ОСНОВНОЙ АКТ 2:
пакет com.example.dbhelper;
импортировать androidx.appcompat.app.AppCompatActivity;
импортировать android.os.Bundle;
публичный класс MainActivity2 расширяет AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
Как сейчас написано, ваш ответ неясен. Пожалуйста, отредактируйте , чтобы добавить дополнительную информацию, которая поможет другим понять, как это относится к заданному вопросу. Более подробную информацию о том, как писать хорошие ответы, вы можете найти в справочном центре.