【问题标题】:Password protecting my app密码保护我的应用程序
【发布时间】:2014-01-22 19:20:35
【问题描述】:

我对 JAVA 和 android 开发非常陌生,正在尝试使用密码保护我的应用程序。 我试图做到这一点,以便每当用户按下提交按钮时,如果密码正确,它将开始一个新的活动。

到目前为止,我有以下代码:

对于我的按钮:

 <Button
          android:id="@+id/button_enterpassword"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/text_enterpassword"
          android:layout_centerHorizontal="true"
          android:layout_marginTop="262dp"
          android:onClick="openMenu"
          android:textSize="60sp"
          android:text="@string/button_confirm"
           />

对于我的活动:

 // This is the method called when the user presses the button 
public void openMenu(View view) {
    MyMethods compareText = new MyMethods();
    boolean same = compareText.compareText();
    if(same = true){ 
    MyMethods openActivity = new MyMethods();
    openActivity.callActivity();
    }
}}

对于我的 MyMethods 类:

 public class MyMethods extends Activity {

public void callActivity() {

     Intent intent = new Intent(this , MainMenu.class);
        startActivity(intent);
}

public boolean compareText() {
    boolean same = false;
    //assigning the name sumbitButton to the button from the UI
    //Button sumbitButton = (Button) findViewById(R.id.button_enterpassword);
    //Defines when the user has selected the button
   // sumbitButton.setOnClickListener(new View.OnClickListener() {        
        //public void onClick(View v){
        //assigning the name passwordEditText to the text inside the textbox
        EditText passwordEditText = (EditText)         

  findViewById(R.id.text_enterpassword);
        if(passwordEditText.getText().toString().equals("Test")){
            same = true;

        }
        return same;
        }

}

但是,每当我按下按钮时,我的程序就会崩溃。

为您的帮助干杯!

【问题讨论】:

  • 您应该发布错误堆栈跟踪以获得更好的答案。

标签: android button crash passwords


【解决方案1】:

有几点需要注意:

  1. MyMethods 正在扩展 Activity,但您使用它的方式是 unorthodox。
  2. 在openMenu()中,你的比较是错误的,你在

    中少了一个=
    if (same = true) { //<---------- should be if (same == true) or if (same)
    
  3. 从 MyMethods 中删除您的 callActivity() 和 compareText(),并在您将使用它们的类中声明它们,即在您有 openMenu() 的类中。我还将 compareText() 重命名为 isPasswordValid(),以使其更清晰。

  4. 将 openMenu() 重写为:

    public void openMenu(View view) {
        if (isPasswordValid()) {
            callActivity();
        }
    }
    
  5. 你也可以重写 compareText():

    public boolean isPasswordValid() {
        EditText passwordEditText = (EditText) findViewById(R.id.text_enterpassword);
    
        return passwordEditText.getText().toString().equals("Test");
    }
    
  6. 另外,由于您要启动另一个活动,请确保它已在 AndroidManifest 中声明。

【讨论】:

  • 非常感谢您的帮助!尤其是关于什么是正统的,什么不是正统的!
猜你喜欢
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
  • 2014-09-01
相关资源
最近更新 更多