这里我初始化在btnlog onclick
之后获取用户输入的值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();
}
});
现在我想从公共类接收用户输入并对其进行编码,变量u和p基本上没有从公共类中获取任何值
@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();
答案 0 :(得分:0)
在onCreate()之外定义u和p并将其声明为public。现在您可以通过
从其他类访问这些变量 this.p=MainActivity.p;
this.u=MainActivity.u;
答案 1 :(得分:0)
我的java不是很流畅但看起来你试图将变量传递给asynctask,如果是这样的话那么看看这里, How to pass variables in and out of AsyncTasks? 它显示了如何在.execute()调用
上传递变量答案 2 :(得分:0)
您可以使用.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()
@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();