leithdm
4/24/2020 - 4:19 PM

Celeb names: code to parse straight up HTML on a website

public class MainActivity<ArraList> extends AppCompatActivity {

    String website = "INSERT URL HERE";
    String downloadedHTML = null;
    ArrayList<String> celebNames;
    ArrayList<String> celebPictureSource;
    ImageView imageView;
    private int correctAnswerLocation;

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

        DownloadTask downloadHTMLTask = new DownloadTask();
        try {
            downloadedHTML = downloadHTMLTask.execute(website).get();
            //Log.i("HTML code as follows", downloadedHTML);
            setupArrays();
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("ERROR: downloading HTML", "Failed to download HTML");
        }
    }

    private void setupArrays() {
        celebNames = new ArrayList<>();
        Pattern pName = Pattern.compile("<span>(.*?)</span>");
        Matcher mName = pName.matcher(downloadedHTML);

        celebPictureSource = new ArrayList<>();
        Pattern pImage = Pattern.compile("img src=\"(.*?)\" width");
        Matcher mImage = pImage.matcher(downloadedHTML);

        while (mName.find()) {
            celebNames.add(mName.group(1));
        }

        while (mImage.find()) {
            celebPictureSource.add(mImage.group(1));
        }
        Log.i("CelebNames Array", celebNames.toString());
        Log.i("Celeb pictures Array", celebPictureSource.toString());
        setupButtonsAndImage();
    }

    private int[] generateFourRandomNumbers() {
        int[] array = new int[4];
        for (int i = 0; i < 4; i++) {
            array[i] = new Random().nextInt(celebNames.size() - 1) + 1; //index 0 is junk data
        }
        return array;
    }

    private void setupButtonsAndImage() {

        correctAnswerLocation = (int) (Math.random() * 4);
        int[] randomCelebName = generateFourRandomNumbers();
        System.out.println("Random celeb names is: " + Arrays.toString(randomCelebName));
        System.out.println("Correct celeb name is " + celebNames.get(randomCelebName[correctAnswerLocation]));
        System.out.println("Correct celeb image is " + celebPictureSource.get(randomCelebName[correctAnswerLocation]));
        System.out.println("Correct answer location is " + correctAnswerLocation);

        Button b1 = findViewById(R.id.button1);
        b1.setText(celebNames.get(randomCelebName[0]));
        Button b2 = findViewById(R.id.button2);
        b2.setText(celebNames.get(randomCelebName[1]));
        Button b3 = findViewById(R.id.button3);
        b3.setText(celebNames.get(randomCelebName[2]));
        Button b4 = findViewById(R.id.button4);
        b4.setText(celebNames.get(randomCelebName[3]));

        imageView = findViewById(R.id.imageView);
        ImageDownloader task = new ImageDownloader();
        Bitmap myBitmap;

        try {
            myBitmap = task.execute(celebPictureSource.get(randomCelebName[correctAnswerLocation])).get();
            imageView.setImageBitmap(myBitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void guessAnswer(View view) {
        Button b = (Button) view;
        if (Integer.parseInt(b.getTag().toString()) == correctAnswerLocation) { //alternative if (view.getTag().toString().equals(Integer.toString(correctAnswerLocation)
            Toast.makeText(this, "You are correct !", Toast.LENGTH_SHORT).show();
            setupArrays();
        } else {
            Toast.makeText(this, "You are wrong", Toast.LENGTH_SHORT).show();
        }
    }

    //download the image
    public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... urls) {
            try {
                URL url = new URL(urls[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                InputStream is = urlConnection.getInputStream();
                return BitmapFactory.decodeStream(is);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("I could not return a Bitmap");
                return null;
            }
        }
    }


    //download the page source
    public class DownloadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String result = "";
            URL url;
            HttpURLConnection httpURLConnection;

            try {
                url = new URL(urls[0]);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream ips = httpURLConnection.getInputStream();
                InputStreamReader ipsReader = new InputStreamReader(ips);
                int data = ipsReader.read();

                while (data != -1) {
                    char c = (char) data;
                    result += c;
                    data = ipsReader.read();
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                return "Failed to download data";
            }
        }
    }
}