0 / 0 / 0
Регистрация: 05.03.2024
Сообщений: 1
|
|
|
|
Установка роли при регистрации и авторизации
05.03.2024, 17:27. Показов 438. Ответов 0
Здравствуйте, я совсем новичок в java и пытаюсь сделать регистрацию и авторизацию в приложении с несколькими ролями: в Registration я беру логин и пароль, а в Username я беру роль через radio button и вот проблема в том что авторизовываюсь я под разными ролями, но роль не учитывается при авторизации то есть Userrole = null, роль не закрепляется за аккаунтом в User адаптере.Буду благодарен если сможете помочь если нужно могу добавить xml файлы
| Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
| import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class Authorization extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authorization);
Button startButton = findViewById(R.id.autorization);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TextInputLayout loginLayout = findViewById(R.id.textInputLayout);
String login = loginLayout.getEditText().getText().toString();
TextInputLayout passwordLayout = findViewById(R.id.textInputLayout2);
String password = passwordLayout.getEditText().getText().toString();
SharedPreferences prefs = getSharedPreferences("userData", MODE_PRIVATE);
String usersJson = prefs.getString("users", "[]");
Gson gson = new Gson();
Type userListType = new TypeToken<ArrayList<User>>(){}.getType();
ArrayList<User> users = gson.fromJson(usersJson, userListType);
if (users != null) {
for (User user : users) {
if (user.getLogin().equals(login) && user.getPassword().equals(password)) {
// Авторизация успешна
Toast.makeText(Authorization.this, "Authorization successful", Toast.LENGTH_SHORT).show();
// Здесь можно добавить код для перехода на следующую активити
Intent intent = new Intent(Authorization.this, Main_menu.class);
startActivity(intent);
finish();
return;
}
}
}
// Если авторизация не удалась
Toast.makeText(Authorization.this, "Invalid login or password", Toast.LENGTH_SHORT).show();
}
});
}
} |
|
| Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class Registration extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
Button start = findViewById(R.id.registration);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TextInputLayout loginLayout = findViewById(R.id.textInputLayout3);
String login = loginLayout.getEditText().getText().toString();
TextInputLayout passwordLayout = findViewById(R.id.textInputLayout4);
String password = passwordLayout.getEditText().getText().toString();
String role = "user";
// Создаем объект User и устанавливаем роль
User user = new User(login, password, role);
SharedPreferences prefs = getSharedPreferences("userData", MODE_PRIVATE);
String usersJson = prefs.getString("users", "[]");
Gson gson = new Gson();
Type userListType = new TypeToken<ArrayList<User>>(){}.getType();
ArrayList<User> users = gson.fromJson(usersJson, userListType);
if (users == null) {
users = new ArrayList<>();
}
users.add(user);
SharedPreferences.Editor editor = getSharedPreferences("userData", MODE_PRIVATE).edit();
editor.putString("users", gson.toJson(users));
editor.apply();
Intent intent = new Intent(Registration.this, Username.class);
startActivity(intent);
}
});
}
} |
|
| Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
| import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.google.android.material.textfield.TextInputLayout;
public class Username extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_username);
Button start_2 = findViewById(R.id.regist_button);
start_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Получаем имя, фамилию и отчество из соответствующих полей
TextInputLayout string_firstname_layout = findViewById(R.id.textInputLayout3);
String firstName = string_firstname_layout.getEditText().getText().toString();
TextInputLayout string_lastname_layout = findViewById(R.id.textInputLayout4);
String lastName = string_lastname_layout.getEditText().getText().toString();
TextInputLayout string_middlename_layout = findViewById(R.id.textInputLayout5);
String middleName = string_middlename_layout.getEditText().getText().toString();
// Получаем выбранную роль
RadioGroup radioGroup = findViewById(R.id.radios);
int selectedRadioButtonId = radioGroup.getCheckedRadioButtonId();
RadioButton selectedRadioButton = findViewById(selectedRadioButtonId);
String role = "";
if (selectedRadioButtonId == R.id.radio_Button_1) {
role = "user";
} else if (selectedRadioButtonId == R.id.radio_Button_2) {
role = "employee";
}
// Сохраняем данные в SharedPreferences
SharedPreferences.Editor editor = getSharedPreferences("userData", MODE_PRIVATE).edit();
editor.putString("firstName", firstName);
editor.putString("lastName", lastName);
editor.putString("middleName", middleName);
editor.apply();
// Устанавливаем роль в SharedPreferences "auth"
SharedPreferences.Editor authEditor = getSharedPreferences("auth", MODE_PRIVATE).edit();
authEditor.putString("role", role);
authEditor.apply();
// Создаем Intent для передачи данных в следующую активити
Intent intent = new Intent(Username.this, Registration.class);
startActivity(intent);
}
});
// устанавливаем обработчики для кнопок
findViewById(R.id.radio_Button_1).setOnClickListener((view)->onRadioButtonClicked(view));
findViewById(R.id.radio_Button_2).setOnClickListener((view)->onRadioButtonClicked(view));
}
public void onRadioButtonClicked(View view) {
RadioButton radio = (RadioButton) view;
// если переключатель отмечен
boolean checked = radio.isChecked();
}
} |
|
| Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| public class User {
private String login;
private String password;
private String role;
public User(String login, String password, String role) {
this.login = login;
this.password = password;
this.role = role;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
} |
|
0
|