RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 750318
Accepted
Вячеслав
Вячеслав
Asked:2020-11-27 22:44:20 +0000 UTC2020-11-27 22:44:20 +0000 UTC 2020-11-27 22:44:20 +0000 UTC

将多个文件上传到 AsyncTask 时出现问题

  • 772

帮助处理错误:在 RecyclerView 中,当您单击一个元素时,会转换到带有“下载”和“读取”按钮的活动。当您单击“加载”时,将启动 AsyncTask(加载 url 列表)。下载后,按钮变为非活动状态(条件是有一个包含下载文件的文件夹)。当您单击“阅读”时,将切换到另一个活动以查看图片。有条件 - 这是第一本书,它的文件供查看。因此,当您尝试下载第二本书时,表面上一切都很好,但无法查看文件 - 它们没有加载。在调试器中,我运行了两本书的下载周期——它工作不稳定,然后一个文件将加载七个文件,然后一切都完全正常。如果我清理应用程序数据,我首先加载的书可以正常工作。

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tonyodev.fetch.Fetch;
import com.tonyodev.fetch.request.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import ru.yandex.matu1.toddlersbook.models.Book;
import ru.yandex.matu1.toddlersbook.models.BookFiles;

public class BookCardActivity extends AppCompatActivity {
    static final String TAG = "myLogs";
    private int bookId;
    private String fileNamePath = "filesPath.json";

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

        BookUriFromId();

        String covers = MyJSON.getData(this, fileNamePath);
        ArrayList<String> coversPaths = getFilesPathFromFile(covers);

        ImageView imageView = (ImageView) findViewById(R.id.imageView);
        int posit = bookId-1;
        File imgFile = new File(coversPaths.get(posit));
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        imageView.setImageBitmap(myBitmap);

        Button buttonDownload = (Button) findViewById(R.id.button);
        Button buttonRead = (Button) findViewById(R.id.button2);

        String fileBookSt = "book_" + bookId + ".json";
        File fileOfBook = new File(getApplicationContext().getFilesDir().getPath() + File.separator + fileBookSt);

        if(fileOfBook.exists()){
            buttonDownload.setEnabled(false);
        }

        buttonDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Type itemsListType = new TypeToken<List<String>>() {
                }.getType();
                String folderB = "bookfiles_" + bookId;
                String fileBookStorage = "book_" + bookId + ".json";

                    BookLoader bookLoader = new BookLoader();
                    bookLoader.execute();

                    ArrayList<String> pagesPath;
                    ArrayList<String> soundsPath;
                    soundsPath = new ArrayList<>();


                    File bookfolder = new File(String.valueOf(getExternalFilesDir(folderB)));

                    if (!bookfolder.exists()) {
                        bookfolder.mkdirs();
                        Log.d("my", "dir. created");
                    }

                    try {
                        String result = bookLoader.get();
                        Gson gson = new Gson();
                        Book book = gson.fromJson(result, Book.class);
                        List<String> pages = book.getPageUrl();
                        String[] urlsPages = pages.toArray(new String[0]);

                        FileLoader fileLoader = new FileLoader();
                        fileLoader.execute(urlsPages);
                        String flResult = fileLoader.get();

                        pagesPath = new Gson().fromJson(flResult, itemsListType);

                        BookFiles bookFiles = new BookFiles();
                        bookFiles.setBookID(bookId);
                        bookFiles.setPagesPath(pagesPath);
                        bookFiles.setSoundsPath(soundsPath);

                        Gson gson11 = new Gson();
                        String filesJson = gson11.toJson(bookFiles);

                        MyJSON.saveData(getApplicationContext(), filesJson, fileBookStorage);

                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                    }
//                }
            }
        });
    buttonRead.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NextActivity();
        }
    });

    }

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

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        String resultJsonBook = "";
        private String bookIdJson = "http://*****.ru/todbook/book" + bookId + ".json";

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(bookIdJson);

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();

                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }

                resultJsonBook = buffer.toString();

            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultJsonBook;
        }

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

    }

    private class FileLoader extends AsyncTask<String, Void, String> {
        Fetch mFetch;
        String folderB = "bookfiles_" + bookId;
        File bookfolder = new File(String.valueOf(getExternalFilesDir(folderB)));
        List<Request> requestListPages = new ArrayList<>();
        ArrayList<String> pagesPath = new ArrayList<>();
        String resultD;

        @Override
        protected String doInBackground(String... urlsFiles) {

            mFetch = Fetch.newInstance(getApplicationContext());
            mFetch.removeRequests(); //чистим базу запросов

            for (int i = 0; i < urlsFiles.length; i++) {
                String url = urlsFiles[i];
                String path = String.valueOf(bookfolder);
                String fileName = Uri.parse(url).getLastPathSegment();
                Log.d("my2", fileName);
                Request request = new Request(url, path, fileName);
                requestListPages.add(request);
                String pageFilePath = path + "/" + fileName;
                Log.d("my2", pageFilePath);
                pagesPath.add(pageFilePath);
            }

            mFetch.enqueue(requestListPages);
//            resultD = String.valueOf(pagesPath);
            String resultD = new Gson().toJson(pagesPath);
            return resultD;

        }

    }

    private void BookUriFromId() {
        //получаем номер ID книги, с обложки которой перешли в слайдер
        Intent intent = getIntent();
        bookId = intent.getIntExtra("bookId", 1);
        Log.d(TAG, "You read book №" + bookId);
    }

    private void NextActivity() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(BookCardActivity.this, SliderActivity.class);
                intent.putExtra("bookId", bookId); // передаю в слайдер номер книги

                startActivity(intent);
                finish();
            }
        }, 20);
    }

    private ArrayList<String> getFilesPathFromFile(String jsResult) {
        ArrayList<String> urisImg = new ArrayList<>();
        try {
            JSONArray rootJson = new JSONArray(new JSONTokener(jsResult));
            for (int i = 0; i < rootJson.length(); i++) {
                JSONObject o = rootJson.getJSONObject(i);
                String strTo = (String) o.get("uriString");
                urisImg.add(strTo);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return urisImg;
    }

}
android
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    Eugene Krivenja
    2020-11-27T23:02:52Z2020-11-27T23:02:52Z

    好吧,你写了AsyncTask-ov 并在 UI 线程中同步调用它们(View.OnClickListener)

    String result = bookLoader.get();
    ...
    String flResult = fileLoader.get();
    

    再看下去也没有意义,一切都需要重写。

    PS 看来你过去的 C# 经验困扰着你,await/async在 Kotlin-e 中只有 Android 的相似之处。

    • 2

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    Python 3.6 - 安装 MySQL (Windows)

    • 1 个回答
  • Marko Smith

    C++ 编写程序“计算单个岛屿”。填充一个二维数组 12x12 0 和 1

    • 2 个回答
  • Marko Smith

    返回指针的函数

    • 1 个回答
  • Marko Smith

    我使用 django 管理面板添加图像,但它没有显示

    • 1 个回答
  • Marko Smith

    这些条目是什么意思,它们的完整等效项是什么样的

    • 2 个回答
  • Marko Smith

    浏览器仍然缓存文件数据

    • 1 个回答
  • Marko Smith

    在 Excel VBA 中激活工作表的问题

    • 3 个回答
  • Marko Smith

    为什么内置类型中包含复数而小数不包含?

    • 2 个回答
  • Marko Smith

    获得唯一途径

    • 3 个回答
  • Marko Smith

    告诉我一个像幻灯片一样创建滚动的库

    • 1 个回答
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Алексей Шиманский 如何以及通过什么方式来查找 Javascript 代码中的错误? 2020-08-03 00:21:37 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    user207618 Codegolf——组合选择算法的实现 2020-10-23 18:46:29 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5