【问题标题】:Asynctask android return contents "doinBackgroundAsynctask android返回内容“doinBackground
【发布时间】:2016-10-13 08:34:40
【问题描述】:

我想在我的活动中检索我的变量“$content”的内容。 但我不知道如何使用我的 doinbackground 的返回值。 你能帮助我吗 ? 提前谢谢你

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String restURL = "https://proxyepn-test.epnbn.net/wsapi/epn";
        RestOperation test = new RestOperation();
        test.execute(restURL);
    }

    private class RestOperation extends AsyncTask<String, Void, String> {

        //final HttpClient  httpClient = new DefaultHttpClient();
        String content;
        String error;
        ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        String data = "";
        TextView serverDataReceived = (TextView)findViewById(R.id.serverDataReceived);
        TextView showParsedJSON = (TextView) findViewById(R.id.showParsedJSON);

       // EditText userinput = (EditText) findViewById(R.id.userinput);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog.setTitle("Please wait ...");
            progressDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            BufferedReader br = null;

            URL url;
            try {
                url = new URL(params[0]);

                URLConnection connection = url.openConnection();
                connection.setDoOutput(true);

                OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
                outputStreamWr.write(data);
                outputStreamWr.flush();

                br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                while((line = br.readLine())!=null) {
                    sb.append(line);
                    sb.append(System.getProperty("line.separator"));
                }

                content = sb.toString();

            } catch (MalformedURLException e) {
                error = e.getMessage();
                e.printStackTrace();
            } catch (IOException e) {
                error = e.getMessage();
                e.printStackTrace();
            } finally {
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return content;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            progressDialog.dismiss();

            if(error!=null) {
                serverDataReceived.setText("Error " + error);
            } else {
                serverDataReceived.setText(content);

                String output = "";
                JSONObject jsonResponse;

                try {
                    jsonResponse = new JSONObject(content);

                    JSONArray jsonArray = jsonResponse.names();

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject child = jsonArray.getJSONObject(i);

                        String name = child.getString("name");
                        String number = child.getString("number");
                        String time = child.getString("date_added");

                        output = "Name = " + name + System.getProperty("line.separator") + number + System.getProperty("line.separator") + time;
                        output += System.getProperty("line.separator");
                        Log.i("content",content);

                    }

                    showParsedJSON.setVisibility(View.INVISIBLE);
                    showParsedJSON.setText(output);

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

【问题讨论】:

    标签: android android-asynctask return-value


    【解决方案1】:
    1. 您可以通过传递“内容”值直接从asynctask的onPostExecute方法调用活动中存在的方法。

      @Override
      
              protected void onPostExecute(String content) {
      
              Activity.yourMethod(content);
      
              }
      
    2. 如果你想从 asynctask 返回值,你可以使用

      content = test.execute(url).get();
      

    但这不是 asynctask 的好习惯,因为它是作为串行执行工作的。所以它不满足使用 asynctask 进行颚化。因为 get() 会阻塞 UI 线程。

    【讨论】:

    • 感谢您的快速回复,但我不明白如何。这是我尝试过的:
    • protected void onPostExecute(String result) { super.onPostExecute(result); MainActivity.returnContent(content);
    • private static void returnContent(String result) { Log.i("result",result); }
    • 您必须将活动传递给异步任务。在您的活动中,protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RestOperation 测试 = new RestOperation(this); test.execute(restURL);在你的 asynctask 中,创建构造函数。 public RestOperation(MainActivity activity){ this.activity = activity} 然后你可以访问activity.returnContent(count); // count 是一个参数,您可以在 doInBackground() 中设置数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多