Sunday, March 22, 2020

[ANDROID] Guess the Celeb App

Leave a Comment
package com.example.cw.guesstheceleb;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
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 android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

    Button option1;
    Button option2;
    Button option3;
    Button option4;
    ImageView imageView;
    ArrayList <String> celebURLs;
    ArrayList <String> celebNames;
    Random rand;
    int totalCelebs,chosenCelebIndex,chosenOptionIndex;
    String[] options = new String[4];

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

        @Override        protected String doInBackground(String... urls) {
            URL url;
            HttpURLConnection connection=null;
            String result="";
            try            {
                url = new URL(urls[0]);
                connection = (HttpURLConnection) url.openConnection();
                InputStream in = connection.getInputStream();
                InputStreamReader reader = new InputStreamReader(in);

                int data = reader.read();
                while (data!=-1)
                {
                    char ch = (char)data;
                    result+=ch;
                    data = reader.read();
                }
                return result;
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return null;
            }
        }
    }

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

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

            URL url;
            HttpURLConnection connection;
            try            {
                url = new URL(urls[0]);
                connection = (HttpURLConnection)url.openConnection();
                connection.connect();
                InputStream in = connection.getInputStream();

                Bitmap image = BitmapFactory.decodeStream(in);

                return image;
            }catch(Exception e)
            {
                e.printStackTrace();
                Log.i("Inside task class","Image downloading failed");
                return null;
            }

        }
    }

    public void optionClicked(View view)
    {
        Button buttonClicked = (Button)view;
        int userChoice = Integer.parseInt(buttonClicked.getTag().toString());
        if(userChoice==chosenOptionIndex){
            Toast.makeText(this, "Correct!", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(this, "Incorrect! Correct answer is "+celebNames.get(chosenCelebIndex), Toast.LENGTH_SHORT).show();
        }
        setupQuiz();
    }

    public void setupQuiz() {
        ImageDownloader imgTask = new ImageDownloader();
        chosenCelebIndex = rand.nextInt(totalCelebs);
        chosenOptionIndex = rand.nextInt(4);
        try {
            for (int i = 0; i < 4; i++) {
                if (i == chosenOptionIndex) {
                    options[i] = celebNames.get(chosenCelebIndex);
                } else {
                    int wrongCelebNameIndex = rand.nextInt(totalCelebs);
                    while (wrongCelebNameIndex == chosenCelebIndex) wrongCelebNameIndex = rand.nextInt(totalCelebs);
                    options[i] = celebNames.get(wrongCelebNameIndex);
                }
            }
            option1.setText(options[0]);
            option2.setText(options[1]);
            option3.setText(options[2]);
            option4.setText(options[3]);

            Bitmap image = imgTask.execute(celebURLs.get(chosenCelebIndex)).get();
            Log.i("URL chosen",celebURLs.get(chosenCelebIndex));
            imageView.setImageBitmap(image);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

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

        option1 = (Button) findViewById(R.id.option1);
        option2 = (Button) findViewById(R.id.option2);
        option3 = (Button) findViewById(R.id.option3);
        option4 = (Button) findViewById(R.id.option4);

        imageView = (ImageView)findViewById(R.id.imageView);

        celebURLs = new ArrayList<>();
        celebNames = new ArrayList<>();

        rand = new Random();

        InfoDownloader task = new InfoDownloader();
        try {
            String result = task.execute("http://www.posh24.se/kandisar").get();

            String[] strs = result.split("<a href=\"/kandisar/a_till_o\" class=\"link\">Kändisar A-Ö</a>");
            String html = strs[1];

            Pattern p = Pattern.compile("<img src=\"(.*?)\"");
            Matcher m = p.matcher(html);

            while(m.find())
            {
                celebURLs.add(m.group(1));
            }

            p = Pattern.compile("alt=\"(.*?)\"");
            m = p.matcher(html);

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

            totalCelebs = celebNames.size();

            Log.i("No of URLs",celebURLs.size()+""); //28            Log.i("No of Namess",celebNames.size()+""); //23
            setupQuiz();

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


/////////////////////////////////////////////////////////////////////////////
// Design
//////////////////////////////////////////////////////////////////////////////


<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">

    <ImageView        android:id="@+id/imageView"        android:layout_width="0dp"        android:layout_height="0dp"        android:layout_marginBottom="5dp"        android:layout_marginEnd="5dp"        android:layout_marginLeft="5dp"        android:layout_marginRight="5dp"        android:layout_marginStart="5dp"        android:layout_marginTop="5dp"        app:layout_constraintBottom_toTopOf="@+id/option1"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent" />

    <Button        android:id="@+id/option1"        android:layout_width="368dp"        android:layout_height="wrap_content"        android:layout_marginBottom="1dp"        android:layout_marginEnd="8dp"        android:layout_marginLeft="8dp"        android:layout_marginRight="8dp"        android:layout_marginStart="8dp"        android:layout_marginTop="5dp"        android:onClick="optionClicked"        android:tag="0"        android:text="option1"        app:layout_constraintBottom_toTopOf="@+id/option2"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintHorizontal_bias="0.0"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <Button        android:id="@+id/option2"        android:layout_width="368dp"        android:layout_height="wrap_content"        android:layout_marginBottom="1dp"        android:layout_marginEnd="8dp"        android:layout_marginLeft="8dp"        android:layout_marginRight="8dp"        android:layout_marginStart="8dp"        android:layout_marginTop="1dp"        android:onClick="optionClicked"        android:tag="1"        android:text="option2"        app:layout_constraintBottom_toTopOf="@+id/option3"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintHorizontal_bias="0.0"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toBottomOf="@+id/option1" />

    <Button        android:id="@+id/option3"        android:layout_width="368dp"        android:layout_height="wrap_content"        android:layout_marginBottom="1dp"        android:layout_marginEnd="8dp"        android:layout_marginLeft="8dp"        android:layout_marginRight="8dp"        android:layout_marginStart="8dp"        android:layout_marginTop="1dp"        android:onClick="optionClicked"        android:tag="2"        android:text="option3"        app:layout_constraintBottom_toTopOf="@+id/option4"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintHorizontal_bias="0.0"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toBottomOf="@+id/option2" />

    <Button        android:id="@+id/option4"        android:layout_width="368dp"        android:layout_height="wrap_content"        android:layout_marginBottom="16dp"        android:layout_marginEnd="8dp"        android:layout_marginLeft="8dp"        android:layout_marginRight="8dp"        android:layout_marginStart="8dp"        android:layout_marginTop="1dp"        android:onClick="optionClicked"        android:tag="3"        android:text="option4"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintHorizontal_bias="0.5"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toBottomOf="@+id/option3" />

</android.support.constraint.ConstraintLayout>
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment