First things first, I’m a novice in Android and apologize for anything unreasonable.
What I’m trying to do here is to display Main activity and show an AlertDialog, asking for short password (full username and password will be saved in Preferences). I need to find a way to exit the application if the passcode doesn’t match, otherwise, load main activity.
Here is my code so far:
public class MainActivity extends Activity implements OnClickListener
{
Button screening;
Button screeningLog;
@Override
protected void onCreate (Bundle savedInstanceState)
{
resetPreferences ();
// Set theme
setTheme (App.getTheme ());
setContentView (R.layout.main);
super.onCreate (savedInstanceState);
createControlsAndListeners ();
if (!App.isLoggedIn ())
{
final LinearLayout view = new LinearLayout (this);
final TextView passcodeText = new TextView (this);
final EditText passcode = new EditText (this);
passcodeText.setText (R.string.passcode);
passcode.setHint (R.string.passcode_hint);
passcode.setInputType (InputType.TYPE_TEXT_VARIATION_PASSWORD);
view.setOrientation (LinearLayout.VERTICAL);
view.addView (passcodeText);
view.addView (passcode);
AlertDialog.Builder builder = new AlertDialog.Builder (this);
builder.setTitle ("Enter Passcode.");
builder.setView (view);
builder.setPositiveButton (R.string.login, new DialogInterface.OnClickListener ()
{
public void onClick (DialogInterface dialog, int whichButton)
{
if (App.get (passcode).equals (App.getPassword ().substring (0, 4)))
{
App.setLoggedIn (true);
dialog.dismiss ();
}
else
{
Toast toast = Toast.makeText (MainActivity.this, Error.get (Error.AUTHENTICATION),
App.getDelay ());
toast.show ();
}
}
});
builder.show ();
}
}
public void resetPreferences ()
{
PreferenceManager.setDefaultValues (this, R.xml.preferences, false);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences (this);
App.setServer (preferences.getString ("server", ""));
App.setUsername (preferences.getString ("username", ""));
App.setPassword (preferences.getString ("password", ""));
App.setNightMode (preferences.getBoolean ("night_mode", false));
App.setDelay (Integer.parseInt (preferences.getString ("delay", "30000")));
}
private void createControlsAndListeners ()
{
screening = (Button) findViewById (R.main_id.screeningButton);
screening.setOnClickListener (this);
screeningLog = (Button) findViewById (R.main_id.screeningLogButton);
screening.setOnClickListener (this);
}
}
Try this it might help you. You can use the intent for this.
Or
If this is your first activity in app then call
finish()method in else condition.