2016-12-25 4 views
0

У меня есть приложение Android с активностью входа. мое приложение работает отлично, но после того, как я вхожу в систему, и я закрываю приложение, а затем открываю его снова, я всегда должен сначала войти в систему. Я не знаю, как сделать мою программу только логином один раз.Android Войти Активность

Мой код как этот

public class MainActivity extends Activity { 
TextView btnForgot; 
Button btnLogin; 
EditText inputEmail; 
EditText inputPassword; 
private TextView loginErrorMsg; 
private TextView macmac, macmac1; 
private ProgressDialog pDialog; 
private static String KEY_SUCCESS = "success"; 
private static String KEY_UID = "uid"; 
private static String KEY_USERNAME = "uname"; 
private static String KEY_FIRSTNAME = "fname"; 
private static String KEY_LASTNAME = "lname"; 
private static String KEY_EMAIL = "email"; 
private static String KEY_CREATED_AT = "created_at"; 
private static String MAC = "mac_0"; 
JSONParser jParser = new JSONParser(); 
JSONArray products = null; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    btnForgot = (TextView) findViewById(R.id.textView); 
    inputEmail = (EditText) findViewById(R.id.email); 
    inputPassword = (EditText) findViewById(R.id.password); 
    btnLogin = (Button) findViewById(R.id.btnLogin); 
    loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg); 
    TypedValue typedValueColorPrimaryDark = new TypedValue(); 
    MainActivity.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValueColorPrimaryDark, true); 
    final int colorPrimaryDark = typedValueColorPrimaryDark.data; 
    if (Build.VERSION.SDK_INT >= 21) { 
     getWindow().setStatusBarColor(colorPrimaryDark); 
    } 

    /** Button Forgot Password **/ 
    btnForgot.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View view) { 
      Intent myIntent = new Intent(view.getContext(), PasswordResetActivity.class); 
      startActivityForResult(myIntent, 0); 
      finish(); 
     }}); 

    /** Button Login **/ 
    btnLogin.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 
      if ( (!inputEmail.getText().toString().equals("")) && (!inputPassword.getText().toString().equals(""))) 
      { 
       NetAsync(view); 
      } 
      else if ((!inputEmail.getText().toString().equals(""))) 
      { 
       Toast.makeText(getApplicationContext(), "Password field empty", Toast.LENGTH_SHORT).show(); 
      } 
      else if ((!inputPassword.getText().toString().equals(""))) 
      { 
       Toast.makeText(getApplicationContext(), "Email field empty", Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
       Toast.makeText(getApplicationContext(), "Email and Password field are empty", Toast.LENGTH_SHORT).show(); 
      } 
     } 
    }); 
} 

private class NetCheck extends AsyncTask<String,String,Boolean> 
{ 
    private ProgressDialog nDialog; 
    @Override 
    protected void onPreExecute(){ 
     super.onPreExecute(); 
     nDialog = new ProgressDialog(MainActivity.this); 
     nDialog.setTitle("Checking Network"); 
     nDialog.setMessage("Loading.."); 
     nDialog.setIndeterminate(false); 
     nDialog.setCancelable(true); 
     nDialog.show(); 
    } 

    /** Gets current device state and checks for working internet connection by trying Google **/ 
    @Override 
    protected Boolean doInBackground(String... args){ 
     ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
     if (netInfo != null && netInfo.isConnected()) { 
      try { 
       URL url = new URL("http://www.google.com"); 
       HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); 
       urlc.setConnectTimeout(3000); 
       urlc.connect(); 
       if (urlc.getResponseCode() == 200) { 
        return true; 
       } 
      } catch (MalformedURLException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
     return false; 
    } 

    @Override 
    protected void onPostExecute(Boolean th){ 
     if(th == true){ 
      nDialog.dismiss(); 
      new ProcessLogin().execute(); 
     } 
     else{ 
      nDialog.dismiss(); 
      loginErrorMsg.setText("Error in Network Connection"); 
     } 
    } 
} 

/** Async Task to get and send data to My Sql database through JSON respone **/ 
private class ProcessLogin extends AsyncTask<String, String, JSONObject> { 
    private ProgressDialog pDialog; 
    String email,password,mac1; 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     inputEmail = (EditText) findViewById(R.id.email); 
     inputPassword = (EditText) findViewById(R.id.password); 
     email = inputEmail.getText().toString(); 
     password = inputPassword.getText().toString(); 
     //mac1 = macmac.getText().toString(); 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setTitle("Contacting Servers"); 
     pDialog.setMessage("Logging in ..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    @Override 
    protected JSONObject doInBackground(String... args) { 
     UserFunctions userFunction = new UserFunctions(); 
     JSONObject json = userFunction.loginUser(email, password); 
     return json; 
    } 

    @Override 
    protected void onPostExecute(JSONObject json) { 
     try { 
      if (json.getString(KEY_SUCCESS) != null) { 
       String res = json.getString(KEY_SUCCESS); 
       if(Integer.parseInt(res) == 1){ 
        pDialog.setMessage("Loading User Space"); 
        pDialog.setTitle("Getting Data"); 
        DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 
        JSONObject json_user = json.getJSONObject("user"); 
        /** Clear all previous data in SQlite database **/ 
        UserFunctions logout = new UserFunctions(); 
        logout.logoutUser(getApplicationContext()); 
        db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT)); 
        /** If JSON array details are stored in SQlite it launches the User Panel **/ 
        Intent upanel = new Intent(getApplicationContext(), HomeActivity.class); 
        upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        pDialog.dismiss(); 
        new status_login().execute(); 
        startActivity(upanel); 
        /** Close Login Screen **/ 
        finish(); 
       }else{ 
        pDialog.dismiss(); 
        loginErrorMsg.setText("Incorrect username or password"); 
       } 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
public void NetAsync(View view){ 
    new NetCheck().execute(); 
} 
} 

кто-то может помочь мне сделать мое приложение только один раз для входа?

благодаря, прежде чем

ответ

0

Вы должны сохранять значения в пределах общего предпочтения, так что, до тех пор пока данные приложения не будет очищено или не сеанса уничтожен пользователем, пользователь будет зарегистрирован в пределах приложения, и экран Логина будет отображаться только один раз.

0

в вашем сообщении выполните, вы знаете, что ваш пользователь успешно зарегистрировался или нет. поэтому было бы не так уж сложно установить, что логин является истинным, поэтому в другом действии вы можете проверить значение этого общего значения предпочтений и, если оно истинно, тогда он был успешно зарегистрирован в противном случае. так что-то написать следующим образом

// in this method where you find your user either to be logged in or failed 
@Override 
protected void onPostExecute(JSONObject json) { 
     try { 
      if (json.getString(KEY_SUCCESS) != null) { 
      if (login == true) { 
      SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); 
      SharedPreferences.Editor editor = sharedPref.edit(); 
      editor.putBoolean(getString(R.string.login), true); 
      editor.commit(); 
      } 
     } 
} 

и ваш основной проверки деятельности для него, как показано ниже

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); 
boolean login = getResources().getBoolean(R.string.login); 
if (login) { 
// do what you want to do 
} else { 
    // prompt for login again 
} 

узнать больше о SharedPreference

+0

во втором коде может нравится? 'if (login) { Intent upanel = new Intent (getApplicationContext(), HomeActivity.class); startActivity (upanel); finish(); } else { } ' –

+0

ошибка, подобная этому sir http://prntscr.com/dnoduq –

+0

, где вы знаете, что ваш пользователь успешно зарегистрирован, установите общие предпочтения. здесь R.string.login - всего лишь ключ. вам не нужно делать это с помощью строковых ресурсов, но наличие строкового ресурса сделает ваш код понятным и будет меньше конфликтов с вашими ключами, поскольку он получит больше настроек для вашего приложения – xFighter

0

Вы можете использовать SharedPreferences объект для сохранения состояния входа. После того, как пользователь успешно войти в запоминании логического флага, например:

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPref.edit(); 
editor.putBoolean("signed_in", true); 
editor.commit(); 

В следующий раз вы просто проверить это значение.

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
    if (sharedPref.getBoolean("signed_in", false) == true){ 
    //user is login 
    }else{ 
    //user not login 
} 
+0

ошибка в getActivity() sir –

+0

Я обновил код –

0
This is Your Answer 

public class MainActivity extends Activity { 
    TextView btnForgot; 
    Button btnLogin; 
    EditText inputEmail; 
    EditText inputPassword; 
    private TextView loginErrorMsg; 
    private TextView macmac, macmac1; 
    private ProgressDialog pDialog; 
    private static String KEY_SUCCESS = "success"; 
    private static String KEY_UID = "uid"; 
    private static String KEY_USERNAME = "uname"; 
    private static String KEY_FIRSTNAME = "fname"; 
    private static String KEY_LASTNAME = "lname"; 
    private static String KEY_EMAIL = "email"; 
    private static String KEY_CREATED_AT = "created_at"; 
    private static String MAC = "mac_0"; 
    JSONParser jParser = new JSONParser(); 
    JSONArray products = null; 
    SharedPreferences sharedPref; 
    SharedPreferences.Editor editor; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     sharedPref = getSharedPreferences("MysharePrefrence", MODE_PRIVATE); 
     editor = sharedPref.edit(); 
     boolean login = sharedPref.getBoolean("isLogin",false); 

     if (login) 
     { 
      Intent upanel = new Intent(getApplicationContext(), HomeActivity.class); 
      upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(upanel); 
      finish(); 

     } 


     btnForgot = (TextView) findViewById(R.id.textView); 
     inputEmail = (EditText) findViewById(R.id.email); 
     inputPassword = (EditText) findViewById(R.id.password); 
     btnLogin = (Button) findViewById(R.id.btnLogin); 
     loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg); 
     TypedValue typedValueColorPrimaryDark = new TypedValue(); 
     MainActivity.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValueColorPrimaryDark, true); 
     final int colorPrimaryDark = typedValueColorPrimaryDark.data; 
     if (Build.VERSION.SDK_INT >= 21) { 
      getWindow().setStatusBarColor(colorPrimaryDark); 
     } 

     /** Button Forgot Password **/ 
     btnForgot.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View view) { 
       Intent myIntent = new Intent(view.getContext(), PasswordResetActivity.class); 
       startActivityForResult(myIntent, 0); 
       finish(); 
      }}); 

     /** Button Login **/ 
     btnLogin.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View view) { 
       if ( (!inputEmail.getText().toString().equals("")) && (!inputPassword.getText().toString().equals(""))) 
       { 
        NetAsync(view); 
       } 
       else if ((!inputEmail.getText().toString().equals(""))) 
       { 
        Toast.makeText(getApplicationContext(), "Password field empty", Toast.LENGTH_SHORT).show(); 
       } 
       else if ((!inputPassword.getText().toString().equals(""))) 
       { 
        Toast.makeText(getApplicationContext(), "Email field empty", Toast.LENGTH_SHORT).show(); 
       } 
       else 
       { 
        Toast.makeText(getApplicationContext(), "Email and Password field are empty", Toast.LENGTH_SHORT).show(); 
       } 
      } 
     }); 
    } 

    private class NetCheck extends AsyncTask<String,String,Boolean> 
    { 
     private ProgressDialog nDialog; 
     @Override 
     protected void onPreExecute(){ 
      super.onPreExecute(); 
      nDialog = new ProgressDialog(MainActivity.this); 
      nDialog.setTitle("Checking Network"); 
      nDialog.setMessage("Loading.."); 
      nDialog.setIndeterminate(false); 
      nDialog.setCancelable(true); 
      nDialog.show(); 
     } 

     /** Gets current device state and checks for working internet connection by trying Google **/ 
     @Override 
     protected Boolean doInBackground(String... args){ 
      ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
      NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
      if (netInfo != null && netInfo.isConnected()) { 
       try { 
        URL url = new URL("http://www.google.com"); 
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); 
        urlc.setConnectTimeout(3000); 
        urlc.connect(); 
        if (urlc.getResponseCode() == 200) { 
         return true; 
        } 
       } catch (MalformedURLException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
      return false; 
     } 

     @Override 
     protected void onPostExecute(Boolean th){ 
      if(th == true){ 
       nDialog.dismiss(); 
       new ProcessLogin().execute(); 
      } 
      else{ 
       nDialog.dismiss(); 
       loginErrorMsg.setText("Error in Network Connection"); 
      } 
     } 
    } 

    /** Async Task to get and send data to My Sql database through JSON respone **/ 
    private class ProcessLogin extends AsyncTask<String, String, JSONObject> { 
     private ProgressDialog pDialog; 
     String email,password,mac1; 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      inputEmail = (EditText) findViewById(R.id.email); 
      inputPassword = (EditText) findViewById(R.id.password); 
      email = inputEmail.getText().toString(); 
      password = inputPassword.getText().toString(); 
      //mac1 = macmac.getText().toString(); 
      pDialog = new ProgressDialog(MainActivity.this); 
      pDialog.setTitle("Contacting Servers"); 
      pDialog.setMessage("Logging in ..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     @Override 
     protected JSONObject doInBackground(String... args) { 
      UserFunctions userFunction = new UserFunctions(); 
      JSONObject json = userFunction.loginUser(email, password); 
      return json; 
     } 

     @Override 
     protected void onPostExecute(JSONObject json) { 
      try { 
       if (json.getString(KEY_SUCCESS) != null) { 
        String res = json.getString(KEY_SUCCESS); 
        if(Integer.parseInt(res) == 1){ 
         pDialog.setMessage("Loading User Space"); 
         pDialog.setTitle("Getting Data"); 
         DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 
         JSONObject json_user = json.getJSONObject("user"); 
         /** Clear all previous data in SQlite database **/ 
         UserFunctions logout = new UserFunctions(); 
         logout.logoutUser(getApplicationContext()); 
         db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT)); 
         /** If JSON array details are stored in SQlite it launches the User Panel **/ 


         editor.putBoolean("isLogin",true); 
         editor.commit(); 


         Intent upanel = new Intent(getApplicationContext(), HomeActivity.class); 
         upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
         pDialog.dismiss(); 
         new status_login().execute(); 
         startActivity(upanel); 
         /** Close Login Screen **/ 
         finish(); 
        }else{ 
         pDialog.dismiss(); 
         loginErrorMsg.setText("Incorrect username or password"); 
        } 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    public void NetAsync(View view){ 
     new NetCheck().execute(); 
    } 
} 
+0

Надеюсь, это поможет вам – Rishi

+1

Очистите свой SharePreference при выходе из системы – Rishi

+0

Ошибка здесь http://prntscr.com/dnoid7 –

Смежные вопросы