我需要从AsyncTask访问一个Object。 这是AsyncTask的代码:
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
@Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
我想访问data
。我不知道我该怎么做。
答案 0 :(得分:1)
另一个替代方法是使用private static modifier声明data
变量并创建一个public static get方法。从第二个活动可以直接访问该公共静态方法。
private class FirstAcitivity extends Activity
{
private static String data = "";
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
@Override
protected String doInBackground(String... url) {
// For storing data from web service
//String data = ""; // Comment this line
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
public static String getData()
{
return data;
}
}
现在访问第二个活动
public class SecondActivity extends Activity
{
String data = FirstActivity.getData();
}
答案 1 :(得分:1)
您也可以通过将变量声明如下来访问它:
public static String data="";
然后您可以在其他活动中访问它:
ClassName.data
其中ClassName将是您定义变量的类的名称。