当前位置: 首页 > 知识库问答 >
问题:

只有创建视图层次结构的原始线程才能接触其视图-Android

马梓
2023-03-14

我正在使用MultipartEntityBuilder将图像发送到php服务器,我将图片和视频发送到设备摄像头的目录中,我需要将文件保存在新的ArrayList上并将其发送到php服务器。

总是报告错误:

我的代码

private class MyAsyncTask extends AsyncTask<String, Integer, Double>
    {
        @Override
        protected Double doInBackground (String... params)
        {
            String datos = value.getText().toString();

            HttpClient httpClient = getNewHttpClient();

            HttpPost httppost = new HttpPost("https://myurl.com");

            try
            {

path = Environment.getExternalStorageDirectory().toString() + "/mydirectory";

                File fileArray = new File(path);
                ArrayList<File> files = new ArrayList<File>(Arrays.asList(fileArray.listFiles()));

                int itemCount = files.size();

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();

                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                for (int i = 0; i < itemCount; i++)
                {
                    builder.addPart("images[]", new FileBody(new File(path + "/" + num_img)));
                    num_img++;
                }

                builder.addTextBody("response", "prueba");

                HttpEntity entity = builder.build();

                httppost.setEntity(entity);

    //...............................

}

更新

protected void onPostExecute (Double result)
        {
            path = Environment.getExternalStorageDirectory().toString() + "/myDirectory";


            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    File fileArray = new File(path);
                    ArrayList<File> files = new ArrayList<File>(Arrays.asList(fileArray.listFiles()));

                    int itemCount = files.size();
                    tv_files.setText("valor:" + itemCount);

                    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

                    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                    builder.addTextBody("response", "prueba");

                    for (int i = 0; i < itemCount; i++)
                    {
                        builder.addPart("images[]", new FileBody(new File(path + "/" + num_img)));
                        num_img++;
                    }

                    HttpEntity entity = builder.build();

                }
            });

共有1个答案

文自怡
2023-03-14

这个错误是想告诉你永远不要碰任何线程之外的UI视图不运行在UIThread上。

在您的DoInBackground中,您试图获取编辑文本的值,这是考虑在后台运行的线程中触摸UI视图。

解决方案:移动以下行

String datos = value.getText().toString();

onPreExcute()AsyncTask的构造函数上的doInbackground外部方法。只需将String datos声明为AsyncTask中的全局变量,并根据需要在您的doInbackground()中使用它

    @Override
    protected void onPreExecute() {
       datos = value.getText().toString();
    }

 类似资料: