我使用的AsyncTask類在我的第一個活動其做工精細 並調用第二個,我調用另一個的AsyncTask調用對象的onCreate 並調用Web服務在doInBackground 那麼它的給予例外 機器人.os.networkmainthread。如何使用的AsyncTask在Android 4.2
我沒有得到作爲 我是新來的Android開發 任何想法,所以請給我一些樣品或我告訴你我的代碼
這是我的代碼
public class panel extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.panel);
User_Balance_Load Balance_load=new User_Balance_Load();
Balance_load.execute();
Toast.makeText(getBaseContext(),Cls_Constant.username, Toast.LENGTH_LONG).show();
}
class User_Balance_Load extends AsyncTask<Void, Void, Void>
{
private final ProgressDialog dialog = new ProgressDialog(panel.this);
protected void onPreExecute() {
this.dialog.setMessage("Loding Diet type...");
this.dialog.show();
}
protected Void doInBackground(final Void... unused) {
// TODO Auto-generated method stub
panel.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Update_balance();
}
});
return null;
}
protected void onPostExecute(Void result)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
}
}
void Update_balance()
{
Vector result;
result=Cls_webservice.User_Balance(Cls_Constant.Guid);
if(result.size()>0)
{
String UserBalance=result.elementAt(2).toString();
TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
Tv_User_balacne.setText(UserBalance);
}
}
這是我的類web服務的
public class Cls_webservice {
public static Vector User_Balance(String id)
{
Vector _vector = new Vector();
final String userid = id;
final String METHOD_NAME = "WCFDatatableRes";
final String SOAP_ACTION = "http://tempuri.org/WCFDatatableRes";
final String NAMESPACE = "http://tempuri.org/";
final String URL = "http://xxxxxxxx.com/GameRoom/ANDROIDLOTT/WebService.asmx";
String return_val="";
SoapObject newob;
try
{
Object response;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.encodingStyle = SoapEnvelope.ENC;
SoapObject Request = new SoapObject(NAMESPACE , METHOD_NAME);
Request.addProperty("Params", userid+",3");
Request.addProperty("Do", "Balance");
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
AndroidHttpTransport httptransport ;
httptransport = new AndroidHttpTransport(URL);
httptransport.debug=true;
try
{
httptransport.call(SOAP_ACTION,envelope);
response = envelope.getResponse();
newob = (SoapObject)envelope.bodyIn;
return_val = newob.toString();
SoapObject diettype_listResult = (SoapObject) newob.getProperty("WCFDatatableRes ") ;
SoapObject diffgram = (SoapObject) diettype_listResult.getProperty("diffgram") ;
}
catch (Exception e) {
System.out.println("error:" + e);
}
}
catch (Exception e) {
}
return _vector;
}
}
異常來自這一行 - >「httptransport.call(SOAP_ACTION,envelope); 所以請幫助我 和 我的第一個活動 相同的代碼的工作,我不知道爲什麼在第二次前來錯誤 感謝
,因爲你正在運行在UI線程網絡相關的操作時
感謝JesusS :)謝謝,你極多 – Dharmeshsharma 2013-04-08 09:09:43
別客氣 :) – JesusS 2013-04-08 09:46:46