只是说,我在android proggaming新手,我想做的只是存储电子邮件并通过用户检查支票" checarSessao" CheckBox,并保持记录,如果他关闭应用程序,当他再次打开时,我想自动显示Home而不是再次登录屏幕...
这是我的登录
package complete.lyne.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
public class Login extends AppCompatActivity {
EditText loginEmail, loginSenha;
Button btLogar;
TextView refCadastrar;
String url = "";
String parametro = "";
private Session session;
private CheckBox checkBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
loginEmail = (EditText)findViewById(R.id.loginEmail);
loginSenha = (EditText)findViewById(R.id.loginSenha);
btLogar = (Button)findViewById(R.id.btLogar);
refCadastrar = (TextView)findViewById(R.id.refCadastrar);
checkBox = (CheckBox)findViewById(R.id.checarSessao);
refCadastrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent abreCadastro = new Intent(Login.this, Cadastro.class);
startActivity(abreCadastro);
}
});
checkBox = (CheckBox) findViewById(R.id.checarSessao);
if (!new Session(this).Logado()) {
//user's email and password both are saved in preferences
startActivity(new Intent(Login.this, Home.class));
}
btLogar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String email = loginEmail.getText().toString();
String senha = loginSenha.getText().toString();
if(email.isEmpty() && senha.matches(".*[a-z].*")) {
loginEmail.setError("Insira seu endereço de Email.");
} else if (email.matches(".*[a-z].*") && senha.isEmpty()) {
loginSenha.setError("Insira sua Senha.");
} else if (email.isEmpty() && senha.isEmpty()) {
Toast.makeText(getApplicationContext(), "Nenhum campo pode ficar vazio.", Toast.LENGTH_LONG).show();
} else {
// Casa
url = "http://192.168.1.103/lyne/logar.php";
// Badran
// url = "http://172.16.2.15/lyne/logar.php";
parametro = "email=" + email + "&senha=" + senha;
new SolicitaDados().execute(url);
}
} else {
Toast.makeText(getApplicationContext(), "Nenhuma conexão com a Internet foi encontrada.", Toast.LENGTH_LONG).show();
}
}
});
}
private class SolicitaDados extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return Conexao.postDados(urls[0], parametro);
}
@Override
protected void onPostExecute(String resultado) {
if(resultado != null) {
if (resultado.contains("login_ok")) {
String[] dados = resultado.split(",");
Intent abreHome = new Intent(Login.this, Home.class);
abreHome.putExtra("idusu", dados[0]);
abreHome.putExtra("nomeusu", dados[1]);
abreHome.putExtra("sobreusu", dados[2]);
abreHome.putExtra("emailusu", dados[3]);
abreHome.putExtra("senhausu", dados[4]);
String email = loginEmail.getText().toString();
String password = loginSenha.getText().toString();
if (checkBox.isChecked()) {
salvarLogin(email, password);
startActivity(abreHome);
finish();
}
overridePendingTransition(android.R.anim.fade_out, android.R.anim.fade_in);
startActivity(abreHome);
finish();
} else {
Toast.makeText(getApplicationContext(), "Usuário ou senha incorretos.", Toast.LENGTH_LONG).show();
}
}
}
}
private void salvarLogin(String email, String password) {
new Session(this).salvarLogin(email, password);
}
}
这是我的会议
package complete.lyne.myapplication;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by Higor on 10/08/2017.
*/
public class Session {
Context context;
Session(Context context) {
this.context = context;
}
public void salvarLogin(String email, String senha) {
SharedPreferences sharedPreferences = context.getSharedPreferences("LoginDetails", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Email", email);
editor.putString("Senha", senha);
editor.commit();
}
public String getEmail() {
SharedPreferences sharedPreferences = context.getSharedPreferences("LoginDetails", Context.MODE_PRIVATE);
return sharedPreferences.getString("Email", "");
}
public boolean Logado() {
SharedPreferences sharedPreferences = context.getSharedPreferences("LoginDetails", Context.MODE_PRIVATE);
boolean isEmailEmpty = sharedPreferences.getString("Email", "").isEmpty();
boolean isPasswordEmpty = sharedPreferences.getString("Password", "").isEmpty();
return isEmailEmpty || isPasswordEmpty;
}
}
和我的家
package complete.lyne.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Layout;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import static complete.lyne.myapplication.R.layout.header_navegacao;
public class Home extends AppCompatActivity {
// Fragmentos
FragmentTransaction fragmentTransaction;
NavigationView navigationView;
// Fim dos Fragmentos
TextView bdNome;
String uNome;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle aToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Home.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
drawerLayout = (DrawerLayout)findViewById(R.id.DrawerLayout);
aToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.abrir, R.string.fechar);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
View header = navigationView.getHeaderView(0);
bdNome = (TextView) header.findViewById(R.id.bdNome);
uNome = getIntent().getExtras().getString("nomeusu");
bdNome.setText(uNome);
drawerLayout.addDrawerListener(aToggle);
aToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Fragmentos
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container,new HomeFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Line");
navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.mConta:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.main_container,new ContaFragment());
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
getSupportActionBar().setTitle("Minha Conta");
item.setChecked(true);
drawerLayout.closeDrawers();
break;
case R.id.mPerfil:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.main_container,new PerfilFragment());
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
getSupportActionBar().setTitle("Perfil");
item.setChecked(true);
drawerLayout.closeDrawers();
break;
case R.id.mAmigos:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.main_container,new AmigosFragment());
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
getSupportActionBar().setTitle("Amigos");
item.setChecked(true);
drawerLayout.closeDrawers();
break;
case R.id.mSobre:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.main_container,new SobreFragment());
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
getSupportActionBar().setTitle("Sobre");
item.setChecked(true);
drawerLayout.closeDrawers();
break;
case R.id.mSair:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.main_container,new SobreFragment());
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
item.setChecked(true);
drawerLayout.closeDrawers();
break;
}
return true;
}
});
// Fim Fragmentos
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(aToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void onBackPressed() {
DrawerLayout layout = (DrawerLayout)findViewById(R.id.DrawerLayout);
Home.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
if (layout.isDrawerOpen(GravityCompat.START)) {
layout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
解
登录
package complete.lyne.myapplication;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
public class Login extends AppCompatActivity {
EditText loginEmail, loginSenha;
Button btLogar;
TextView refCadastrar;
String url = "";
String parametro = "";
private CheckBox checkBox;
public static final String info_usuario = "info_usuario";
public static final String email = "email";
public static final String senha = "senha";
public static final String nomeusu = "nomeusu";
public static final boolean isLogin = Boolean.parseBoolean("islogin");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
loginEmail = (EditText) findViewById(R.id.loginEmail);
loginSenha = (EditText) findViewById(R.id.loginSenha);
btLogar = (Button) findViewById(R.id.btLogar);
refCadastrar = (TextView) findViewById(R.id.refCadastrar);
checkBox = (CheckBox) findViewById(R.id.checarSessao);
SharedPreferences sharedPref;
sharedPref = getSharedPreferences("info_usuario", Context.MODE_PRIVATE);
boolean login = sharedPref.getBoolean(String.valueOf(isLogin), false);
if(login){
Intent abreHome = new Intent(Login.this, Home.class);
startActivity(abreHome);
}
refCadastrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent abreCadastro = new Intent(Login.this, Cadastro.class);
startActivity(abreCadastro);
}
});
btLogar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String email = loginEmail.getText().toString();
String senha = loginSenha.getText().toString();
if (email.isEmpty() && senha.matches(".*[a-z].*")) {
loginEmail.setError("Insira seu endereço de Email.");
} else if (email.matches(".*[a-z].*") && senha.isEmpty()) {
loginSenha.setError("Insira sua Senha.");
} else if (email.isEmpty() && senha.isEmpty()) {
Toast.makeText(getApplicationContext(), "Nenhum campo pode ficar vazio.", Toast.LENGTH_LONG).show();
} else {
// Casa
url = "http://192.168.1.103/lyne/logar.php";
// Badran
// url = "http://172.16.2.15/lyne/logar.php";
parametro = "email=" + email + "&senha=" + senha;
new SolicitaDados().execute(url);
}
} else {
Toast.makeText(getApplicationContext(), "Nenhuma conexão com a Internet foi encontrada.", Toast.LENGTH_LONG).show();
}
}
});
}
private class SolicitaDados extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return Conexao.postDados(urls[0], parametro);
}
@Override
protected void onPostExecute(String resultado) {
if (resultado != null) {
if (resultado.contains("login_ok")) {
String[] dados = resultado.split(",");
Intent abreHome = new Intent(Login.this, Home.class);
abreHome.putExtra("idusu", dados[0]);
abreHome.putExtra("nomeusu", dados[1]);
abreHome.putExtra("sobreusu", dados[2]);
abreHome.putExtra("emailusu", dados[3]);
abreHome.putExtra("senhausu", dados[4]);
if (checkBox.isChecked()) {
SharedPreferences sharedPref = getSharedPreferences("info_usuario", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(email, loginEmail.getText().toString());
editor.putString(senha, loginSenha.getText().toString());
editor.putString(nomeusu, "Higor");
editor.putBoolean(String.valueOf(isLogin), true);
editor.commit();
editor.apply();
Toast.makeText(getApplicationContext(), "Esta marcado.", Toast.LENGTH_LONG).show();
startActivity(abreHome);
finish();
}
overridePendingTransition(android.R.anim.fade_out, android.R.anim.fade_in);
startActivity(abreHome);
finish();
} else {
Toast.makeText(getApplicationContext(), "Usuário ou senha incorretos.", Toast.LENGTH_LONG).show();
}
}
}
}
public class Global extends Application {
@Override
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String recentSearches = sharedPreferences.getString("email", "");
if (recentSearches.isEmpty()) {
Intent intent = new Intent(getApplicationContext(), Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
}
答案 0 :(得分:0)
使用以下代码;
用于存储值;
SharedPreferences sp=getSharedPreferences("Login", Context.MODE_PRIVATE);
SharedPreferences.Editor Ed=sp.edit();
Ed.putString("id",login_id.getText().toString() );
Ed.putString("password",login_password.getText().toString() );
Ed.commit();
获取价值;
SharedPreferences sharedPreferences = getSharedPreferences("Login", MODE_PRIVATE);
String uName = sharedPreferences.getString("id", "");
String password = sharedPreferences.getString("password", "");
答案 1 :(得分:0)
如果你想检查它,只有每次应用程序启动时第一次更好地进行普通课程。 你可以这样做:(这个类每个应用程序启动运行一次)
public class Global extends Application {
@Override
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String email = sharedPreferences.getString("email", "");
if(email.isEmpty()){
Intent intent = new Intent(getApplicationContext(), YOUR_ACTIVITY.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
然后你应该在Manifest中注册课程:
<application
android:name=".Global"
android:label="@string/app_name">
<activity android:name="MyActivity"
</activity>
</application>