Я создаю android app
для тестирования, где у меня есть registration
и login
.
Когда пользователь регистрируется, он вводит Name
, Surname
и Username
.
Я сохраняю ваши данные в shared preferences
и показываю их в Домашнем действии.
Когда пользователь выходит из системы, он должен войти в систему для входа в систему. В форме login
пользователь должен ввести только username
.
После проверки подлинности, ваша домашняя активность должна содержать вашу информацию, но вы видите только ее Username
, а Name
и Surname
- нет.
Можете ли вы помочь мне понять, почему он не показывает все ваши данные, когда вы login
?
Активность при входе
public class MainActivity extends AppCompatActivity {
private Button login, registrazione;
private EditText username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button)findViewById(R.id.button2);
registrazione = (Button)findViewById(R.id.button);
username = (EditText)findViewById(R.id.editText5);
if (SharedPref.getInstance(this).isLoggedIn()) {
startActivity(new Intent(this, Home.class));
finish();
}
registrazione.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),RegisterR.class);
startActivity(intent);
}
});
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
validateUserData();
}
});
}
private void validateUserData() {
//first getting the values
final String user_username = username.getText().toString();
//checking if username is empty
if (TextUtils.isEmpty(user_username)) {
username.setError("Please enter your username");
username.requestFocus();
// Vibrate for 100 milliseconds
login.setEnabled(true);
return;
}
//checking if password is empty
//Login User if everything is fine
loginUser(user_username);
}
private void loginUser(String username) {
//making api call
Api api = ApiClient.getClient().create(Api.class);
Call<Model> login = api.login(username);
login.enqueue(new Callback<Model>() {
@Override
public void onResponse(Call<Model> call, Response<Model> response) {
if(response.body().getIsSuccess() == 1){
String user = response.body().getUsername();
String user1 = response.body().getName();
String user2 = response.body().getSurname();
//storing the user in shared preferences
SharedPref.getInstance(MainActivity.this).storeUserName(user,user1,user2);
startActivity(new Intent(MainActivity.this,Home.class));
}else{
Toast.makeText(MainActivity.this,response.body().getMessage(),Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<Model> call, Throwable t) {
Toast.makeText(MainActivity.this,t.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
Домашняя активность
public class Home extends AppCompatActivity {
private TextView nome,cognome,username;
private Button logout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
nome = (TextView)findViewById(R.id.textView);
cognome = (TextView)findViewById(R.id.textView2);
username = (TextView)findViewById(R.id.textView3);
String loggedUsername = SharedPref.getInstance(this).LoggedInUser();
username.setText("Username : "+loggedUsername);
String loggedUsername1 = SharedPref.getInstance(this).LoggedInUser1();
nome.setText("Name : "+loggedUsername1);
String loggedUsername2 = SharedPref.getInstance(this).LoggedInUser2();
cognome.setText("Name : "+loggedUsername2);
logout = (Button)findViewById(R.id.button4);
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
SharedPref.getInstance(getApplicationContext()).logout();
}
});
}
}
SharedPref Activity
public class SharedPref {
//Storage File
public static final String SHARED_PREF_NAME = "larnmktech";
//Username
public static final String USER_NAME = "username";
public static final String NAME = "name";
public static final String SURNAME = "surname";
public static SharedPref mInstance;
public static Context mCtx;
public SharedPref(Context context) {
mCtx = context;
}
public static synchronized SharedPref getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPref(context);
}
return mInstance;
}
//method to store user data
public void storeUserName(String names, String names1, String names2) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(USER_NAME, names);
editor.putString(NAME, names1);
editor.putString(SURNAME, names2);
editor.apply();
}
//check if user is logged in
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(USER_NAME, null) != null;
}
//find logged in user
public String LoggedInUser() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(USER_NAME, null);
}
public String LoggedInUser1() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(NAME, null);
}
public String LoggedInUser2() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(SURNAME, null);
}
//Logout user
public void logout() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
mCtx.startActivity(new Intent(mCtx, MainActivity.class));
}
}
Модель деятельности
public class Model {
private String name;
private String surname;
private String username;
private int isSuccess;
private String message;
public Model(String name, String surname, String username, int isSuccess, String message) {
this.name = name;
this.surname = surname;
this.username = username;
this.isSuccess = isSuccess;
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getIsSuccess() {
return isSuccess;
}
public void setIsSuccess(int isSuccess) {
this.isSuccess = isSuccess;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Активность API
@POST("l.php")
@FormUrlEncoded
Call<Model> login(@Field("username") String username);
login.php
<?php
//getting user values
$username=$_POST['username'];
//an array of response
$output = array();
//requires database connection
require_once('db.php');
//checking if email exit
$conn=$dbh->prepare("SELECT username FROM utenti WHERE username=?");
$conn->bindParam(1,$username);
$conn->execute();
if($conn->rowCount() == 0){
$output['isSuccess'] = 0;
$output['message'] = "Username sbagliato";
}
//get the username
if($conn->rowCount() !==0){
$results=$conn->fetch(PDO::FETCH_OBJ);
//we get both the username and password
$username=$results->username;
$output['isSuccess'] = 1;
$output['message'] = "login sucessful";
$output['username'] = $username;
}
echo json_encode($output);
?>
Если бы кто-нибудь мог мне помочь, я бы с удовольствием выслушал.
Спасибо.