开发者

How to call and run a function from other class

I am beginning Android developer. I am currently experiencing a problem with my class. I used Login.java to separa开发者_如何学Cte function. Below is my code:

public class GTSMobile extends Activity {
@Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.login); 

     Login lg = new Login();
     lg.Chk_Login();

 } 
}
public class Login extends Activity{
public void Chk_Login() {
  Button launch = (Button)findViewById(R.id.login_button);  
  launch.setOnClickListener( new OnClickListener()
        { @Override        
            public void onClick(View viewParam)
             {                    
              EditText usernameEditText = (EditText) findViewById(R.id.txt_username);
              EditText passwordEditText = (EditText) findViewById(R.id.txt_password);             
              String sUserName = usernameEditText.getText().toString();
              String sPassword = passwordEditText.getText().toString();

              if(sUserName.length() == 0 || sPassword.length() == 0){
               ShowOKAlert();
              }else{
               setContentView(R.layout.main);              
              }
            }
  }); // end of launch.setOnclickListener  
 }

 void ShowOKAlert(){
  AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Login Fail");
        alertDialog.setMessage("Please Enter UserName and Password");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int which) {              
           }
        });
        alertDialog.setIcon(R.drawable.icon);
        alertDialog.show();
 }
}


You cannot work with Activities this way. An Activity is something the user "sees". Imagine it as being a screen on the phone. There's always one Activity being shown to the user & you can't just do method calls between them.

Check out this for more information about the Activity lifecycle: http://developer.android.com/reference/android/app/Activity.html

You would start a new Activity using: startActivity(..), not using "new YourActivity(..)"

However, in your code, I see no reason why you would start a new Activity. Just write a method checkLogin(...) in your first Activity.

Hope that helps you.

Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜