// MainActivity.java package com.exa… · The Chat Archive
Explore / Programming // MainActivity.java package com.example.myapplication.View; import android.app.Dialog;… Save Share Download ▾ Report// MainActivity.java
package com.example.myapplication.View;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication.Attempt_Quiz_Section.Tests;
import com.example.myapplication.Create_Quiz.create_quiz_main;
import com.example.myapplication.Model.User;
import com.example.myapplication.R;
import com.example.myapplication.Auth_Controller.ResetPasswordActivity;
import com.example.myapplication.Auth_Controller.LoginActivity;
import com.example.myapplication.Results_section.ResultsAdmin;
import com.example.myapplication.AdminSection.ManageUsersActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseDatabase database;
private FirebaseAuth auth;
private DatabaseReference myRef;
private TextView userEmailTextView;
private boolean isAdmin = false;
private TextView userIDTextView;
private CircleImageView imageView;
private CircleImageView headerImageView;
private FloatingActionButton floatingActionButton;
private NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Ensure you have the correct layout
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imageView = findViewById(R.id.card1);
floatingActionButton = findViewById(R.id.chatHead);
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
// Initialize navigationView before calling checkForAdmin()
navigationView = findViewById(R.id.nav_view);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// Set up navigation header
View header = navigationView.getHeaderView(0);
headerImageView = header.findViewById(R.id.imageView);
userEmailTextView = header.findViewById(R.id.text_user_name);
setUserEmailInHeader();
navigationView.setNavigationItemSelectedListener(this);
userIDTextView = findViewById(R.id.text_user_card);
setUserDisplayName();
floatingActionButton.setOnClickListener(v -> {
if (isAdmin) {
startActivity(new Intent(MainActivity.this, create_quiz_main.class));
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
} else {
Toast.makeText(MainActivity.this, "You are not an admin", Toast.LENGTH_SHORT).show();
}
});
checkForAdmin(); // Check for admin privileges after initializing navigationView
}
private void checkForAdmin() {
myRef.child("admins").addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String uid = auth.getUid();
if (uid != null && dataSnapshot.child(uid).exists() &&
Boolean.TRUE.equals(dataSnapshot.child(uid).getValue(Boolean.class))) {
isAdmin = true;
Toast.makeText(getApplicationContext(),
"Здравствуйте, Администратор!",
Toast.LENGTH_LONG).show();
} else {
isAdmin = false;
}
// Update visibility of the "Create Test" menu item
Menu navMenu = navigationView.getMenu();
navMenu.findItem(R.id.create_test).setVisible(isAdmin);
navMenu.findItem(R.id.nav_manage_users).setVisible(isAdmin);
// Optionally, hide the floating action button for non-admins
if (!isAdmin) {
floatingActionButton.hide();
} else {
floatingActionButton.show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
// Handle possible errors
Toast.makeText(getApplicationContext(),
"Failed to check admin status.",
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(
R.id.drawer_layout);
if (drawer.isDrawerOpen(
GravityCompat.START)) {
drawer.closeDrawer(
GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu if you want to add items to the action bar (if needed)
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here (if needed)
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here
int id = item.getItemId();
if (id == R.id.nav_test) {
// Open Tests activity
if (isNetworkAvailable(MainActivity.this)) {
startActivity(new Intent(MainActivity.this, Tests.class));
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
} else {
alertNoConnection();
}
} else if (id == R.id.nav_result) {
// Open Results activity
if (isNetworkAvailable(MainActivity.this)) {
Intent intent = new Intent(MainActivity.this, ResultsAdmin.class);
intent.putExtra("ISADMIN", isAdmin);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
} else {
alertNoConnection();
}
} else if (id == R.id.nav_manage_users) {
// Open Manage Users activity
if (isAdmin && isNetworkAvailable(MainActivity.this)) {
startActivity(new Intent(MainActivity.this, ManageUsersActivity.class));
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
} else if (isNetworkAvailable(MainActivity.this)) {
Toast.makeText(getApplicationContext(), "You are not an administrator!", Toast.LENGTH_SHORT).show();
} else {
alertNoConnection();
}
} else if (id == R.id.create_test) {
// Open Create Quiz activity
if (isAdmin && isNetworkAvailable(MainActivity.this)) {
startActivity(new Intent(MainActivity.this, create_quiz_main.class));
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
} else if (isNetworkAvailable(MainActivity.this)) {
Toast.makeText(getApplicationContext(), "You are not an administrator!", Toast.LENGTH_SHORT).show();
} else {
alertNoConnection();
}
} else if (id == R.id.nav_respass) {
// Open Reset Password activity
if (isNetworkAvailable(MainActivity.this)) {
startActivity(new Intent(MainActivity.this, ResetPasswordActivity.class));
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
} else {
alertNoConnection();
}
} else if (id == R.id.nav_signout) {
// Sign out and return to Login screen
auth.signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setUserDisplayName() {
DatabaseReference usersRef = myRef.child("users");
String uid = auth.getUid();
if (uid != null) {
usersRef.child(uid)
.addValueEventListener(
new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
User user = dataSnapshot.getValue(User.class);
if (user != null && user.name != null) {
String message = "Hey " + user.name + ", what's up!";
userIDTextView.setText(message);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
// Handle possible errors
}
});
}
}
private void setUserEmailInHeader() {
FirebaseUser currentUser = auth.getCurrentUser();
if (currentUser != null) {
userEmailTextView.setText(currentUser.getEmail());
}
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null &&
connectivityManager.getActiveNetworkInfo().isConnected();
}
public void alertNoConnection() {
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (builder.getWindow() != null) {
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
builder.setOnDismissListener(dialogInterface -> {
// Do nothing
});
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.nowifi); // Ensure you have an image named 'nowifi' in your resources
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
400,
400));
builder.show();
}
Assistant2024-12-02 05:31 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Dec 2, 2024
Added to archive Nov 16, 2026
ID 01m7h42ajh9e2961xdnyh2txpdSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 0b07b41563df65184658938588420dc4
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
// create_quiz_main.java
package com.example.myapplication.Create_Quiz;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.example.myapplication.Model.Test;
import com.example.myapplication.R;
import com.example.myapplication.Create_Quiz.Custom_quiz;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.*;
import java.util.ArrayList;
import java.util.Objects;
public class create_quiz_main extends AppCompatActivity {
private Button addButton;
private Toolbar toolbar;
private ListView testListView;
private ArrayList<Test> adminTests;
private TestAdapter testAdapter;
private FirebaseDatabase database;
private DatabaseReference myRef;
private FirebaseAuth auth;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Ensure you're using the correct layout file
setContentView(R.layout.content_main_1);
// Initialize Firebase
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
auth = FirebaseAuth.getInstance();
toolbar = findViewById(R.id.toolbartst);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
// Initialize the ListView and adapter
testListView = findViewById(R.id.test_list_view);
adminTests = new ArrayList<>();
testAdapter = new TestAdapter(this, adminTests);
testListView.setAdapter(testAdapter);
// Load the admin's tests
loadAdminTests();
// Initialize "Add" button
addButton = findViewById(R.id.add_button);
if (addButton == null) {
Log.e("create_quiz_main", "add_button is null. Check your layout file.");
}
// Set click listener on "Add" button
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("create_quiz_main", "Add button clicked");
Toast.makeText(create_quiz_main.this, "Add button clicked", Toast.LENGTH_SHORT).show();
try {
Intent intent = new Intent(create_quiz_main.this, Custom_quiz.class);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(create_quiz_main.this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
// Set click listener on list items
testListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// You can implement editing or viewing of the selected test here
}
});
}
private void loadAdminTests() {
myRef.child("tests").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
adminTests.clear();
for (DataSnapshot testSnapshot : snapshot.getChildren()) {
String adminUID = testSnapshot.child("adminUID").getValue(String.class);
if (auth.getUid().equals(adminUID)) {
Test test = new Test();
test.setName(testSnapshot.getKey());
test.setAdminUID(adminUID);
// You can retrieve other test details if needed
adminTests.add(test);
}
}
testAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
// Handle errors if any
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// Custom_quiz.java
package com.example.myapplication.Create_Quiz;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.example.myapplication.Model.Question;
import com.example.myapplication.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;
public class Custom_quiz extends AppCompatActivity {
EditText question;
EditText aText;
EditText bText;
EditText cText;
EditText dText;
RadioButton aRadio;
RadioButton bRadio;
RadioButton cRadio;
RadioButton dRadio;
RadioGroup optionsGroup;
int currentQuestion = 1;
int previousQuestion = 1;
EditText questionNumber;
ArrayList<Question> ques;
JSONArray jsonArray;
String selectedOption = "";
String fileName = "file";
private FirebaseDatabase database;
private FirebaseAuth auth;
private DatabaseReference myRef;
CardView fab, f2, fl;
Button addOptionButton;
Button removeOptionButton;
int optionCount = 2;
private LinearLayout optionCLayout, optionDLayout;
// New variables for image selection
private Button selectImageButton;
private Uri selectedImageUri = null;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
jsonArray = new JSONArray();
setContentView(R.layout.activity_create_quiz);
question = findViewById(R.id.questionView);
aText = findViewById(R.id.aText);
bText = findViewById(R.id.bText);
cText = findViewById(R.id.cText);
dText = findViewById(R.id.dText);
questionNumber = findViewById(R.id.questionNumber);
aRadio = findViewById(R.id.aRadio);
bRadio = findViewById(R.id.bRadio);
cRadio = findViewById(R.id.cRadio);
dRadio = findViewById(R.id.dRadio);
optionsGroup = findViewById(R.id.optionsGroup);
addOptionButton = findViewById(R.id.addOptionButton);
removeOptionButton = findViewById(R.id.removeOptionButton);
optionCLayout = findViewById(R.id.optionCLayout);
optionDLayout = findViewById(R.id.optionDLayout);
optionCLayout.setVisibility(View.GONE);
optionDLayout.setVisibility(View.GONE);
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
selectedOption = "";
currentQuestion = 1;
setListeners();
ques = new ArrayList<>();
fab = findViewById(R.id.nextfab);
fl = findViewById(R.id.fab2); // Save button
f2 = findViewById(R.id.pre_card);
f2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (previousQuestion > 1) {
previousQuestion--;
setAllData(previousQuestion);
}
if (previousQuestion == 1)
f2.setVisibility(View.INVISIBLE);
Toast.makeText(Custom_quiz.this, String.valueOf(previousQuestion), Toast.LENGTH_SHORT).show();
}
});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Save current question
boolean cont = getEnteredQuestionsValue();
if (cont) {
previousQuestion++;
currentQuestion++;
Toast.makeText(Custom_quiz.this, "Вопрос " + currentQuestion, Toast.LENGTH_SHORT).show();
questionNumber.setText(String.valueOf(currentQuestion));
clearAllData();
f2.setVisibility(View.VISIBLE);
resetOptionCount();
}
}
});
fl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Save current question if not yet saved
boolean cont = getEnteredQuestionsValue();
if (cont || jsonArray.length() > 0) {
final JSONObject tempObject = new JSONObject();
// Get view from dialog_custom.xml
LayoutInflater li = LayoutInflater.from(Custom_quiz.this);
View promptsView = li.inflate(R.layout.dialog_custom, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Custom_quiz.this);
// Set dialog_custom.xml to AlertDialog Builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = promptsView.findViewById(R.id.editTextDialogUserInput);
final EditText userTime = promptsView.findViewById(R.id.editTextDialogUserInput1);
// Optionally set time limit
userTime.setHint("Введите время в минутах (опционально)");
// Setup dialog
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String timeStr = userTime.getText().toString().trim();
try {
tempObject.put("Questions", jsonArray);
tempObject.put("adminUID", auth.getUid()); // Include admin UID
if (!TextUtils.isEmpty(timeStr)) {
int time = Integer.parseInt(timeStr);
tempObject.put("Time", time);
} else {
tempObject.put("Time", 0); // No time limit
}
} catch (JSONException e) {
e.printStackTrace();
}
final String jsonStr = tempObject.toString();
// Get test name
if (!TextUtils.isEmpty(userInput.getText().toString())) {
String testName = userInput.getText().toString().trim();
Map<String, Object> result = new Gson().fromJson(jsonStr, Map.class);
myRef.child("tests").child(testName).setValue(result);
Toast.makeText(getApplicationContext(), "Тест успешно сохранён", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Имя теста не может быть пустым", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// Create AlertDialog
AlertDialog alertDialog = alertDialogBuilder.create();
// Show it
alertDialog.show();
} else {
Toast.makeText(getApplicationContext(),
"Некорректный формат вопроса", Toast.LENGTH_SHORT).show();
}
}
});
addOptionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
increaseOptionCount();
}
});
removeOptionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
decreaseOptionCount();
}
});
// Set initial option count
resetOptionCount();
// Initialize image selection button
selectImageButton = findViewById(R.id.selectImageButton);
selectImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Выберите изображение"), 1);
}
});
}
private void resetOptionCount() {
optionCount = 2;
optionCLayout.setVisibility(View.GONE);
optionDLayout.setVisibility(View.GONE);
cText.setText("");
dText.setText("");
cRadio.setChecked(false);
dRadio.setChecked(false);
checkOptionButtons();
}
private void increaseOptionCount() {
if (optionCount < 4) {
optionCount++;
if (optionCount == 3) {
optionCLayout.setVisibility(View.VISIBLE);
cText.setVisibility(View.VISIBLE);
cRadio.setVisibility(View.VISIBLE);
} else if (optionCount == 4) {
optionDLayout.setVisibility(View.VISIBLE);
dText.setVisibility(View.VISIBLE);
dRadio.setVisibility(View.VISIBLE);
}
}
checkOptionButtons();
}
private void decreaseOptionCount() {
if (optionCount > 2) {
if (optionCount == 4) {
optionDLayout.setVisibility(View.GONE);
dText.setText("");
dText.setVisibility(View.GONE);
dRadio.setChecked(false);
dRadio.setVisibility(View.GONE);
if (dRadio.isChecked()) {
dRadio.setChecked(false);
selectedOption = "";
}
} else if (optionCount == 3) {
optionCLayout.setVisibility(View.GONE);
cText.setText("");
cText.setVisibility(View.GONE);
cRadio.setChecked(false);
cRadio.setVisibility(View.GONE);
if (cRadio.isChecked()) {
cRadio.setChecked(false);
selectedOption = "";
}
}
optionCount--;
}
checkOptionButtons();
}
private void checkOptionButtons() {
if (optionCount == 2) {
removeOptionButton.setEnabled(false);
} else {
removeOptionButton.setEnabled(true);
}
if (optionCount == 4) {
addOptionButton.setEnabled(false);
} else {
addOptionButton.setEnabled(true);
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
final AlertDialog.Builder builder = new AlertDialog.Builder(Custom_quiz.this);
builder.setMessage("Выйти без сохранения?");
builder.setPositiveButton("Ок", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public void setAllData(int position) {
clearAllData();
Question question1 = ques.get(position - 1);
questionNumber.setText(String.valueOf(question1.getId()));
question.setText(question1.getQuestion());
aText.setText(question1.getOpt_A());
bText.setText(question1.getOpt_B());
switch (question1.getOptionCount()) {
case 2:
resetOptionCount();
break;
case 3:
increaseOptionCount(); // to 3
cText.setText(question1.getOpt_C());
break;
case 4:
increaseOptionCount(); // to 3
increaseOptionCount(); // to 4
cText.setText(question1.getOpt_C());
dText.setText(question1.getOpt_D());
break;
}
switch (question1.getAnswer()) {
case "A":
aRadio.setChecked(true);
break;
case "B":
bRadio.setChecked(true);
break;
case "C":
cRadio.setChecked(true);
break;
case "D":
dRadio.setChecked(true);
break;
}
// No need to load image here since we are not editing images in previous questions
}
private void clearAllData() {
aRadio.setChecked(false);
bRadio.setChecked(false);
cRadio.setChecked(false);
dRadio.setChecked(false);
aText.setText(null);
bText.setText(null);
cText.setText(null);
dText.setText(null);
question.setText(null);
selectedOption = "";
selectedImageUri = null;
}
private boolean getEnteredQuestionsValue() {
boolean cont = false;
if (TextUtils.isEmpty(question.getText().toString().trim())) {
question.setError("Пожалуйста, заполните вопрос");
} else if (TextUtils.isEmpty(aText.getText().toString().trim())) {
aText.setError("Пожалуйста, заполните вариант A");
} else if (TextUtils.isEmpty(bText.getText().toString().trim())) {
bText.setError("Пожалуйста, заполните вариант B");
} else if (optionCount >= 3 && TextUtils.isEmpty(cText.getText().toString().trim())) {
cText.setError("Пожалуйста, заполните вариант C");
} else if (optionCount == 4 && TextUtils.isEmpty(dText.getText().toString().trim())) {
dText.setError("Пожалуйста, заполните вариант D");
} else if (selectedOption.equals("")) {
Toast.makeText(this, "Пожалуйста, выберите правильный ответ", Toast.LENGTH_SHORT).show();
} else {
// Create Question object
final Question quest = new Question();
quest.setId(currentQuestion);
quest.setQuestion(question.getText().toString());
quest.setOpt_A(aText.getText().toString());
quest.setOpt_B(bText.getText().toString());
if (optionCount >= 3)
quest.setOpt_C(cText.getText().toString());
if (optionCount == 4)
quest.setOpt_D(dText.getText().toString());
quest.setOptionCount(optionCount);
quest.setAnswer(selectedOption);
if (selectedImageUri != null) {
String imageBase64 = encodeImageToBase64(selectedImageUri);
quest.setImageBase64(imageBase64);
}
// Add question to list and JSON
addQuestion(quest);
cont = true;
}
return cont;
}
private void addQuestion(Question quest) {
ques.add(quest);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("answer", quest.getAnswer());
jsonObject.put("opt_A", quest.getOpt_A());
jsonObject.put("opt_B", quest.getOpt_B());
if (optionCount >= 3)
jsonObject.put("opt_C", quest.getOpt_C());
if (optionCount == 4)
jsonObject.put("opt_D", quest.getOpt_D());
jsonObject.put("question", quest.getQuestion());
jsonObject.put("optionCount", quest.getOptionCount());
if (quest.getImageBase64() != null)
jsonObject.put("imageBase64", quest.getImageBase64());
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(jsonObject);
}
private void setListeners() {
aRadio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedOption = "A";
bRadio.setChecked(false);
cRadio.setChecked(false);
dRadio.setChecked(false);
}
});
bRadio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedOption = "B";
aRadio.setChecked(false);
cRadio.setChecked(false);
dRadio.setChecked(false);
}
});
cRadio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedOption = "C";
aRadio.setChecked(false);
bRadio.setChecked(false);
dRadio.setChecked(false);
}
});
dRadio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedOption = "D";
aRadio.setChecked(false);
bRadio.setChecked(false);
cRadio.setChecked(false);
}
});
}
// Method to encode image to Base64
private String encodeImageToBase64(Uri imageUri) {
try {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// Compress the image to reduce size
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos); // Adjust quality as needed
byte[] bytes = baos.toByteArray();
return Base64.encodeToString(bytes, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// Handle image selection result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Handle image selection result
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
selectedImageUri = data.getData();
// Optionally, display a message indicating that the image has been selected
Toast.makeText(this, "Изображение выбрано", Toast.LENGTH_SHORT).show();
}
}
package com.example.myapplication.Create_Quiz;
import android.content.Context;
import android.view.;
import android.widget. ;
import com.example.myapplication.Model.Test;
import com.example.myapplication.R;
import java.util.ArrayList;
public class TestAdapter extends ArrayAdapter {
private Context mContext;
ArrayList dataList;
public TestAdapter(Context context, ArrayList<Test> list) {
super(context, 0, list);
mContext = context;
dataList = list;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View listItem = convertView;
if (listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.test_item, parent, false);
((ImageView) listItem.findViewById(R.id.item_imageView))
.setImageDrawable(mContext.getDrawable(R.drawable.ic_appicon));
((TextView) listItem.findViewById(R.id.item_textView))
.setText(dataList.get(position).getName());
((Button) listItem.findViewById(R.id.item_button)).setVisibility(View.GONE);
// Set click listeners if needed
return listItem;
}
package com.example.myapplication.Attempt_Quiz_Section;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.example.myapplication.R;
import com.example.myapplication.Model.Question;
import com.example.myapplication.Model.Test;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import es.dmoral.toasty.Toasty;
public class AttemptTest extends AppCompatActivity {
ArrayList<Question> questions;
String[] answers;
Toolbar toolbar;
ViewPager2 scrollView;
LinearLayout indexLayout;
GridView quesGrid;
ArrayList<String> list;
ArrayList<String> arrayList;
int flag_controller = 1;
long timer;
popGridAdapter popGrid;
Button next, prev;
private DatabaseReference mDatabase;
private FirebaseAuth auth;
private String TESTNAME;
private int countPaused = 0;
private boolean hasTimeLimit = false;
private int score = 0;
private int totalQuestions = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDatabase = FirebaseDatabase.getInstance().getReference();
auth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_attempt);
questions = ((Test) getIntent().getExtras().get("Questions")).getQuestions();
TESTNAME = (String) getIntent().getExtras().get("TESTNAME");
answers = new String[questions.size()];
totalQuestions = questions.size();
toolbar = findViewById(R.id.toolbar);
toolbar.setTitleTextColor(getResources().getColor(android.R.color.black));
setSupportActionBar(toolbar);
scrollView = findViewById(R.id.discrete);
scrollView.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
final QuestionAdapter questionAdapter = new QuestionAdapter(questions);
scrollView.setAdapter(questionAdapter);
next = findViewById(R.id.next);
next.setOnClickListener(view -> {
if (scrollView.getCurrentItem() == questions.size() - 1) {
showPopUp();
} else {
scrollView.setCurrentItem(scrollView.getCurrentItem() + 1);
}
});
prev = findViewById(R.id.prev);
prev.setOnClickListener(view -> {
if (scrollView.getCurrentItem() != 0) {
scrollView.setCurrentItem(scrollView.getCurrentItem() - 1);
}
});
setNextPrevButton(scrollView.getCurrentItem());
indexLayout = findViewById(R.id.index_layout);
indexLayout.setAlpha(.5f);
quesGrid = findViewById(R.id.pop_grid);
popGrid = new popGridAdapter(AttemptTest.this);
quesGrid.setAdapter(popGrid);
quesGrid.setOnItemClickListener((adapterView, view, i, l) -> {
scrollView.setCurrentItem(i);
slideUp(indexLayout);
});
scrollView.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
setNextPrevButton(position);
}
});
Long testTime = ((Test) getIntent().getExtras().get("Questions")).getTime();
if (testTime != null && testTime > 0) {
timer = testTime * 60 * 1000;
hasTimeLimit = true;
} else {
timer = -1;
hasTimeLimit = false;
}
if (hasTimeLimit) {
Toasty.info(AttemptTest.this, "У Вас ограничение по времени! Завершите или отправьте свой тест.", Toasty.LENGTH_LONG).show();
}
}
void showPopUp() {
AlertDialog.Builder builder = new AlertDialog.Builder(AttemptTest.this);
builder.setMessage("Вы хотите отправить результаты?");
builder.setPositiveButton("Да", (dialogInterface, i) -> {
submit();
dialogStart();
});
builder.setNegativeButton("Нет", (dialogInterface, i) -> dialogInterface.cancel());
builder.show();
}
/* Отправка результатов в базу данных */
void submit() {
flag_controller = 0;
score = 0;
list = new ArrayList<>();
arrayList = new ArrayList<>();
for (int i = 0; i < answers.length; i++) {
if (answers[i] != null && answers[i].equals(questions.get(i).getAnswer())) {
score++;
}
String temp = (answers[i] != null) ? answers[i] + ")" : "null) ";
list.add("Ваш выбор (" + temp + " Правильный ответ (" + questions.get(i).getAnswer() + ")");
arrayList.add(questions.get(i).getQuestion());
}
try {
mDatabase.child("Results").child(((Test) getIntent().getExtras().get("Questions")).getName())
.child(auth.getUid()).setValue(score);
} catch (Exception e) {
Log.e("Result Update Failed ", e.getMessage());
}
}
void dialogStart() {
AlertDialog.Builder builder = new AlertDialog.Builder(AttemptTest.this);
builder.setTitle("Ваш результат");
builder.setMessage("Вы ответили правильно на " + score + " из " + totalQuestions + " вопросов.");
builder.setCancelable(false);
builder.setPositiveButton("Просмотреть ответы", (dialog, which) -> showDetailedResults());
builder.setNegativeButton("Закончить", (dialog, which) -> {
finish();
dialog.dismiss();
});
builder.show();
}
void showDetailedResults() {
final AlertDialog.Builder builderSingle = new AlertDialog.Builder(AttemptTest.this);
builderSingle.setIcon(R.mipmap.ic_launcher_round);
builderSingle.setTitle("Ответы на " + TESTNAME);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(AttemptTest.this, android.R.layout.select_dialog_item);
final ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<>(AttemptTest.this, android.R.layout.select_dialog_item);
for (String y : arrayList) {
arrayAdapter1.add(y);
}
for (String x : list) {
arrayAdapter.add(x);
}
builderSingle.setCancelable(false);
builderSingle.setNegativeButton("Готово!", (dialog, which) -> {
finish();
dialog.dismiss();
});
builderSingle.setAdapter(arrayAdapter1, (dialog, which) -> {
String strName = arrayAdapter.getItem(which);
AlertDialog.Builder builderInner = new AlertDialog.Builder(AttemptTest.this);
builderInner.setMessage(strName);
builderInner.setCancelable(false);
builderInner.setTitle("Ваш ответ:");
builderInner.setPositiveButton("Ок", (dialog1, which1) -> builderSingle.show());
builderInner.show();
});
builderSingle.show();
}
@Override
protected void onPause() {
super.onPause();
if (hasTimeLimit && countPaused <= 2 && countPaused >= 0 && flag_controller == 1) {
Toasty.info(AttemptTest.this, "Завершите или отправьте свой тест! У вас ограничение по времени.", Toasty.LENGTH_LONG).show();
}
countPaused++;
}
@Override
protected void onResume() {
super.onResume();
if (hasTimeLimit && countPaused > 2) {
Toasty.success(AttemptTest.this, "Спасибо! Ваши ответы были отправлены.", Toasty.LENGTH_SHORT).show();
countPaused = -1000;
submit();
dialogStart();
}
}
@Override
protected void onRestart() {
super.onRestart();
if (hasTimeLimit) {
Toasty.info(AttemptTest.this, "Завершите или отправьте свой тест! У вас ограничение по времени.", Toasty.LENGTH_LONG).show();
}
}
void setNextPrevButton(int pos) {
if (pos == 0) {
prev.setText("");
} else {
prev.setText("Предыдущий");
}
if (pos == questions.size() - 1) {
next.setText("Отправить");
} else {
next.setText("Следующий");
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
showPopUp();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.attempt_menu, menu);
if (hasTimeLimit) {
final MenuItem counter = menu.findItem(R.id.counter);
new CountDownTimer(timer, 1000) {
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
long hr = TimeUnit.MILLISECONDS.toHours(millis);
long mn = TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
long sc = TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
String hms = format(hr) + ":" + format(mn) + ":" + format(sc);
counter.setTitle(hms);
timer = millis;
}
String format(long n) {
return n < 10 ? "0" + n : "" + n;
}
public void onFinish() {
submit();
dialogStart();
}
}.start();
} else {
MenuItem counter = menu.findItem(R.id.counter);
counter.setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.submit) {
showPopUp();
return true;
} else if (id == R.id.info) {
togglePopUp();
}
return super.onOptionsItemSelected(item);
}
void togglePopUp() {
if (indexLayout.getVisibility() == View.GONE) {
slideDown(indexLayout);
} else {
slideUp(indexLayout);
}
}
class QuestionAdapter extends RecyclerView.Adapter<QuestionAdapter.ViewHolder> {
private ArrayList<Question> data;
QuestionAdapter(ArrayList<Question> data) {
this.data = data;
}
@Override
public QuestionAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.frag_test, parent, false);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
v.setLayoutParams(params);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(final QuestionAdapter.ViewHolder holder, final int position) {
Question currentQuestion = data.get(position);
holder.questionText.setText(currentQuestion.getQuestion());
// Decode and display image if available
holder.questionImageView.setVisibility(View.GONE);
String imageBase64 = currentQuestion.getImageBase64();
if (imageBase64 != null && !imageBase64.isEmpty()) {
byte[] decodedString = Base64.decode(imageBase64, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.questionImageView.setImageBitmap(decodedByte);
holder.questionImageView.setVisibility(View.VISIBLE);
}
holder.r1.setText(currentQuestion.getOpt_A());
holder.r2.setText(currentQuestion.getOpt_B());
holder.r5.setText("Снять выбор");
int optionCount = currentQuestion.getOptionCount();
if (optionCount >= 3) {
holder.r3.setVisibility(View.VISIBLE);
holder.r3.setText(currentQuestion.getOpt_C());
} else {
holder.r3.setVisibility(View.GONE);
}
if (optionCount == 4) {
holder.r4.setVisibility(View.VISIBLE);
holder.r4.setText(currentQuestion.getOpt_D());
} else {
holder.r4.setVisibility(View.GONE);
}
holder.radioGroup.setOnCheckedChangeListener(null);
if (answers[position] == null) {
holder.radioGroup.clearCheck();
} else if (answers[position].equals("A")) {
holder.radioGroup.check(R.id.radioButton);
} else if (answers[position].equals("B")) {
holder.radioGroup.check(R.id.radioButton2);
} else if (answers[position].equals("C")) {
holder.radioGroup.check(R.id.radioButton3);
} else if (answers[position].equals("D")) {
holder.radioGroup.check(R.id.radioButton4);
}
holder.radioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
int adapterPosition = holder.getAdapterPosition();
if (adapterPosition != RecyclerView.NO_POSITION) {
if (i == R.id.radioButton) {
answers[adapterPosition] = "A";
} else if (i == R.id.radioButton2) {
answers[adapterPosition] = "B";
} else if (i == R.id.radioButton3) {
answers[adapterPosition] = "C";
} else if (i == R.id.radioButton4) {
answers[adapterPosition] = "D";
} else if (i == R.id.radioButton5) {
holder.radioGroup.clearCheck();
answers[adapterPosition] = null;
}
popGrid.notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return data.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView questionText;
private RadioGroup radioGroup;
private RadioButton r1, r2, r3, r4, r5;
private ImageView questionImageView; // ImageView to display question image
ViewHolder(View itemView) {
super(itemView);
questionText = itemView.findViewById(R.id.questionTextView);
radioGroup = itemView.findViewById(R.id.radioGroup);
r1 = itemView.findViewById(R.id.radioButton);
r2 = itemView.findViewById(R.id.radioButton2);
r3 = itemView.findViewById(R.id.radioButton3);
r4 = itemView.findViewById(R.id.radioButton4);
r5 = itemView.findViewById(R.id.radioButton5);
questionImageView = itemView.findViewById(R.id.questionImageView);
}
}
}
class popGridAdapter extends BaseAdapter {
Context mContext;
popGridAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
return questions.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
View convertView = view != null ? view : new Button(mContext);
if (answers[i] == null)
convertView.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
else
convertView.setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));
((Button) convertView).setText("" + (i + 1));
convertView.setOnClickListener(v -> scrollView.setCurrentItem(i));
return convertView;
}
}
public void slideUp(View view) {
TranslateAnimation animate = new TranslateAnimation(
0, 0, 0, -view.getHeight());
animate.setDuration(500);
view.startAnimation(animate);
view.setVisibility(View.GONE);
}
public void slideDown(View view) {
view.setVisibility(View.VISIBLE);
TranslateAnimation animate = new TranslateAnimation(
0, 0, -view.getHeight(), 0);
animate.setDuration(500);
view.startAnimation(animate);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
package com.example.myapplication.Attempt_Quiz_Section;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication.R;
import com.example.myapplication.Model.Question;
import com.example.myapplication.Model.Test;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Objects;
public class Tests extends AppCompatActivity {
private FirebaseDatabase database;
private DatabaseReference myRef;
private ProgressBar progressBar;
private ListView listView;
private TestAdapter testAdapter;
private int lastPos = -1;
ArrayList<Test> tests = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tests);
// Update layout file to use ProgressBar instead of AVLoadingIndicatorView
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitleTextColor(getResources().getColor(android.R.color.black));
setSupportActionBar(toolbar);
progressBar = findViewById(R.id.loader1);
progressBar.setVisibility(View.VISIBLE);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar())
.setDisplayHomeAsUpEnabled(true);
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
listView = findViewById(R.id.test_listview);
testAdapter = new TestAdapter(Tests.this, tests);
listView.setAdapter(testAdapter);
getQues();
}
@Override
protected void onRestart() {
super.onRestart();
Toast.makeText(Tests.this, "Finish or submit your test! Before time runs out.", Toast.LENGTH_LONG).show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
public void getQues() {
myRef.child("tests").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
tests.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Test t = new Test();
t.setName(snapshot.getKey());
t.setTime(Long.parseLong(snapshot.child("Time").getValue().toString()));
ArrayList<Question> ques = new ArrayList<>();
for (DataSnapshot qSnap : snapshot.child("Questions").getChildren()) {
ques.add(qSnap.getValue(Question.class));
}
t.setQuestions(ques);
tests.add(t);
}
testAdapter.dataList = tests;
testAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
Log.e("The read success: ", "su" + tests.size());
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
progressBar.setVisibility(View.GONE);
Log.e("The read failed: ", databaseError.getMessage());
}
});
}
class TestAdapter extends ArrayAdapter<Test> implements Filterable {
private Context mContext;
ArrayList<Test> dataList;
public TestAdapter(Context context, ArrayList<Test> list) {
super(context, 0, list);
mContext = context;
dataList = list;
}
@SuppressLint("SetTextI18n")
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItem = convertView;
if (listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.test_item, parent, false);
((ImageView) listItem.findViewById(R.id.item_imageView))
.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_appicon));
((TextView) listItem.findViewById(R.id.item_textView))
.setText(dataList.get(position).getName() + " : " + dataList.get(position).getTime() + "Min");
((Button) listItem.findViewById(R.id.item_button)).setText("Attempt");
listItem.findViewById(R.id.item_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mContext, AttemptTest.class);
intent.putExtra("Questions", dataList.get(position));
intent.putExtra("TESTNAME", dataList.get(position).getName());
startActivity(intent);
}
});
Animation animation = AnimationUtils.loadAnimation(getContext(),
(position > lastPos) ? R.anim.up_from_bottom : R.anim.down_from_top);
listItem.startAnimation(animation);
lastPos = position;
return listItem;
}
}
<!-- Include the main content -->
<include
android:id="@+id/content_create_quiz"
layout="@layout/content_create_quiz" />
<!-- "Next" button -->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom">
<androidx.cardview.widget.CardView
android:id="@+id/nextfab"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_margin="20dp"
app:cardCornerRadius="5dp"
app:cardElevation="10dp"
app:cardBackgroundColor="@color/colorPrimaryDark">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="Далее"
android:textColor="@android:color/white"/>
</androidx.cardview.widget.CardView>
</RelativeLayout>
<!-- "Previous" button -->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|bottom">
<androidx.cardview.widget.CardView
android:id="@+id/pre_card"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:visibility="invisible"
app:cardCornerRadius="5dp"
app:cardElevation="10dp"
app:cardBackgroundColor="@color/colorPrimaryDark">
<TextView
android:id="@+id/prevTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="Предыдущий"
android:textColor="@android:color/white"/>
</androidx.cardview.widget.CardView>
</RelativeLayout>
<!-- "Save" button -->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end">
<androidx.cardview.widget.CardView
android:id="@+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
app:cardCornerRadius="5dp"
app:cardElevation="10dp"
app:cardBackgroundColor="@color/colorPrimaryDark">
<TextView
android:id="@+id/saveTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="Сохранить"
android:textColor="@android:color/white"/>
</androidx.cardview.widget.CardView>
</RelativeLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/Theme.MyApplication.AppBarOverlay"
android:id="@+id/tooltst">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbartst"
app:navigationIcon="@drawable/ic_keyboard_arrow_left_black_24dp"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="?android:attr/colorPrimary"
app:popupTheme="@style/Theme.MyApplication.PopupOverlay">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<RelativeLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="20dp">
<Button
android:id="@+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:textColor="@android:color/white"
android:background="@drawable/button_circular"
android:elevation="4dp"
android:paddingHorizontal="20dp"
android:paddingVertical="10dp" />
</RelativeLayout>
<ListView
android:id="@+id/test_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?android:attr/actionBarSize"
android:padding="16dp"
android:layout_above="@id/add_button"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<TextView
android:text="questions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/questionTextView"
android:fontFamily="@font/lato_black"
android:textStyle="bold"
android:textSize="28sp"
android:textColor="#eb346e"
android:paddingStart="10dp"
android:layout_gravity="start"
android:paddingBottom="10dp"/>
<ImageView
android:id="@+id/questionImageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:visibility="gone"
android:layout_marginBottom="10dp"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|center_vertical"
android:layout_marginStart="20dp"
android:scrollbarSize="20dp"
android:gravity="center"
android:id="@+id/radioGroup">
<RadioButton
android:text="Rb1"
android:textSize="20sp"
android:layout_width="match_parent"
android:fontFamily="@font/lato_black"
android:layout_height="wrap_content"
android:id="@+id/radioButton"
android:paddingBottom="10dp">
</RadioButton>
<RadioButton
android:textSize="20sp"
android:text="Rb2"
android:fontFamily="@font/lato_black"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/radioButton2" />
<RadioButton
android:textSize="20sp"
android:text="Rb3"
android:layout_width="match_parent"
android:fontFamily="@font/lato_black"
android:layout_height="wrap_content"
android:id="@+id/radioButton3" />
<RadioButton
android:textSize="20sp"
android:text="Rb4"
android:layout_width="match_parent"
android:fontFamily="@font/lato_black"
android:layout_height="wrap_content"
android:id="@+id/radioButton4" />
<RadioButton
android:textSize="20sp"
android:text="Clear Selection"
android:layout_width="match_parent"
android:fontFamily="@font/lato_black"
android:layout_height="wrap_content"
android:id="@+id/radioButton5" />
</RadioGroup>
<RelativeLayout
android:id="@+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- Заголовок вопроса и номер -->
<LinearLayout
android:id="@+id/questionHeaderLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal"
android:paddingLeft="20dp"
android:paddingRight="20dp">
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Вопрос"
android:textSize="24sp"
android:textStyle="bold"/>
<TextView
android:id="@+id/questionNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="1"
android:textSize="24sp"
android:textStyle="bold"/>
</LinearLayout>
<EditText
android:id="@+id/questionView"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_below="@id/questionHeaderLayout"
android:layout_margin="20dp"
android:gravity="top|start"
android:hint="Введите ваш вопрос здесь"
android:textSize="16sp"/>
<!-- Кнопка для выбора изображения -->
<Button
android:id="@+id/selectImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Выбрать изображение"
android:layout_below="@id/questionView"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"/>
<!-- ImageView для отображения выбранного изображения -->
<ImageView
android:id="@+id/questionImageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_below="@id/selectImageButton"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:visibility="gone"/>
<!-- Группа вариантов (RadioGroup) -->
<RadioGroup
android:id="@+id/optionsGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/questionImageView"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:orientation="vertical">
<!-- Вариант A -->
<LinearLayout
android:id="@+id/optionALayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/aRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A"/>
<EditText
android:id="@+id/aText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:hint="Вариант A"/>
</LinearLayout>
<!-- Вариант B -->
<LinearLayout
android:id="@+id/optionBLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/bRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="B"/>
<EditText
android:id="@+id/bText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:hint="Вариант B"/>
</LinearLayout>
<!-- Вариант C -->
<LinearLayout
android:id="@+id/optionCLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="gone">
<RadioButton
android:id="@+id/cRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C"/>
<EditText
android:id="@+id/cText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:hint="Вариант C"/>
</LinearLayout>
<!-- Вариант D -->
<LinearLayout
android:id="@+id/optionDLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="gone">
<RadioButton
android:id="@+id/dRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="D"/>
<EditText
android:id="@+id/dText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:hint="Вариант D"/>
</LinearLayout>
</RadioGroup>
<!-- Кнопки добавления/удаления вариантов -->
<LinearLayout
android:id="@+id/option_buttons_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/optionsGroup"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:gravity="center_horizontal">
<Button
android:id="@+id/addOptionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Добавить вариант" />
<Button
android:id="@+id/removeOptionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:text="Удалить вариант" />
</LinearLayout>
</RelativeLayout>
<group
android:checkableBehavior="single">
<item
android:id="@+id/nav_test"
android:icon="@drawable/ic_test_icon"
android:font="@font/lato_black"
android:iconTint="@android:color/black"
android:title="Tests" />
<item
android:id="@+id/nav_result"
android:icon="@drawable/ranking"
android:font="@font/lato_black"
android:title="Results" />
<item
android:id="@+id/create_test"
android:icon="@android:drawable/ic_menu_add"
android:font="@font/lato_black"
android:visible="false"
android:title="Create Test"/>
</group>
<item android:title="Account">
<menu>
<item
android:id="@+id/nav_manage_users"
android:icon="@drawable/ic_feedback_black_24dp"
android:font="@font/lato_black"
android:title="Управление пользователями" />
<item
android:id="@+id/nav_respass"
android:icon="@drawable/ic_vpn_key_black_24dp"
android:font="@font/lato_black"
android:title="Сменить пароль" />
<item
android:id="@+id/nav_signout"
android:icon="@drawable/ic_menu_send"
android:font="@font/lato_black"
android:title="Выйти" />
</menu>
</item>
почему то при нажатии на кнопку add в окне создания тестов ничего не происходит напиши полные исправленные коды для этого
It seems like the issue arises because the Add button is either not clickable due to layout problems or there's an exception occurring when trying to start the Custom_quiz activity. Let's address both potential problems step by step.
1. Adjust the Layout to Ensure the Add Button is Clickable
The Add button might not be responding because of how the views are arranged in your content_main_1.xml layout file. Let's rework the layout to ensure the Add button is properly positioned and clickable.
Updated content_main_1.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- AppBarLayout and Toolbar -->
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/Theme.MyApplication.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbartst"
app:navigationIcon="@drawable/ic_keyboard_arrow_left_black_24dp"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="?android:attr/colorPrimary"
app:popupTheme="@style/Theme.MyApplication.PopupOverlay">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<!-- Main content area -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<!-- The 'Add' button -->
<Button
android:id="@+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:textColor="@android:color/white"
android:background="@drawable/button_circular"
android:elevation="4dp"
android:paddingHorizontal="20dp"
android:paddingVertical="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_margin="20dp"/>
<!-- The ListView -->
<ListView
android:id="@+id/test_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:layout_above="@id/add_button"
android:layout_below="@+id/appbar_layout"/>
</RelativeLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Explanation:
We moved the Button above the ListView in the XML to ensure that the ListView can reference the Add button's ID in layout_above.
The Button is anchored to the bottom end of the screen using android:layout_alignParentBottom and android:layout_alignParentEnd.
The ListView fills the space between the AppBarLayout and the Add button.
2. Verify IDs and Inflate Correct Layout in create_quiz_main.java
Ensure that your create_quiz_main.java file is inflating the correct layout and that the IDs match:
// In create_quiz_main.java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Ensure you're using the updated layout file
setContentView(R.layout.content_main_1);
// Initialize Firebase
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
auth = FirebaseAuth.getInstance();
toolbar = findViewById(R.id.toolbartst);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
// Initialize the ListView and adapter
testListView = findViewById(R.id.test_list_view);
adminTests = new ArrayList<>();
testAdapter = new TestAdapter(this, adminTests);
testListView.setAdapter(testAdapter);
// Load the admin's tests
loadAdminTests();
// Initialize "Add" button
addButton = findViewById(R.id.add_button);
// Check if the button is properly found
if (addButton == null) {
Log.e("create_quiz_main", "add_button is null. Check your layout file.");
}
// Set click listener on "Add" button
addButton.setOnClickListener(view -> {
Log.d("create_quiz_main", "Add button clicked");
try {
Intent intent = new Intent(create_quiz_main.this, Custom_quiz.class);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(create_quiz_main.this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
// Set click listener on list items
testListView.setOnItemClickListener((adapterView, view, position, id) -> {
// You can implement editing or viewing of the selected test here
});
}
3. Declare Custom_quiz Activity in AndroidManifest.xml
Ensure that your Custom_quiz activity is declared in your AndroidManifest.xml file:
<application
...>
...
<activity android:name=".Create_Quiz.Custom_quiz" />
...
</application>
4. Check for Exceptions
If you're still experiencing issues, check your Logcat for any exceptions when you click the Add button. Sometimes, if there's an error starting the activity (e.g., due to not being declared in the manifest), it can silently fail.
Also, you can enhance your exception handling to provide more detailed feedback:
addButton.setOnClickListener(view -> {
Log.d("create_quiz_main", "Add button clicked");
try {
Intent intent = new Intent(create_quiz_main.this, Custom_quiz.class);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(create_quiz_main.this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
5. Verify Custom_quiz Activity
Make sure that your Custom_quiz class is correctly defined and doesn't have issues in its onCreate method that might cause it to crash immediately when it's started.
Summary
By adjusting the layout file to ensure the Add button is properly positioned and clickable, verifying that the Custom_quiz activity is declared in the manifest, and checking for any exceptions, you should resolve the issue where nothing happens when the Add button is clicked.
Complete Corrected Codes
Updated content_main_1.xml (As shown above)
Updated create_quiz_main.java (Ensure IDs match and setContentView uses the correct layout)
Updated AndroidManifest.xml (Add Custom_quiz activity declaration)
Once these changes are made, rebuild your application and test clicking the Add button again. It should now navigate you to the Custom_quiz activity where you can proceed to create tests.
Copy first response
Not yet included in a published release.