我使用以下代码从服务器获取数据,如果服务器的值是 GEEK
,那么它将加载到下一个类,但新视图不加载 . 你能说出什么问题吗?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
login = (Button) findViewById(R.id.login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String Re;
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
Re=tryLogin(mUsername, mPassword);
if(Re=="GEEK")
{
Intent i = new Intent();
i.setClassName(v.getContext(),"com.httplogin.MainScreen");
startActivity(i);
}
}
});
}
protected String tryLogin(String mUsername, String mPassword)
{
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "username="+mUsername+"&password="+mPassword;
try
{
url = new URL("http://serverspace/script.php");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
isr.close();
reader.close();
}
catch(IOException e)
{
Toast.makeText(this,e.toString(),0).show();
}
return response;
}
}
3 回答
关于代码的一个重要注意事项是,您永远不应该从UI线程运行长时间操作,例如远程服务器访问(在您的情况下为tryLogin()调用) . 这种编程将导致您的应用程序中出现ANR . 有关此主题的更多详细信息,请阅读this article
简而言之,不是从onCreate调用tryLogin,而是创建异步任务
登录任务应该像这样定义:
请参考此代码..............,使用trim函数,因为它消除了String中的空间 .
是否区分大小写?在比较不重要的字符串和.equals()时,你应该使用.equalsIgnoreCase() . 您是否已逐步完成并调试以确保
tryLogin(mUsername, mPassword)
返回预期值?