GPT-3.5 Chatbot
This app provides you full access to GPT-3.5 (4096 token limit). You don't need any OPENAI API key.
Chatbot
Доделай профиль а также сделай его вызов в четвертом пункте нижнего меню , помни что данные профиля должны обновляться после каждой авторизации, а также для каждого пункта профиля где должны быть все данные о пользователе , должна быть возможность изменить эти данные (все это должно сохраняться после перезагрузки приложения) :package com.example.myapp_2.Data.register;



public class LoginFragment extends Fragment {

private EditText editTextEmail, editTextPassword;
private Button buttonLogin;

private UserDAO userDAO;

public LoginFragment() {

}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

userDAO = new UserDAO(getActivity());
userDAO.open();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.login, container, false);

getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.GONE);
editTextEmail = view.findViewById(R.id.editTextEmail);
editTextPassword = view.findViewById(R.id.editTextPassword);
buttonLogin = view.findViewById(R.id.buttonLogin);

buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();

if (userDAO.login(email, password)) {
Toast.makeText(getActivity(), “Login successful”, Toast.LENGTH_SHORT).show();

// переход на другой фрагмент
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
} else {
Toast.makeText(getActivity(), “Invalid email or password”, Toast.LENGTH_SHORT).show();
}
}
});
Button buttonReturn = view.findViewById(R.id.buttonReturn);

buttonReturn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new RegistrationFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});

return view;
}

@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
}
package com.example.myapp_2.Data.register;

i

import java.util.List;

public class RegistrationFragment extends Fragment {

private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonRegister_1;

private UserDAO userDAO;

public RegistrationFragment() {

}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

userDAO = new UserDAO(getActivity());
userDAO.open();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.refister, container, false);

getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.GONE);
editTextName = view.findViewById(R.id.editTextName);
editTextEmail = view.findViewById(R.id.editTextEmail);
editTextPassword = view.findViewById(R.id.editTextPassword);
buttonRegister_1 = view.findViewById(R.id.buttonRegister_1);

buttonRegister_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();

long rowID = userDAO.register(name, email, password);

if (rowID > 0) {
Toast.makeText(getActivity(), “Registration successful”, Toast.LENGTH_SHORT).show();

// вывод всех пользователей в лог
List<User> users = userDAO.getAllUsers();
Log.d(“UserDatabase”, “All users:”);
for (User user : users) {
Log.d(“UserDatabase”, user.toString());
}

getFragmentManager().popBackStack();
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
} else if (rowID == -1) {
Toast.makeText(getActivity(), “Invalid email”, Toast.LENGTH_SHORT).show();

} else {
Toast.makeText(getActivity(), “Registration failed”, Toast.LENGTH_SHORT).show();
}
}
});
Button buttonLogin_1 = view.findViewById(R.id.buttonLogin_1);

buttonLogin_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new LoginFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
Button buttonExit = view.findViewById(R.id.buttonExit);

buttonExit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

getFragmentManager().popBackStack();
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});


return view;
}

@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
}

package com.example.myapp_2.Data.register;


public class UserDAO {

private SQLiteDatabase database;
private UserDatabaseHelper dbHelper;

public UserDAO(Context context) {
dbHelper = new UserDatabaseHelper(context);
}

public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}

public void close() {
dbHelper.close();
}

public long register(String name, String email, String password) {
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
return -1; // email не соответствует формату
}

Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_EMAIL},
UserDatabaseHelper.COLUMN_EMAIL + " = ?“,
new String[]{email}, null, null, null, null);

if (cursor != null && cursor.getCount() > 0) { // если уже есть пользователь с такой почтой
cursor.close();
return -2;
}

ContentValues values = new ContentValues();
values.put(UserDatabaseHelper.COLUMN_NAME, name);
values.put(UserDatabaseHelper.COLUMN_EMAIL, email);
values.put(UserDatabaseHelper.COLUMN_PASSWORD, password);

return database.insert(UserDatabaseHelper.TABLE_USERS, null, values);
}

public boolean login(String email, String password) {
Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD},
UserDatabaseHelper.COLUMN_EMAIL + " = ? AND " + UserDatabaseHelper.COLUMN_PASSWORD + " = ?”,
new String[]{email, password}, null, null, null, null);

if (cursor != null && cursor.getCount() > 0) {
cursor.close();
return true;
} else {
return false;
}
}

@SuppressLint(“Range”)
public List<User> getAllUsers() {
List<User> users = new ArrayList<>();

Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_ID, UserDatabaseHelper.COLUMN_NAME,
UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD},
null, null, null, null, null);

if (cursor != null && cursor.moveToFirst()) {
do {
User user = new User();
user.setId(cursor.getInt(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_ID)));
user.setName(cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_NAME)));
user.setEmail(cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_EMAIL)));
user.setPassword(cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_PASSWORD)));

users.add(user);
} while (cursor.moveToNext());

cursor.close();
}

return users;
}
public User getUserById(int id) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_ID, UserDatabaseHelper.COLUMN_NAME, UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD},
UserDatabaseHelper.COLUMN_ID + “= ?”, new String[]{String.valueOf(id)},
null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

@SuppressLint(“Range”) User user = new User(cursor.getInt(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_NAME)),
cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_EMAIL)),
cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_PASSWORD)));

cursor.close();
return user;
}
public void updateUser(User user) {
ContentValues values = new ContentValues();
values.put(UserDatabaseHelper.COLUMN_NAME, user.getName());
values.put(UserDatabaseHelper.COLUMN_EMAIL, user.getEmail());
values.put(UserDatabaseHelper.COLUMN_PASSWORD, user.getPassword());

database.update(UserDatabaseHelper.TABLE_USERS, values,
UserDatabaseHelper.COLUMN_ID + " = ?“,
new String[]{String.valueOf(user.getId())});
}
}
package com.example.myapp_2.Data.register;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class UserDatabaseHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = “UserDatabase”;

public static final String TABLE_USERS = “users”;
public static final String COLUMN_ID = “_id”;
public static final String COLUMN_NAME = “name”;
public static final String COLUMN_EMAIL = “email”;
public static final String COLUMN_PASSWORD = “password”;

public UserDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USERS_TABLE = “CREATE TABLE " + TABLE_USERS + “(”
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,”
+ COLUMN_NAME + " TEXT,”
+ COLUMN_EMAIL + " TEXT,“
+ COLUMN_PASSWORD + " TEXT”
+ “)”;
db.execSQL(CREATE_USERS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
onCreate(db);
}
}package com.example.myapp_2.UI.view.activities;




public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private NoteViewModel noteViewModel;

private BroadcastReceiver broadcastReceiver;

static boolean isRegister = false;
Button button1;
Button button3;
// private FirstFragment firstFragment = new FirstFragment();
ActivityMainBinding binding;
private Button btn_fragment1,btn_fragment2,btn_fragment3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
replaceFragment(new FirstFragment());

binding.bottomNavigationView.setOnItemSelectedListener(item -> {
switch(item.getItemId()){
case R.id.home:

replaceFragment(new FirstFragment());
break;
case R.id.profile:
replaceFragment(new SecondFragment());
break;
case R.id.settings:
replaceFragment(new ThirdFragment());
break;
case R.id.menu_profile:
replaceFragment(new ProfileFragment());
break;

}
return true;
});

getSupportFragmentManager().beginTransaction().replace(R.id.nav_container, new FirstFragment()).addToBackStack(null).commit();

if (isRegister) {
binding.bottomNavigationView.setVisibility(View.GONE);
} else {
binding.bottomNavigationView.setVisibility(View.VISIBLE);
}
}

private void registerBroadcastReceiver() {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Получение сообщения
String action = intent.getAction();
if(action.equals(“com.example.myapplication_2.SEND_MESSAGE”)) {
String message = intent.getStringExtra(“MESSAGE”);
// Вывод сообщения в лог
Log.d(“MyApp2”, "Received message: " + message);
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(“com.example.myapplication_2.SEND_MESSAGE”);
registerReceiver(broadcastReceiver, intentFilter);
}


@Override
public void onClick(View view) {//2 способ

}
@Override
protected void onDestroy() {
super.onDestroy();
// Удаление приемника
unregisterReceiver(broadcastReceiver);
}

private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_container,fragment);
String A = “HELLO”;


Bundle bundle = new Bundle();
bundle.putInt(“hello world”, 4344);
fragment.setArguments(bundle);


fragmentTransaction.commit();

}

// вызов фрагмента регистрации с передачей кода запроса

public void startRegistration() {
isRegister = true;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.nav_container, new RegistrationFragment()).addToBackStack(null).commit();
}

// обработка полученного результата (кода запроса)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
isRegister = true; // установка значения переменной isRegister в true
}
}

}
package com.example.myapp_2.Data.register;

i
import com.example.myapp_2.R;

public class ProfileFragment extends Fragment {

private UserDAO userDAO;
private int userId = 1;
private User user;

private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonUpdate;

public ProfileFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

userDAO = new UserDAO(getActivity());
userDAO.open();

// получение текущего пользователя из базы данных
user = userDAO.getUserById(userId);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_profile, container, false);

getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.VISIBLE);

// отображение имени текущего пользователя
TextView textViewName = view.findViewById(R.id.textViewName);
textViewName.setText(user.getName());

editTextName = view.findViewById(R.id.editTextName);
editTextEmail = view.findViewById(R.id.editTextEmail);
editTextPassword = view.findViewById(R.id.editTextPassword);

// отображение данных текущего пользователя в editText
editTextName.setText(user.getName());
editTextEmail.setText(user.getEmail());
editTextPassword.setText(user.getPassword());

buttonUpdate = view.findViewById(R.id.buttonUpdate);
buttonUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateUser();
}
});

return view;
}

// метод обновления данных пользователя
private void updateUser() {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();

// обновление данных пользователя в базе данных
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userDAO.updateUser(user);

Toast.makeText(getActivity(), “User updated”, Toast.LENGTH_SHORT).show();
}

@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
}
продолжай
Ниже приведены изменения в классе MainActivity для вызова фрагмента профиля из нижнего меню, а также для обработки возвращаемых значений:

package com.example.myapp_2.UI.view.activities;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private NoteViewModel noteViewModel;

private BroadcastReceiver broadcastReceiver;

static boolean isRegister = false;
Button button1;
Button button3;
// private FirstFragment firstFragment = new FirstFragment();
ActivityMainBinding binding;
private Button btn_fragment1,btn_fragment2,btn_fragment3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
replaceFragment(new FirstFragment());

binding.bottomNavigationView.setOnItemSelectedListener(item -> {
switch(item.getItemId()){
case R.id.home:

replaceFragment(new FirstFragment());
break;
case R.id.profile:
replaceFragment(new SecondFragment());
break;
case R.id.settings:
replaceFragment(new ThirdFragment());
break;
case R.id.menu_profile:
replaceFragment(new ProfileFragment());
break;

}
return true;
});

getSupportFragmentManager().beginTransaction().replace(R.id.nav_container, new FirstFragment()).addToBackStack(null).commit();

if (isRegister) {
binding.bottomNavigationView.setVisibility(View.GONE);
} else {
binding.bottomNavigationView.setVisibility(View.VISIBLE);
}

// получение данных пользователя при каждой авторизации
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey(“user_id”)) {
int userId = getIntent().getExtras().getInt(“user_id”);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new ProfileFragment());
transaction.addToBackStack(null);
transaction.commit();
}
}
}

private void register
BroadcastReceiver() {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Получение сообщения
String action = intent.getAction();
if(action.equals(“com.example.myapplication_2.SEND_MESSAGE”)) {
String message = intent.getStringExtra(“MESSAGE”);
// Вывод сообщения в лог
Log.d(“MyApp2”, "Received message: " + message);
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(“com.example.myapplication_2.SEND_MESSAGE”);
registerReceiver(broadcastReceiver, intentFilter);
}


@Override
public void onClick(View view) {//2 способ

}
@Override
protected void onDestroy() {
super.onDestroy();
// Удаление приемника
unregisterReceiver(broadcastReceiver);
}

private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_container,fragment);
String A = “HELLO”;


Bundle bundle = new Bundle();
bundle.putInt(“hello world”, 4344);
fragment.setArguments(bundle);


fragmentTransaction.commit();

}

// вызов фрагмента регистрации с передачей кода запроса

public void startRegistration() {
isRegister = true;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.nav_container, new RegistrationFragment()).addToBackStack(null).commit();
}

// обработка полученного результата (кода запроса)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
isRegister = true; // установка значения переменной
isRegister в true
}
// обновление данных пользователя после закрытия фрагмента профиля
if (requestCode == 2) {
if (data != null && data.getBooleanExtra(“profile_updated”, false)) {
// получение текущего пользователя из базы данных
UserDAO userDAO = new UserDAO(this);
userDAO.open();
int userId = data.getIntExtra(“user_id”, 0);
User user = userDAO.getUserById(userId);
userDAO.close();

// обновление отображаемых данных в editText
EditText editTextName = findViewById(R.id.editTextName);
EditText editTextEmail = findViewById(R.id.editTextEmail);
EditText editTextPassword = findViewById(R.id.editTextPassword);
editTextName.setText(user.getName());
editTextEmail.setText(user.getEmail());
editTextPassword.setText(user.getPassword());
}
}
}

}