在Android中如何从Asynctask接收字符串()

笛里谁知壮士心,沙头空照征人骨。这篇文章主要讲述在Android中如何从Asynctask接收字符串?相关的知识,希望能为你提供帮助。
在我的android项目中,我在MainActivity内:

String receivedData = https://www.songbingjia.com/android/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 = https://www.songbingjia.com/android/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 = https://www.songbingjia.com/android/result; finalResult.setText(receivedData); } } }

另一答案【在Android中如何从Asynctask接收字符串()】您可以在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 = https://www.songbingjia.com/android/result; } }


    推荐阅读