当我运行我的 android studio java 应用程序时,它在真实设备上崩溃了

问题描述 投票:0回答:0

我有以下代码,我正在尝试制作一个应用程序,从网站获取足球运动员的照片和姓名,然后放置一张带有 4 种可能答案的图像,用户必须猜测它是谁。但是,在我的设备上运行它时它崩溃了

我的代码:

package com.example.a82guessthecelebrity;


import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> footballerURLs = new ArrayList<String>();
    ArrayList<String> footballerNames = new ArrayList<String>();
    int chosenPlayer = 0;
    String[] answers = new String[4];
    int locationOfCorrectAnswer = 0;
    ImageView imageView;
    Button button0;
    Button button1;
    Button button2;
    Button button3;
    int score;
    int questionsAsked;

    public void celebChosen(View view) {
        if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))) {
            Toast.makeText(getApplicationContext(),"Correct!",Toast.LENGTH_SHORT).show();
            score ++;
        } else {
            Toast.makeText(getApplicationContext(),"Wrong! It was " + footballerNames.get(chosenPlayer),Toast.LENGTH_SHORT).show();
        }
        questionsAsked ++;

        newQuestion();
    }

    public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... urls) {
            try {

                URL url = new URL(urls[0]);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                InputStream inputStream = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
                return myBitmap;

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

    public class DownloadTask extends AsyncTask<String, Void, String> {

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

            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;

            try {

                url = new URL(urls[0]);

                urlConnection = (HttpURLConnection) url.openConnection();

                InputStream in = urlConnection.getInputStream();

                InputStreamReader reader = new InputStreamReader(in);

                int data = reader.read();

                while (data != -1) {
                    char current = (char) data;
                    result += current;
                    data = reader.read();
                }

                return result;

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

        }
    }

    public void newQuestion() {
        try {
            Random rand = new Random();

            chosenPlayer = rand.nextInt(footballerURLs.size());

            ImageDownloader imageTask = new ImageDownloader();

            Bitmap playerImage = imageTask.execute(footballerURLs.get(chosenPlayer)).get();

            imageView.setImageBitmap(playerImage);

            locationOfCorrectAnswer = rand.nextInt(4);

            int incorrectAnswerLocation;

            for (int i = 0; i < 4; i++) {
                if (i == locationOfCorrectAnswer) {
                    answers[i] = footballerNames.get(chosenPlayer);
                } else {
                    incorrectAnswerLocation = rand.nextInt(footballerURLs.size());

                    while (incorrectAnswerLocation == chosenPlayer) {
                        incorrectAnswerLocation = rand.nextInt(footballerURLs.size());
                    }

                    answers[i] = footballerNames.get(incorrectAnswerLocation);
                }
            }

            button0.setText(answers[0]);
            button1.setText(answers[1]);
            button2.setText(answers[2]);
            button3.setText(answers[3]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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


        imageView = findViewById(R.id.imageView);
        button0 = findViewById(R.id.button0);
        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        button3 = findViewById(R.id.button3);

        DownloadTask task = new DownloadTask();
        String result = null;

        try {

            result = task.execute("https://bleacherreport.com/articles/705591-the-100-best-soccer-players-of-all-time").get();

            String[] splitResult = result.split("<div class=\"organism contentStream slide\" id=\"slide68\">");

            Pattern p = Pattern.compile("<img alt=(.*?)>");
                Matcher m = p.matcher(splitResult[1]);

            while (m.find()) {
                Pattern p2 = Pattern.compile("src=\"(.*?)\"");

                Matcher m2 = p2.matcher(m.group(1));

                while (m2.find()) {
                    footballerURLs.add(m2.group(1));

                }

            }


            Pattern p3 = Pattern.compile("<div class=\"organism contentStream slide\"(.*?)/h2>");
            Matcher m3 = p3.matcher(splitResult[1]);

            while (m3.find()) {
                Pattern p4 = Pattern.compile("<h2>(.*?)<");
                Matcher m4 = p4.matcher(Objects.requireNonNull(m3.group(1)));

                while (m4.find()) {
                    String footballerName = m4.group(1).trim();
                    footballerName = footballerName.replaceAll("[0-9]", "");
                    footballerName = footballerName.replaceAll("\\. ", "");
                    footballerNames.add(footballerName);

                }

            }
            footballerNames.remove(1);


            newQuestion();

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

错误:

03/25 16:10:46: Launching 'app' on OPPO CPH2219.
Install successfully finished in 264 ms.
$ adb shell am start -n "com.example.a82guessthecelebrity/com.example.a82guessthecelebrity.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 7770 on device 'oppo-cph2219-e91b6bde'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/essthecelebrit: Late-enabling -Xcheck:jni
E/essthecelebrit: Unknown bits set in runtime_flags: 0x40000000
D/ProcessState: Binder ioctl to enable oneway spam detection failed: Invalid argument
I/OneTrace: Mark active for pid=7770? true
D/cutils-dev: otrace_set_tracing_enabled? true
D/cutils-dev: properties changed in otrace_seq_number_changed!
W/re-initialized>: type=1400 audit(0.0:18700): avc: granted { execute } for path="/data/data/com.example.a82guessthecelebrity/code_cache/startup_agents/69880af5-agent.so" dev="dm-29" ino=453160 scontext=u:r:untrusted_app:s0:c91,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c91,c256,c512,c768 tclass=file app=com.example.a82guessthecelebrity
V/studio.deploy: Startup agent attached to VM
V/studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-6b5afa68.jar
W/essthecelebrit: DexFile /data/data/com.example.a82guessthecelebrity/code_cache/.studio/instruments-6b5afa68.jar is in boot class path but is not in a known location
V/studio.deploy: Applying transforms with cached classes
W/essthecelebrit: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
W/essthecelebrit: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10091; state: ENABLED
I/oplus.android.OplusFrameworkFactoryImpl: get feature:IOplusAutoResolutionFeature
I/oplus.android.OplusFrameworkFactoryImpl: getOplusAutoResolutionFeature
D/CompactWindowAppManager: initCompactApplicationInfo 
I/OplusFeatureCache: Milliseconds spent on init(): 37
D/LoadedApk: mApplicationInfo overrideDisplayId:null
V/GraphicsEnvironment: ANGLE Developer option for 'com.example.a82guessthecelebrity' set to: 'default'
V/GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
E/MultiApp.Impl: OplusMultiAppImpl
D/AppCompatDelegate: Checking for metadata for AppLocalesMetadataHolderService : Service not found
I/oplus.android.OplusFrameworkFactoryImpl: Unknow feature:IOplusTextViewRTLUtilForUG
W/essthecelebrit: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
W/essthecelebrit: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
E/OplusCustomizeRestrictionManager: sInstance is null, start a new sInstance
I/Quality: ActivityThread: viewInflate delay 141 com.example.a82guessthecelebrity:layout/activity_main 7770
W/System: A resource failed to call close. 
I/essthecelebrit: Thread[5,tid=7776,WaitingInMainSignalCatcherLoop,Thread*=0xb400007e2fc8cc00,peer=0x12d01fe0,"Signal Catcher"]: reacting to signal 3
I/essthecelebrit: 
I/essthecelebrit: Waiting for a blocking GC ObjectsAllocated
I/essthecelebrit: WaitForGcToComplete blocked ObjectsAllocated on Background for 17.625ms
I/essthecelebrit: Wrote stack traces to tombstoned
I/essthecelebrit: Thread[5,tid=7776,WaitingInMainSignalCatcherLoop,Thread*=0xb400007e2fc8cc00,peer=0x12d01fe0,"Signal Catcher"]: reacting to signal 3
I/essthecelebrit: 
I/essthecelebrit: Waiting for a blocking GC ObjectsAllocated
I/essthecelebrit: WaitForGcToComplete blocked ObjectsAllocated on Background for 28.916ms
I/essthecelebrit: Wrote stack traces to tombstoned

请帮忙

在模拟器上运行app没问题,但是在oppo上运行就崩溃了

java android crash
© www.soinside.com 2019 - 2024. All rights reserved.