从AsyncTask的类返回的数据 [英] Return data from AsyncTask class
问题描述
我如何从我的AsyncTask的数据?我MainActivity被调用DataCall.getJSON功能触发AsyncTask的,但我不知道如何让数据恢复到原来的活动。
MainActivity与调用DataCall应该返回一个字符串,并将其保存在 state_data code>
字符串state_data = DataCall.getJSON(spinnerURL,spinnerContentType);
DataCall:
公共类DataCall延伸活动{
私有静态最后字符串变量=MyApp的;
私有类DownloadWebPageTask扩展的AsyncTask<字符串,太虚,字符串> {
保护字符串doInBackground(字符串...网址){
串响应=;
对于(字符串网址:网址){
DefaultHttpClient客户端=新DefaultHttpClient();
HTTPGET HTTPGET =新HTTPGET(URL);
尝试 {
HTT presponse执行= client.execute(HTTPGET);
InputStream的内容= execute.getEntity()的getContent()。
的BufferedReader缓冲=新的BufferedReader(
新InputStreamReader的(内容));
字符串s =;
而((S = buffer.readLine())!= NULL){
响应+ = S;
}
}赶上(例外五){
e.printStackTrace();
}
}
返回响应;
}
保护无效onPostExecute(字符串结果){
//这是我需要回到我的数据TO的主要活动。 (我猜测)
}
}
公共无效的getJSON(字符串myUrlString,字符串的contentType){
DownloadWebPageTask任务=新DownloadWebPageTask();
task.execute(新的String [] {http://www.mywebsite.com/+ myUrlString});
}
}
关键的,我是要创建一个类名为URLWithParams或东西,因为的AsyncTask将允许在只发送1类型,我需要两个URL和PARAMS的HTTP请求。
公共类URLWithParams {
公共字符串URL;
公开名单<的NameValuePair> namevaluepairs中;
公共URLWithParams()
{
namevaluepairs中=新的ArrayList<的NameValuePair>();
}
}
,然后我将其发送到JSONClient:
公共类JSONClient扩展的AsyncTask< URLWithParams,太虚,字符串> {
私人最终静态字符串变量=JSONClient;
ProgressDialog progressDialog;
GetJSONListener getJSONListener;
公共JSONClient(GetJSONListener监听器){
this.getJSONListener =侦听器;
}
@覆盖
保护字符串doInBackground(URLWithParams ...网址){
返回连接(网址[0] .URL,网址[0] .nameValuePairs);
}
公共静态字符串连接(字符串URL,列表和LT;的NameValuePair>对)
{
HttpClient的HttpClient的=新DefaultHttpClient();
如果(网址== NULL)
{
Log.d(TAG,想连接,但网址为空);
}
其他
{
Log.d(TAG,开始跟URL+网址);
}
如果(对== NULL)
{
Log.d(TAG,想连接,但对为空);
}
其他
{
Log.d(TAG,开始跟这么多的对:+ pairs.size());
对于(的NameValuePair狗:对)
{
Log.d(TAG,例如:+ dog.toString());
}
}
//执行请求
HTT presponse响应;
尝试 {
// prepare请求对象
HttpPost httpPost =新HttpPost(URL);
httpPost.setEntity(新UrlEn codedFormEntity(对));
响应= httpclient.execute(httpPost);
//检查响应状态
Log.i(TAG,response.getStatusLine()的toString());
的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(response.getEntity()的getContent(),UTF-8));
JSON字符串= reader.readLine();
返回JSON;
}赶上(ClientProtocolException E){
// TODO自动生成的catch块
e.printStackTrace();
}赶上(IOException异常E){
// TODO自动生成的catch块
e.printStackTrace();
}
返回null;
}
@覆盖
保护无效onPostExecute(JSON字符串){
getJSONListener.onRemoteCallComplete(JSON);
}
公共接口GetJSONListener {
公共无效onRemoteCallComplete(字符串jsonFromNet);
}
}
然后从我的主类像这样把它叫做
公共类BookCatalog实现GetJSONListener {
私人最终字符串变量= this.getClass()getSimpleName()。
私人字符串CATALOG_URL =URL;
私人无效getCatalogFromServer(){
URLWithParams mURLWithParams =新URLWithParams();
mURLWithParams.url = CATALOG_URL;
尝试 {
JSONClient asyncPoster =新JSONClient(本);
asyncPoster.execute(mURLWithParams);
}赶上(例外五){
// TODO自动生成的catch块
e.printStackTrace();
}
}
@覆盖
公共无效onRemoteCallComplete(字符串jsonBookCatalogList){
Log.d(TAG,收到的JSON目录:);
Log.d(TAG,jsonBookCatalogList);
的JSONObject bookCatalogResult;
尝试 {
bookCatalogResult =(JSONObject的)新JSONTokener(jsonBookCatalogList).nextValue();
JSONArray书= bookCatalogResult.getJSONArray(书);
如果(书!= NULL){
ArrayList的<字符串> newBookOrdering =新的ArrayList<字符串>();
INT num_books = books.length();
BookCatalogEntry温度;
DebugLog.d(TAG,显然,我们发现+ Integer.toString(num_books)+的书。);
对于(INT book_id = 0; book_id< num_books; book_id ++){
JSONObject的书= books.getJSONObject(book_id);
字符串标题= book.getString(标题);
INT版本= book.getInt(代价);
}
}
}赶上(JSONException E){
e.printStackTrace();
}
}
}
How do I get the data from my AsyncTask? My MainActivity is calling the DataCall.getJSON function that triggers the AsyncTask but I am not sure how to get the data back to the original Activity.
MainActivity with call to DataCall that should return a string and save it in state_data
String state_data = DataCall.getJSON(spinnerURL,spinnerContentType);
DataCall:
public class DataCall extends Activity {
private static final String TAG = "MyApp";
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
protected void onPostExecute(String result) {
//THIS IS WHERE I NEED TO RETURN MY DATA TO THE MAIN ACTIVITY. (I am guessing)
}
}
public void getJSON(String myUrlString, String contentType) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.mywebsite.com/" + myUrlString });
}
}
The key for me was to create a class called URLWithParams or something because AsyncTask will allow only 1 type to be sent IN, and I needed both the URL and the params for the HTTP request.
public class URLWithParams {
public String url;
public List<NameValuePair> nameValuePairs;
public URLWithParams()
{
nameValuePairs = new ArrayList<NameValuePair>();
}
}
and then I send it to a JSONClient:
public class JSONClient extends AsyncTask<URLWithParams, Void, String> {
private final static String TAG = "JSONClient";
ProgressDialog progressDialog ;
GetJSONListener getJSONListener;
public JSONClient(GetJSONListener listener){
this.getJSONListener = listener;
}
@Override
protected String doInBackground(URLWithParams... urls) {
return connect(urls[0].url, urls[0].nameValuePairs);
}
public static String connect(String url, List<NameValuePair> pairs)
{
HttpClient httpclient = new DefaultHttpClient();
if(url == null)
{
Log.d(TAG, "want to connect, but url is null");
}
else
{
Log.d(TAG, "starting connect with url " + url);
}
if(pairs == null)
{
Log.d(TAG, "want to connect, though pairs is null");
}
else
{
Log.d(TAG, "starting connect with this many pairs: " + pairs.size());
for(NameValuePair dog : pairs)
{
Log.d(TAG, "example: " + dog.toString());
}
}
// Execute the request
HttpResponse response;
try {
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
response = httpclient.execute(httpPost);
// Examine the response status
Log.i(TAG,response.getStatusLine().toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
return json;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String json ) {
getJSONListener.onRemoteCallComplete(json);
}
public interface GetJSONListener {
public void onRemoteCallComplete(String jsonFromNet);
}
}
Then call it from my main class like this
public class BookCatalog implements GetJSONListener {
private final String TAG = this.getClass().getSimpleName();
private String catalog_url = "URL";
private void getCatalogFromServer() {
URLWithParams mURLWithParams = new URLWithParams();
mURLWithParams.url = catalog_url;
try {
JSONClient asyncPoster = new JSONClient(this);
asyncPoster.execute(mURLWithParams);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onRemoteCallComplete(String jsonBookCatalogList) {
Log.d(TAG, "received json catalog:");
Log.d(TAG, jsonBookCatalogList);
JSONObject bookCatalogResult;
try {
bookCatalogResult = (JSONObject) new JSONTokener(jsonBookCatalogList).nextValue();
JSONArray books = bookCatalogResult.getJSONArray("books");
if(books != null) {
ArrayList<String> newBookOrdering = new ArrayList<String>();
int num_books = books.length();
BookCatalogEntry temp;
DebugLog.d(TAG, "apparently we found " + Integer.toString(num_books) + " books.");
for(int book_id = 0; book_id < num_books; book_id++) {
JSONObject book = books.getJSONObject(book_id);
String title = book.getString("title");
int version = book.getInt("price");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
这篇关于从AsyncTask的类返回的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!