在Android中如何从Asynctask接收字符串?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Android中如何从Asynctask接收字符串?相关的知识,希望对你有一定的参考价值。
在我的android项目中,我在MainActivity
内:
String receivedData = new myTask().execute().get();
现在myTask
任务是:
public class MainActivity extends Activity {
private Button button;
private TextView finalResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn_do_it);
finalResult = (TextView) findViewById(R.id.tv_result);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String receivedData = new myTask().execute().get();
finalResult.setText(receivedData);
}
});
}
private class myTask extends AsyncTask<String, Void, String> {
@Override
protected Void doInBackground(Void... params) {
Gson gson = new Gson();
List<Myobject> newObject = new ArrayList<Myobject>();
try {
//here I add object valus to the list
newObject.add(valueadded)
} catch {
Exception e
}
//here returning the value as String
return gson.toJson(newObject);
}
protected void onPostExecute(String result) {
String receivedData = result;
}
}
}
但是receiveData没有收到AsyncTask
的任何价值。为什么会这样?我究竟做错了什么?
答案
您的AsyncTask定义如下:
private class myTask extends AsyncTask<String, Void, Void>
最后一个泛型类型是结果的类型。你有空虚。这意味着您的AsyncTask不返回值。如果你想要一个String结果,你必须像这样定义它:
private class myTask extends AsyncTask<String, Void, String>
这意味着您现在可以从doInBackground()返回一个String。
另一答案
尝试这样的事情
public class MainActivity extends Activity {
String receivedData;
private Button button;
private TextView finalResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn_do_it);
finalResult = (TextView) findViewById(R.id.tv_result);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new myTask().execute().get();
}
});
}
private class myTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(Void... params) {
Gson gson = new Gson();
List<Myobject> newObject = new ArrayList<Myobject>();
try {
//here I add object valus to the list
newObject.add(valueadded)
} catch (Exception e) {
//here returning the value as String
return gson.toJson(newObject);
}
}
protected void onPostExecute(String result) {
String receivedData = result;
finalResult.setText(receivedData);
}
}
}
另一答案
您可以在Async Task中添加onPostExecute方法以接收String。喜欢下面
private class myTask extends AsyncTask<String, Void, String> {
@Override
protected Void doInBackground(Void... params) {
.........
return someString;
}
protected void onPostExecute(String result) {
String receivedData = result;
}
}
以上是关于在Android中如何从Asynctask接收字符串?的主要内容,如果未能解决你的问题,请参考以下文章
如何将变量从 AsyncTask 返回到 Android 中的 Google Map 活动
在 Android 中,如何从 AsyncTask 更改 TextView? [复制]