public void dialog_success{ Dialog dialog=new Dialogthis dialog.requestWindowFeatureWindow.FEATURE_NO_TITLE dialog.setContentViewR.layout.dialog_success dialog.show; Button btnok=Butt
Actors và Use Cases
Mô tả
Ứng dụng này giúp trẻ em thực hành câu hỏi trắc nghiệm môn Toán và Tiếng Việt, cho phép chấm điểm và hiển thị kết quả ngay sau khi hoàn thành Trẻ có thể dễ dàng xem danh sách các câu hỏi để ôn tập và cải thiện kỹ năng học tập.
Admin có thể đăng nhập, đăng ký, quản lý các câu hỏi
Thiết kế cơ sở dữ liệu và chức năng
SQL
2.1.1 Category import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.List; import tktsp.example.a17dtha2_aptracnghiem.DB.DBHelper; import tktsp.example.a17dtha2_aptracnghiem.model.Category; import tktsp.example.a17dtha2_aptracnghiem.model.User; public class categoryDao { private SQLiteDatabase db; private DBHelper dbHelper; public static final String SQL_CREATE_CAT = "CREATE TABLE tbl_category(\n" +
"\t id INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
"\t name TEXT NOT NULL);"; public static final String TBL_CAT = "tbl_category"; public static final String TAG = "CategotyDAO"; public categoryDao(Context context){
2 dbHelper=new DBHelper(context); db dbHelper= getWritableDatabase();
} public int insertCat(Category category){
ContentValues values = new ContentValues(); values.put("id", category.getId()); values.put("name", category.getName()); try { if (db.insert(TBL_CAT, null, values) == - ) {1 return -1;
List categories=new ArrayList();
Cursor cquery(TBL_CAT,null,null,null,null,null,null ;) c.moveToFirst(); while (c.isAfterLast() == false) {
Log.d("checkname", categories.get( ).getName())1 ; Log.d("checkid", String.valueOf(categories.get(1).getId()) ); return categories;
The `userDao` class manages user data within an SQLite database, utilizing `DBHelper` for database operations It includes the creation of a user table (`tbl_user`) with a primary key for the username Essential imports include `ContentValues`, `Cursor`, and `SQLiteDatabase`, which facilitate data manipulation and retrieval The class is designed to handle user-related functionalities, ensuring efficient data management in Android applications.
"\t name_user text NOT NULL,\n" +
"\t email text NOT NULL UNIQUE,\n" +
"\t permission INTEGER NOT NULL);"; public static final String TBL_USER = "tbl_user"; public static final String TAG = "UserDAO";
//kh i t o DB, cho phép ghi sqlở ạ public userDao(Context context) { dbHelper = new DBHelper(context); db = dbHelper.getWritableDatabase();
} public int insertUser(User user) { enCode enCode = new enCode();
String pass = enCode.md5(user.getPassword().toString());
ContentValues values = new ContentValues(); values.put("username", user.getUsername()); values.put("password", pass);
4 values.put("name_user", user.getName_user()); values.put("email", user.getEmail()); values.put("permission", 1); try { if (db.insert(TBL_USER, null, values) == - ) {1 return -1;
List dsuser = new ArrayList();
To retrieve user data from the database, a cursor is initiated with the query method on the TBL_USER table The cursor is then moved to the first row to begin processing the results A while loop is employed to iterate through the cursor until it reaches the end, allowing for the extraction of user information by creating a new User object with the retrieved string values from the cursor.
Log.d("email", dsuser.get( ).getEmail())0 ; return dsuser;
} public boolean checkUsername(String username) {
String sql = "SELECT * FROM " + TBL_USER + " WHERE username='" + username + "'"; Cursor c = db.rawQuery(sql, null);
Log.d("giatri", String.valueOf(c.getCount()));
// Log.d("giatri",pass); c.close(); return true; else } { c.close(); return false;
} public Boolean checkLogin(String username String pass) {,
List listuser = new ArrayList(); enCode edCode = new enCode();
String password = edCode.md5(pass);
String sql = "SELECT * FROM " + TBL_USER + " WHERE username='" + username + "' and password='" + password + "'";
Cursor c = db.rawQuery(sql, null); if (c.getCount() > ) {0 c.close(); return true; else } { c.close(); return false;
} public User getProfile(String username) {
// String sql = "SELECT * FROM " + TBL_USER + " WHERE username='" + username + "'"; // WHERE username='" + username + "'
// Cursor c = db.rawQuery(sql, null);
Cursor cquery(TBL_USER,null,where whereArgs, ,null,null,null ;) c.moveToFirst();
User user = new User( c.getString(0), c.getString( )1, c.getString( )2, c.getString( )3,
2.1.3 Quiz Contract import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.List; import tktsp.example.a17dtha2_aptracnghiem.DB.DBHelper; import tktsp.example.a17dtha2_aptracnghiem.endcode.enCode; import tktsp.example.a17dtha2_aptracnghiem.model.QuizContract; import tktsp.example.a17dtha2_aptracnghiem.model.User; public class quizcontractDao { private SQLiteDatabase db; private DBHelper dbHelper; public static final String SQL_CREATE_QUIZ = "CREATE TABLE tbl_quiz(\n" + "\t id INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
"\t category INTEGER NOT NULL);"; public static final String TBL_QUIZ = "tbl_quiz"; public static final String TAG = "QuizContractDAO";
7 public quizcontractDao(Context context){ dbHelper= new DBHelper(context); db dbHelper= getWritableDatabase();
} public int insertQuiz(QuizContract quiz){
To insert quiz data into the database, a new ContentValues object is created to store the quiz details, including the ID, question, options, answer, and category The values are populated using the quiz object's getter methods The insertion is attempted into the TBL_QUIZ table, and if the operation fails, it returns -1 to indicate an error.
} public List getQuizbyCat(int id){
List listQuiz=new ArrayList();
String[] whereArgs={String.valueOf(id)};
To retrieve data from the database, a cursor is created by querying the TBL_QUIZ table with specified conditions The cursor is then positioned at the first row of the result set A while loop is used to iterate through the cursor until it reaches the end of the data Within the loop, a QuizContract object is instantiated using the values retrieved from the cursor, which includes various attributes such as integers and strings from specific columns.
); listQuiz.add(quiz); cursor.moveToNext();
//Log.d("check",listQuiz.get(0).getAnswer());
} public int deleteQuiz(QuizContract quiz){
String[] whereArgs={String.valueOf(quiz.getId())}; try { if (db.delete(TBL_QUIZ,where,whereArgs)< ){0 return -1;
} public int updateQuiz(QuizContract quiz){
To store quiz data efficiently, create a new ContentValues object and populate it with essential information Use the `put` method to add the quiz question, options, correct answer, and category This structured approach ensures that all relevant quiz details are organized and easily retrievable for future use.
String[] whereArgs={String.valueOf(quiz.getId())}; try { if (db.update(TBL_QUIZ,values where whereArgs)==-, , 1) { return -1;
Giao diện và code
The `registerUser ` class extends `AppCompatActivity` to manage user registration in an Android application It imports essential libraries for user interface components and functionality, including `Dialog`, `Intent`, and `Toast` The class utilizes a `Bundle` to handle activity data and employs regex patterns for input validation It integrates a `userDao` for database operations related to user management, ensuring a seamless registration process for new users.
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; Intent intent;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_user); anhxa(); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
Intent Main=new Intent(registerUser.this,MainActivity.class); startActivity(Main); finish();
In the method `anhxa()`, several user interface elements are initialized, including the back button (`btnBack`), the registration button (`btnDangky`), and input fields for username (`edtUsename`), password (`edtPassword`), confirm password (`edtRPassword`), email (`edtEmail`), and name (`edtName`).
} public void addUser(View view){ anhxa();
//kh i t o userDao đ bắắt đầầu th c hi n nghi p vở ạ ể ự ệ ệ ụ userDao=new userDao(registerUser.this ;)
//check điêầu ki nệ if (edtName.getText().toString().isEmpty() || edtUsename.getText().toString().isEmpty() || edtPassword.getText().toString().isEmpty() || edtRPassword.getText().toString().isEmpty() || edtEmail.getText().toString().isEmpty()){
In the registration process, it is crucial to ensure that the username and password meet specific length requirements, with both needing to be at least five characters long If the username or password does not meet this criterion, a message will be displayed stating, "Username and password must be at least 5 characters long." Additionally, the system checks if the password matches the confirmation password; if they do not match, an alert will inform the user that "Passwords do not match." Furthermore, the email entered must adhere to a valid email pattern; otherwise, the user will receive a notification indicating an invalid email format.
Toast.makeText(registerUser.this, "B n nh p sai Email"ạ ậ , Toast.LENGTH_LONG).show(); else if} ( userDao.checkUsername(edtUsename.getText().toString())==true){
Toast.makeText(registerUser.this, "Tài Kho n Tốần T i"ả ạ , Toast.LENGTH_LONG).show(); } else{
User user=new User(edtUsename.getText().toString(), edtPassword.getText().toString(),edtName.getText().toString(),edtEmail.getText().toString(),1); try { if (userDao.insertUser(user)> ){0 dialog_success();
Toast.makeText(registerUser.this,"Thêm Thầắt B i "ạ +user.getName_user()
Dialog dialog=new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_success); dialog.show();
Button btnok=(Button) dialog.findViewById(R.id.btnOk); btnok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { intent=new Intent(registerUser.this,MainActivity.class); startActivity(intent); finish();
In this Android code sample, we import essential libraries such as androidx.annotation.Nullable and androidx.appcompat.app.AppCompatActivity The code includes the declaration of a Dialog and a ProgressDialog, along with the necessary Intent for activity transitions Inside the onCreate method, we set up the user interface by initializing components like Button and EditText, allowing for user interaction within the application This foundational setup is crucial for creating a responsive and functional Android app.
The MainActivity class in this Android application integrates Facebook login functionality using the Facebook SDK, allowing users to authenticate through their Facebook accounts It includes essential imports such as ProgressBar for loading indicators and Toast for displaying messages The class utilizes CallbackManager to handle login responses and FacebookCallback to manage login success or failure Additionally, it employs GraphRequest for accessing user data and ProfilePictureView to display user profiles The application also incorporates various DAO classes for managing data related to categories, quizzes, and users, while utilizing the Paper library for data persistence The implementation of the DoubleBounce animation from the SpinKit library enhances the user experience during loading processes.
EditText edtUsername edtPassword, ; userDao user;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); user=new userDao(MainActivity.this);
FacebookSdk.sdkInitialize(getApplicationContext()); callbackManager = CallbackManager.Factory.create(); edtUsername=findViewById(R.id.edtUsername); edtPassword=findViewById(R.id.edtPassword); btnDangky=findViewById(R.id.btnRegister); btnLogin=findViewById(R.id.btnLogin);
//login f btnloginf=findViewById(R.id.login_button); btnloginf.setReadPermissions(Arrays.asList("public_profile" "email", )); btnloginf.registerCallback(callbackManager, new FacebookCallback() { @Override public void onSuccess(LoginResult loginResult) {
Paper.book().write(General.USER_CHECK,"Facebook");
Paper.book().write(General.USER_NAME,"null");
String img="https://www.facebook.com/photo? fid="+loginResult.getAccessToken().getUserId();
Paper.book().write(General.USER_IMAGE, img); result();
Intent intent=new Intent(MainActivity.this,bottomNavigation.class ;) startActivity(intent);
@Override public void onError(FacebookException error) {
}); btnDangky.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent AcRegister=new Intent(MainActivity.this,registerUser.class ;) startActivity(AcRegister); finish();
}); btnLogin.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
String passwordPassword.getText().toString(); user=new userDao(MainActivity.this ;)
Boolean taikhoan= user.checkLogin(username password), ; if (taikhoan==true || username.equals("admin") && password.equals("admin")){
Paper.book().write(General.USER_NAME, username);
// Intent AcRegister=new Intent(MainActivity.this,processbar_Activity.class);
Intent AcRegister = new Intent(MainActivity.this,bottomNavigation.class ;) startActivity(AcRegister); finish(); else } {
Toast.makeText(MainActivity.this,"Vui Lòng Ki m Tra l i Tài ể ạ
Kh a"ỏ ,Toast.LENGTH_SHORT).show();
@Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode resultCode data), , ; callbackManager.onActivityResult(requestCode resultCode data), , ;
GraphRequest graphRequest=GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
17 public void onCompleted(JSONObject object GraphResponse response) {, Log.d("JSON", response.getJSONObject().toString()); try {
String email1=object.getString("email");
String name1=object.getString("name");
String id1=object.getString("id");
// String username=object.getString("username");
Paper.book().write(General.ID_FB,id1);
// Paper.book().write(General.USER_NAMEFB, username); Paper.book().write(General.NAME, name1);
Paper.book().write(General.USER_EMAIL, email1);
//String id1=object.getString("id");
Bundle pra=new Bundle(); pra.putString("fields" "name,email,first_name", ); graphRequest.setParameters(pra); graphRequest.executeAsync();
LoginManager.getInstance().logOut(); super.onStart();
2.2.2 Thêm Câu hỏi môn Toán
In this Android code sample, we import necessary libraries including AppCompatActivity and Dialog The activity is defined within the `onCreate` method, where we set up the user interface and handle user interactions Key components include the initialization of a dialog, the intent for navigating between activities, and the use of EditText and Button for user input Logging is implemented for debugging purposes, ensuring a smooth user experience.
19 import android.widget.TextView; import android.widget.Toast; import tktsp.example.a17dtha2_aptracnghiem.DAO.quizcontractDao; import tktsp.example.a17dtha2_aptracnghiem.model.QuizContract; public class addQuestionToan extends AppCompatActivity {
EditText txtcauhoi txtoption1 txtoption2 txtoption3 txtcaudung, , , , ;
Button btnadd btnback, ; quizcontractDao quizcontractDao;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_question_toan); anhxa(); btnback.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent intent=new Intent(addQuestionToan.this,quanlyTracNghiem.class); startActivity(intent);
} public void addQuiz(View view){
//Toast.makeText(addQuestionToan.this,"hihisadasdasdas",Toast.LENGTH_LONG).show(); quizcontractDao=new quizcontractDao(addQuestionToan.this);
String cauhoi=txtcauhoi.getText().toString();
String option1=txtoption1.getText().toString();
String option2=txtoption2.getText().toString();
String option3=txtoption3.getText().toString();
String caudung=txtcaudung.getText().toString();
QuizContract quizContract=new QuizContract(null,cauhoi option1 option2 option3 caudung, , , , ,1); try { if (quizcontractDao.insertQuiz(quizContract)> ){0 int a=quizcontractDao.insertQuiz(quizContract);
Log.d("hihihi", String.valueOf(a)); showdialog();
Toast.makeText(addQuestionToan.this,"Thêm Thầắt B i "ạ ,Toast.LENGTH_LONG).show(); }
} public void anhxa(){ txtcauhoi=findViewById(R.id.txtcauhoi); txtoption1=findViewById(R.id.txtcoption1); txtoption2=findViewById(R.id.txtcoption2); txtoption3=findViewById(R.id.txtcoption3); txtcaudung=findViewById(R.id.txtcaudung); btnback=findViewById(R.id.btnback);
Dialog dialog = new Dialog(addQuestionToan.this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_success); dialog.show();
Button btnok=dialog.findViewById(R.id.btnOk);
TextView txt1=dialog.findViewById(R.id.txt1);
TextView txt2=dialog.findViewById(R.id.txt2); txt1.setText("Thêm Cầu H i Thành Cống"ỏ ); txt2.setVisibility(View.INVISIBLE); btnok.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent intent=new Intent(addQuestionToan.this,listTracNghiemToan.class); startActivity(intent);
2.2.3 Thêm câu hỏi môn Văn
The provided code snippet demonstrates the importation of essential Android libraries for an app's activity, including `AppCompatActivity` for compatibility support and `Dialog` for creating dialog windows It outlines the necessary imports for handling user interactions, such as `Intent` for navigating between activities, and UI components like `Button`, `EditText`, and `TextView` The `onCreate` method is typically where the activity's layout is set up, and user actions can be managed effectively within the app's lifecycle.
22 import android.widget.Toast; import tktsp.example.a17dtha2_aptracnghiem.DAO.quizcontractDao; import tktsp.example.a17dtha2_aptracnghiem.model.QuizContract; public class addQuestionVan extends AppCompatActivity {
EditText txtcauhoi txtoption1 txtoption2 txtoption3 txtcaudung, , , , ;
Button btnadd,btnback; quizcontractDao quizcontractDao;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_question_van); anhxa(); btnback.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent intent=new Intent(addQuestionVan.this,quanlyTracNghiem.class ;) startActivity(intent);
} public void addQuiz(View view){
//Toast.makeText(addQuestionToan.this,"hihisadasdasdas",Toast.LENGTH_LONG).show(); quizcontractDao=new quizcontractDao(addQuestionVan.this ;)
String cauhoi=txtcauhoi.getText().toString();
String option1=txtoption1.getText().toString();
String option2=txtoption2.getText().toString();
String option3=txtoption3.getText().toString();
String caudung=txtcaudung.getText().toString();
QuizContract quizContract=new QuizContract(null,cauhoi option1 option2 option3 caudung, , , , ,2); try { if (quizcontractDao.insertQuiz(quizContract)> ){0 showdialog();
Toast.makeText(addQuestionVan.this,"Thêm Thầắt B i "ạ ,Toast.LENGTH_LONG).show(); }
23 public void anhxa(){ txtcauhoi=findViewById(R.id.txtcauhoi); txtoption1=findViewById(R.id.txtcoption1); txtoption2=findViewById(R.id.txtcoption2); txtoption3=findViewById(R.id.txtcoption3); txtcaudung=findViewById(R.id.txtcaudung); btnback=findViewById(R.id.btnback);
Dialog dialog = new Dialog(addQuestionVan.this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_success); dialog.show();
Button btnok=dialog.findViewById(R.id.btnOk);
TextView txt1=dialog.findViewById(R.id.txt1);
TextView txt2=dialog.findViewById(R.id.txt2); txt1.setText("Thêm Cầu H i Thành Cống"ỏ ); txt2.setVisibility(View.INVISIBLE); btnok.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent intent=new Intent(addQuestionVan.this,listTracNghiemVan.class); startActivity(intent);
2.2.4 Cập nhật câu hỏi Toán, Tiếng Việt
In this code sample, we import essential Android libraries, including `AppCompatActivity` for activity management and `Dialog` for creating dialog windows The `Intent` class is utilized for navigating between activities, while the `Bundle` class manages the activity's state Additionally, we leverage `Log` for logging messages, and various UI components such as `View`, `Button`, `EditText`, and `TextView` to build the user interface This foundational setup is crucial for developing interactive Android applications.
25 import android.widget.Toast; import tktsp.example.a17dtha2_aptracnghiem.DAO.quizcontractDao; import tktsp.example.a17dtha2_aptracnghiem.model.QuizContract; public class detailTracNghiemToan extends AppCompatActivity {
EditText txtcauhoi txtoption1 txtoption2 txtoption3 txtcaudung, , , , ;
Button btnUpdate btnback, ; quizcontractDao quizcontractDao;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_trac_nghiem_toan);
Bundle bundle=intent.getBundleExtra("DATA"); int id=bundle.getInt("id");
String question=bundle.getString("question");
String option1=bundle.getString("option1");
String option2=bundle.getString("option2");
String option3=bundle.getString("option3");
In the `detailTracNghiemToan` class, the `quizcontractDao` is initialized to manage quiz data The question and its corresponding options are displayed using `txtcauhoi`, `txtoption1`, `txtoption2`, and `txtoption3` The correct answer is set with `txtcaudung` An `OnClickListener` is added to the `btnUpdate` button to handle user interactions.
@Override public void onClick(View view) {
QuizContract quiz=new QuizContract( id, txtcauhoi.getText().toString(), txtoption1.getText().toString(), txtoption2.getText().toString(), txtoption3.getText().toString(), txtcaudung.getText().toString(),
26 try { if (quizcontractDao.updateQuiz(quiz)> ){0 showdialog();
Toast.makeText(detailTracNghiemToan.this,"lốỗi",Toast.LENGTH_SHORT).show(); }
// Toast.makeText(detailTracNghiemToan.this,"lốỗi",Toast.LENGTH_SHORT).show(); }
}); btnback.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent intent=new Intent(detailTracNghiemToan.this,listTracNghiemToan.class ;) startActivity(intent);
In the method `anhxa()`, various user interface elements are initialized, including the question text view (`txtcauhoi`), three option text views (`txtoption1`, `txtoption2`, `txtoption3`), the correct answer text view (`txtcaudung`), and two buttons for updating and going back (`btnUpdate`, `btnback`).
Dialog dialog = new Dialog(detailTracNghiemToan.this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_success); dialog.show();
Button btnok=dialog.findViewById(R.id.btnOk);
TextView txt1=dialog.findViewById(R.id.txt1);
TextView txt2=dialog.findViewById(R.id.txt2); txt1.setText("C p Nh t Thành Cống"ậ ậ ); txt2.setVisibility(View.INVISIBLE); btnok.setOnClickListener(new View.OnClickListener() {
27 public void onClick(View view) {
Intent intent=new Intent(detailTracNghiemToan.this,listTracNghiemToan.class ;) startActivity(intent);
The provided code snippet demonstrates the implementation of a detail view in an Android application, specifically within the `detailTracNghiemVan` class that extends `AppCompatActivity` It includes essential imports such as `Dialog`, `Intent`, and UI components like `Button`, `EditText`, and `TextView` The class is designed to manage user interactions and display quiz details, utilizing the `quizcontractDao` for data handling and the `QuizContract` model for structuring quiz information This foundational setup is crucial for creating a responsive and interactive user experience in the app.
EditText txtcauhoi txtoption1 txtoption2 txtoption3 txtcaudung, , , , ;
Button btnUpdate btnback, ; quizcontractDao quizcontractDao;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_trac_nghiem_van);
Bundle bundle=intent.getBundleExtra("DATA"); int id=bundle.getInt("id");
String question=bundle.getString("question");
String option1=bundle.getString("option1");
String option2=bundle.getString("option2");
String option3=bundle.getString("option3");
In the detailTracNghiemVan activity, the answer is retrieved from the bundle using the key "answer" The quizcontractDao is instantiated to manage quiz data The question and options are displayed by setting the text of txtcauhoi, txtoption1, txtoption2, and txtoption3 The correct answer is shown in txtcaudung, and an update button is set up with an onClickListener for user interaction.
@Override public void onClick(View view) {
QuizContract quiz=new QuizContract( id, txtcauhoi.getText().toString(), txtoption1.getText().toString(), txtoption2.getText().toString(), txtoption3.getText().toString(), txtcaudung.getText().toString(),
); try { if (quizcontractDao.updateQuiz(quiz)> ){0 showdialog();
Toast.makeText(detailTracNghiemVan.this,"lốỗi x y ra"ả ,Toast.LENGTH_SHORT).show(); }
// Toast.makeText(detailTracNghiemVan.this,"lốỗi",Toast.LENGTH_SHORT).show(); }
}); btnback.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent intent=new Intent(detailTracNghiemVan.this,listTracNghiemVan.class ;) startActivity(intent);
In the method `anhxa()`, various user interface elements are initialized, including `txtcauhoi` for the question text, `txtoption1`, `txtoption2`, and `txtoption3` for the answer options, `txtcaudung` for the correct answer display, and buttons `btnUpdate` and `btnback` for user interactions.
Dialog dialog = new Dialog(detailTracNghiemVan.this ;) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_success); dialog.show();
Button btnok=dialog.findViewById(R.id.btnOk);
TextView txt1=dialog.findViewById(R.id.txt1);
TextView txt2=dialog.findViewById(R.id.txt2); txt1.setText("C p Nh t Thành Cống"ậ ậ ); txt2.setVisibility(View.INVISIBLE); btnok.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent intent=new Intent(detailTracNghiemVan.this,listTracNghiemVan.class ;) startActivity(intent);
2.2.5 Danh sách toàn bộ câu hỏi Toán và Tiếng Việt
The article discusses the implementation of a list in an Android application using the RecyclerView component It highlights the necessary imports, including AppCompatActivity, LinearLayoutManager, and RecyclerView The code snippet demonstrates how to set up an activity with a RecyclerView, manage the layout, and handle user interactions through buttons Additionally, it emphasizes the importance of utilizing intents and bundles for data passing within the app.
31 import tktsp.example.a17dtha2_aptracnghiem.DAO.quizcontractDao; import tktsp.example.a17dtha2_aptracnghiem.adapter.tracnghiemtoanAdapter; import tktsp.example.a17dtha2_aptracnghiem.model.QuizContract; public class listTracNghiemToan extends AppCompatActivity {
List listquiz; quizcontractDao quizcontractDao; tracnghiemtoanAdapter adapter;
In the `onCreate` method of the `listTracNghiemToan` activity, the layout is set to `activity_list_trac_nghiem_toan`, and a RecyclerView is initialized to display quiz items A LinearLayoutManager is applied to the RecyclerView for proper item arrangement The `quizcontractDao` is instantiated to retrieve quiz data by category, specifically category 1 An adapter, `tracnghiemtoanAdapter`, is created using the fetched quiz list and set to the RecyclerView Additionally, buttons for navigation and adding new items are initialized, with a click listener set for the "add" button.
@Override public void onClick(View view) {
Intent intent=new Intent(listTracNghiemToan.this,addQuestionToan.class ;) startActivity(intent);
}); btnback.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent intent=new Intent(listTracNghiemToan.this,quanlyTracNghiem.class); startActivity(intent);
Màn hình khi làm trắc nghiệm
Code mẫu: import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.animation.ArgbEvaluator; import android.animation.ObjectAnimator; import android.annotation.SuppressLint; import android.app.Dialog;
The `QuizActivity` class in this Android application imports essential libraries for functionality, including `Context`, `Intent`, and `MediaPlayer` It sets up the activity with a countdown timer, vibration effects, and UI elements such as buttons and radio buttons The use of `Paper` for data storage and `quizcontractDao` for database interactions indicates a focus on managing quiz data The activity aims to provide an engaging user experience while adhering to modern Android development practices, including support for various Android versions through the `Build` class.
TextView txtDiem txtCountQuiz txtQuestion txtCountDown, , , ; LinearLayout bgquiz; private ColorStateList textColorDefaultRb;
The code snippet initializes a private ColorStateList for default text color and declares a list to hold QuizContract objects It also tracks the current question with an integer counter and total questions, along with the current QuizContract instance The score is maintained as an integer, while a boolean indicates if the question has been answered Additionally, the code references a quiz contract data access object (DAO) and utilizes a CountDownTimer to manage the remaining time in milliseconds.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz); anhxa(); textColorDefaultRb rb1= getTextColors(); textColorDefaultCd txtCountDown= getTextColors(); quizcontractDao=new quizcontractDao(QuizActivity.this ;)
Paper.init(QuizActivity.this); int id_cat= Paper.book().read(General.CATEGORY); quizContractList quizcontractDao= getQuizbyCat(id_cat); questionTotal quizContractList= size();
Collections.shuffle(quizContractList); //dòng này cho phép sáo tr n phầần t trong m ngộ ử ả showNextQuestion(); btnNext.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
// showNextQuestion(); if(!answered){ if (rb1.isChecked() || rb3.isChecked() || rb2.isChecked() ){ checkAnswerd();
Toast.makeText(QuizActivity.this,"Vui lòng ch n đáp án"ọ ,Toast.LENGTH_SHORT).show(); }
In the method `anhxa()`, various UI components are initialized, including buttons, text views, and a radio group The buttons for canceling and proceeding to the next question are linked to their respective IDs, while text views display the score, quiz count, and current question Additionally, three radio buttons are set up for user selection A countdown timer is also implemented to enhance the quiz experience The cancel button's functionality is defined using an `OnClickListener`, allowing for user interaction within the quiz application.
@Override public void onClick(View view) {
Dialog dialog = new Dialog(QuizActivity.this ;) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_fail); dialog.show();
Button btnok = (Button) dialog.findViewById(R.id.btnOk); btnok.setOnClickListener(new View.OnClickListener() {
// @RequiresApi(api = Build.VERSION_CODES.P)
@Override public void onClick(View view) {
Intent intent=new Intent(QuizActivity.this,bottomNavigation.class); startActivity(intent);
Button btnhuy = (Button) dialog.findViewById(R.id.btnHuy); btnhuy.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) { dialog.dismiss();
The button is labeled "Confirm," and the default text color is applied to the radio buttons The radio button selections are cleared, and if there are more questions remaining, the current question is retrieved from the quiz contract list The options for the current question are displayed as "A," "B," and "C," followed by their respective answers.
//int stt=questionCounter+1; txtQuestion.setText("Cầu H i "ỏ +(questionCounter+1)+":
"+questionCurrent.getQuestion().toString()); txtCountQuiz.setText("Quiz : "+(questionCounter+1)+" / "+questionTotal); answeredse; questionCounter++;
//ch y countdownạ timeLeftInMillis 000; //30 giầy startCountDown();
} private void startCountDown(){ countDownTimer =new CountDownTimer(timeLeftInMillis,1000) { @Override public void onTick(long l) { //c sau 1 giầy ch y hàm onTickứ ạ timeLeftInMillis=l; //l cho biêắt sốắ mili giầy còn l iạ updateCountDown();
@Override public void onFinish() { timeLeftInMillis=0; updateCountDown(); checkAnswerd();
39 private void updateCountDown(){ int minustes =(int) (timeLeftInMillis / 1000) /60; // lầắy phút int seconds =(int) (timeLeftInMillis / 1000) % 60; // lầắy giay
/// quy chu n này đ m b o rắng sốắ phút và giầy đ m b o đúng v i timeLeftInMillis đã setẩ ả ả ẩ ả ớ
To format the countdown timer, use the code `String timeFormat=String.format(Locale.getDefault(),"%02d : %02d", minutes, seconds);` and set the text with `txtCountDown.setText(timeFormat);` If the remaining time is less than 6000 milliseconds, change the text color to red with `txtCountDown.setTextColor(Color.RED);` Additionally, play a sound using `MediaPlayer.create(this,R.raw.cat_sound)` and start it with `mp3.start();` To provide a tactile alert, utilize the vibrator service, checking for Android version compatibility with `if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)`, and then execute a vibration effect with `v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));`.
} animator=ObjectAnimator.ofInt(bgquiz,"backgroundColor",Color.RED,Color.YELLOW,Color.parseColor("#E
CA53E")); animator.setDuration(500); animator.setEvaluator(new ArgbEvaluator());
//animator.setRepeatCount(Animation.INFINITE); animator.start(); else } { txtCountDown.setTextColor(textColorDefaultCd);
} private void checkAnswerd(){ bgquiz.clearAnimation(); answered=true; countDownTimer.cancel();
RadioButton selected=findViewById(radio_button.getCheckedRadioButtonId());
//ánh x buttom đã checkạ int vitrichon=radio_button.indexOfChild(selected)+1; if (vitrichon==Integer.parseInt(questionCurrent.getAnswer())){ score=score+10; txtDiem.setText("score : "+score);
The method `ketqua()` changes the text color of three radio buttons based on the current question's answer Initially, all buttons are set to red Depending on the answer's value, the corresponding button's text color is updated to green, indicating the correct choice.
} if (questionCounter < questionTotal){ btnNext.setText("Tiêắp T c"ụ ); else } { btnNext.setText("Kêắt Thúc");
Intent intent=new Intent(QuizActivity.this,KetQuaActivity.class ;) Bundle bundle = new Bundle(); bundle.putInt("total_score",score); intent.putExtra("DATA", bundle); startActivity(intent);
@Override protected void onDestroy() { super.onDestroy(); if (v.hasVibrator() && v!=null){ v.cancel();
} if (mp3.isPlaying() && mp3 !=null) { mp3.pause(); mp3.stop(); mp3.release();