package com.example.me;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.TextView;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button btnLoginButton;
TextView tmpError, tmpUsername, tmpPassword;
ArrayList<NameValuePair> postParameters;
String response;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tmpError = (TextView) findViewById(R.id.lblMessage);
tmpUsername = (TextView) findViewById(R.id.txtUsername);
tmpPassword = (TextView) findViewById(R.id.txtPassword);
addListenerOnButton();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addListenerOnButton() {
btnLoginButton = (Button) findViewById(R.id.btnLogin);
btnLoginButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg) {
try{
triggerClick();
}
catch (Exception e) {
tmpError.setText("[]" + e.toString());
}
}
});
}
private void triggerClick() {
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", tmpUsername.getText().toString()));
postParameters.add(new BasicNameValuePair("password", tmpPassword.getText().toString()));
final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
@Override
protected String doInBackground(String... params) {
publishProgress(true);
try {
response = CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
return response;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void onPostExecute(String result) {
publishProgress(false);
result = result.replaceAll("\\s+","");
if(result.equals("1")) {
tmpError.setText("Correct");
}
else {
tmpError.setText("Sorry!!("+result+")");
}
}
}
new HttpTask().execute();
}
}
使用空的“结果”字符串一次又一次地回来: - (
答案 0 :(得分:1)
因为在doInBackground()
中你返回空字符串,你应该这样做:
protected String doInBackground(String... params) {
publishProgress(true);
try {
return CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
答案 1 :(得分:1)
字符串结果为空,因为您从doInBackground()
返回一个空字符串。
return "";
答案 2 :(得分:1)
请将String response;
声明为全局变量。
protected String doInBackground(String... params)
{
publishProgress(true);
try
{
response=CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
return response;
}
catch (Exception e)
{
e.printStackTrace();
}
}