2013-02-11 24 views
-1

我對android編程非常陌生,我在Android 2.2中編寫了我的應用程序。但是,當我試圖在Android 3.0的運行我的應用程序或更高版本我得到這樣一個錯誤:在AsynTask中調用舊的方法調用doInBackground

android.os.NetworkOnMainThreadException 

在我的Android 2.2我有一個這樣的方法:

public JSONObject makeServiceCall(String url, Map<String, String> params) 

正在執行網絡通話操作。展望谷歌,我發現我需要將此代碼移動到AsyncTaskdoInBackground

但我在更改doInBackground的參數時遇到問題,因爲它需要Object... varags,其中我的方法需要兩個參數String,Map<String,String>

是否有任何解決方法我可以在doInBackground內部打電話給我的原始makeServiceCall

在此先感謝。

回答

1

您可以使用自定義的AsyncTask的構造函數發送多個變量,那麼您就不需要在​​方法中發送變量。是這樣的:在你的任何其他活動或其他類

private class MyAsyncTask extends AsyncTask<Void, Void, Boolean>{ 

    private String mString = null; 
    Map<String, String> mMap; 
    public MyAsyncTask(String s, Map<String, String> map) { 
     //assign values to class fields 
     this.mMap= map; 
     this.mString = s; 

    } 
    @Override 
    protected Boolean doInBackground(Void... params) { 
     //access class fields here. 
     } 
} 

使用它,如下:

new MyAsyncTask(yourString, yourMap).execute(); 
+0

謝謝。我的方法返回'JSONObject'。但是如果我遵循這一點,這將返回'AsyncTask ' – sriram 2013-02-11 13:04:58

+0

您可以根據您的要求更改它,從Class聲明中替換布爾值到'JSONObjec't,'doInBackground() '和'onPostExecuteMethod()'接收參數給'JSONObject'。 – 2013-02-11 13:07:33

0

嘗試使用Constructor

new Download(str1,str2).execute(); 


public class Download extends AsyncTask<Void, Void, String> {  
    ProgressDialog mProgressDialog; 

    public Download(String st1,String str2) { 

     String STR1 = str1; 
        String STR2 = str2; 
    } 

    protected void onPreExecute() { 
     mProgressDialog = ProgressDialog 
       .show(context, "", "Please wait..."); 
    } 

    protected String doInBackground(Void... params) { 
     //Call ur method use str1,str2 
     return 0; 

    } 

    protected void onPostExecute(String result) { 

    } 

} 
相關問題