**編輯:解決**將代碼移動到AsyncTask
我正在測試AsyncTask功能上的示例代碼。但是dobackGround()方法沒有調用代碼。我注意到一些職位的幫助和重構我的代碼,但它仍然是不工作
這是主要佈局
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText1">
</EditText>
<Button
android:text="Get Name"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<TextView
android:text="from Web service"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
MainActivity.java
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
WebServiceActivity.java
public class WebServiceActivity extends Activity implements View.OnClickListener {
Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
new LongOperation().execute("");
break;
}
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.textView1);
txt.setText("Executed"); // txt.setText(result);
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(Void... values) {}
}
}
WebServiceActivity containts嵌套類LongOperation延伸的AsyncTask。它是我的佈局沒有正確綁定?
需要一些建議
下面的鏈接可以是有用的: http://stackoverflow.com/questions/9671546 /的AsyncTask-Android的示例 – Drv