简体   繁体   English

AsyncTask/doInBackground 未执行

[英]AsyncTask/doInBackground not executing

I'm trying to create an app that queries a site of cat images, saves them to the android device if the JSON ID is unique, and then display them from the device in a slideshow format.我正在尝试创建一个查询猫图像站点的应用程序,如果 JSON ID 是唯一的,则将它们保存到 android 设备,然后以幻灯片格式从设备显示它们。 Despite everything my AsyncTask doesn't seem to actually be executing.尽管如此,我的 AsyncTask 似乎并没有真正执行。 Debugger confirms a network connection is established and doesn't feed me back any errors so I have no idea what's wrong with my code.调试器确认网络连接已建立并且没有反馈给我任何错误,所以我不知道我的代码有什么问题。 Hoping someone can help!希望有人能帮忙! Code is below:代码如下:

package com.example.lab2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.AsyncTaskLoader;

import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

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

        CatImages req = new CatImages();
        req.execute();
    }

    class CatImages extends AsyncTask<String, Integer, String> {

        ArrayList<String> ids = new ArrayList<String>();

        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        Bitmap images;
        String id;
        ImageView imageView = findViewById(R.id.imageView);
        ProgressBar progressBar = findViewById(R.id.progressBar);
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        boolean on = true;

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

            while(on == true) {
                try {
                    URL url = new URL("https://cataas.com/cat?json=true");
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    InputStream response = urlConnection.getInputStream();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"), 8);
                    StringBuilder builder = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        builder.append(line + "\n");
                    }
                    String result = builder.toString();
                    JSONObject image = new JSONObject(result);
                    id = image.getString("id");
                    ids.add(id);

                    for (String element : ids) {
                        if (element.contains(id)) {

                            return null;

                        } else {

                            images = BitmapFactory.decodeStream(response);
                            File path = new File(directory, id + ".jpg");
                            FileOutputStream outputStream = new FileOutputStream(path);
                            images.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                            outputStream.flush();
                            outputStream.close();
                            ids.add(id);

                        }
                    }

                    for (int i = 0; i < 100; i++) {
                        try {
                            publishProgress(i);
                            Thread.sleep(30);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }


                } catch (IOException | JSONException e) {
                    return null;
                }

            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);

            for(String element : ids) {
                if(element.contains(id)) {

                    File openedPic = new File(directory, id + ".jpg");
                    try {
                        Bitmap opener = BitmapFactory.decodeStream(new FileInputStream(openedPic));
                        imageView.setImageBitmap(opener);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                }
            }
        }

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

Try changing !=null to ==null in your second while loop.尝试在第二个 while 循环中将!=null更改为==null

Also you just need while(on) in your first while loop.此外,您只需要在第一个 while 循环中while(on)

Let me know if anything changes.让我知道是否有任何变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM