我在尝试将 AsyncTask
应用于现有代码时遇到困难。
所以我首先要说的是,我的代码工作正常,直到我升级了目标 SDK,并且收到了以下错误消息:
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133) 处的 android.os.NetworkOnMainThreadException
经过一些研究,看起来这是因为我试图在主线程上运行网络操作,这是一个很大的禁忌。解决办法是使用异步任务来运行网络操作。
好吧,到目前为止对我来说是有意义的,现在我所要做的就是以某种方式在我的代码中实现异步任务,这就是我的问题。
基本上,我有一个登录屏幕,成功登录后会进入主页(有点像 Facebook)。当您单击登录按钮时,它会向我的服务器上的 PHP 文件发送一个 HTTP 请求,该文件验证登录名/密码并发回响应。根据该响应,它会让您登录(或给您一个“无效登录”响应)。
所以我很确定这就是罪魁祸首。现在,我的问题是,如何在异步中运行此任务?我并不是在寻找任何人来编写我的代码或任何东西,我只是在寻找一些关于如何开始的指导。我已经这样做了几天了,我很兴奋:(。
这是我的登录类的代码,您可以在底部看到我的异步:
public class AndroidLogin extends Activity implements OnClickListener {
Button ok,back,exit;
TextView result;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Login button clicked
ok = (Button)findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.tbl_result);
}
public void postLoginData() {
// Add user name and password
EditText uname = (EditText)findViewById(R.id.txt_username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.txt_password);
String password = pword.getText().toString();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
// login.php returns true if username and password match in db
HttpPost httppost = new HttpPost("http://www.alkouri.com/android/login.php?username=" + username + "&password=" + password );
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("SENCIDE", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("SENCIDE", str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("SENCIDE", "TRUE");
result.setText("Login Successful! Please Wait...");
}else
{
Log.w("SENCIDE", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
//when register button is clicked
public void RegisterButton(View view) {
Intent myIntent = new Intent(AndroidLogin.this, Registration.class);
AndroidLogin.this.startActivity(myIntent);
}
protected void onPostExecute(Void v){
// turns the text in the textview "Tbl_result" into a text string called "tblresult"
TextView tblresult = (TextView) findViewById(R.id.tbl_result);
// If "tblresult" text string matches the string "Login Successful! Please Wait..." exactly, it will switch to next activity
if (tblresult.getText().toString().equals("Login Successful! Please Wait...")) {
Intent intent = new Intent();
//take text in the username/password text boxes and put them into an extra and push to next activity
EditText uname2 = (EditText)findViewById(R.id.txt_username);
String username2 = uname2.getText().toString();
EditText pword2 = (EditText)findViewById(R.id.txt_password);
String password2 = pword2.getText().toString();
intent.putExtra("username2", username2 + "&pword=" + password2);
startActivity(intent);
}
}
public void onClick(View view) {
class PostLogingDataTask extends AsyncTask<Void,Void,Void>
{
protected Void doInBackground (Void... t)
{
postLoginData();
return null;
}
}
new PostLogingDataTask ().execute();
}
}
这是我收到的错误:
由以下原因引起:android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建 View 层次结构的原始线程才能触摸其 View 。
最佳答案
public void onClick(View view) {
class PostLogingDataTask extends AsyncTask<Void,Void,Void>
{
protected Void doInBackground (Void... t)
{
postLoginData();
}
protected void onPostExecute(Void v){
// turns the text in the textview "Tbl_result" into a text string called "tblresult"
TextView tblresult = (TextView) findViewById(R.id.tbl_result);
// If "tblresult" text string matches the string "Login Successful! Please Wait..." exactly, it will switch to next activity
if (tblresult.getText().toString().equals("Login Successful! Please Wait...")) {
Intent intent = new Intent(this, Homepage.class);
//take text in the username/password text boxes and put them into an extra and push to next activity
EditText uname2 = (EditText)findViewById(R.id.txt_username);
String username2 = uname2.getText().toString();
EditText pword2 = (EditText)findViewById(R.id.txt_password);
String password2 = pword2.getText().toString();
intent.putExtra("username2", username2 + "&pword=" + password2);
startActivity(intent);
}
}
}
new PostLogingDataTask ().execute();
}
关于java - 如何将异步任务与现有代码一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20930182/