Java android studio:如何从另一个类获取变量
在这里,我初始化在btnlogonclick之后获取用户输入的值Java android studio:如何从另一个类获取变量,java,android,Java,Android,在这里,我初始化在btnlogonclick之后获取用户输入的值 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); usernameField = (EditText) findViewById(R.id.etUname); password
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText) findViewById(R.id.etUname);
passwordField = (EditText) findViewById(R.id.etUpass);
btnlog = (Button) findViewById(R.id.loginbtn);
btnview = (Button) findViewById(R.id.viewbtn);
reglink = (TextView) findViewById(R.id.reglink);
btnlog.setOnClickListener (new View.OnClickListener(){
@Override
public void onClick(View v){
String u = usernameField.getText().toString();
String p = passwordField.getText().toString();
new loginPost().execute();
}
});
现在我想从public类接收用户输入并对其进行编码,变量u和p基本上没有从public类获得任何值
@Override
protected String doInBackground(String... params) {
try{
String str = "username=" + u + "&password=" + p;
String data = URLEncoder.encode("str", "UTF-8") + "=" +
URLEncoder.encode(str, "UTF-8");
strUrl ="http://10.0.2.2/android/login.php?"+data+"";
Log.d("STR", data);
URL url = new URL (strUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.connect();
在onCreate()外部定义u和p并将其声明为公共。现在您可以通过以下方式从其他类访问这些变量
this.p=MainActivity.p;
this.u=MainActivity.u;
我的java不是很流利,但看起来您正试图将变量传递给asynctask,如果是这样的话,请看这里,
它显示了如何在.execute()调用中传递变量,您可以在
.execute()
方法中传递变量,因为这就是设计的目的
btnlog.setOnClickListener (new View.OnClickListener(){
@Override
public void onClick(View v){
String u = usernameField.getText().toString();
String p = passwordField.getText().toString();
new loginPost().execute(u,p);
}
});
然后在doInBackground()中
如果我让1班和2班在同一个活动中怎么办?您的答案将返回到此.x=Class.x=this.x,例如?
@Override
protected String doInBackground(String... params) {
try{
String str = "username=" + params[0] + "&password=" + params[1];
String data = URLEncoder.encode("str", "UTF-8") + "=" +
URLEncoder.encode(str, "UTF-8");
strUrl ="http://10.0.2.2/android/login.php?"+data+"";
Log.d("STR", data);
URL url = new URL (strUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.connect();