알고리즘

Android Project - LottoHelper

이온시옥 2018. 12. 6. 05:41
반응형

핵심구현

Zxing(Zebra Crossing) Library - QR코드 스캔

AsyncTask class 사용하여 서버 접근 -  Json을 넘겨주는 서버에 접속하여 값을 가져옴

openFileOutput 함수를 사용하여 내부 스토리지에 파일 write 및 read


중복되는코드가 많고... 코드가 너무 더럽다... 너무시간에재촉되나보니...덕지덕지짠거같다...ㅎㅎ


MainActivity.java

public class MainActivity extends AppCompatActivity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        Button random_button = (Button) findViewById(R.id.button); //랜덤번호 생성

        Button check_button = (Button) findViewById(R.id.button2); //번호 입력하기

        Button history_button = (Button) findViewById(R.id.button3); //지난회차 조회

        Button myinfo_button = (Button) findViewById(R.id.button4); //나의 정보


        random_button.setOnClickListener(new View.OnClickListener() { //랜덤번호

            //버튼을 누르면 인텐트 날리기

            @Override

            public void onClick(View view) { //랜덤번호를 클릭할 경우

                Intent intent = new Intent(MainActivity.this, RandomActivity.class);

                startActivity(intent);

            }

        });


        check_button.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, CheckActivity.class);

                startActivity(intent);

            }

        });


        history_button.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, HistoryActivity.class);

                startActivity(intent);

            }

        });


        myinfo_button.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, MyInfoActivity.class);

                startActivity(intent);

            }

        });


    }

}


CheckActivity.java

public class CheckActivity extends AppCompatActivity {

    String [] Qr_token;

    boolean numberIsSaved;

    boolean qrIsSaved;


    StringBuffer buffer = new StringBuffer();


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_check);


        final EditText episode_num = (EditText) findViewById(R.id.checkEditText0);

        final EditText[] numbers = new EditText[6];

        numbers[0] = (EditText) findViewById(R.id.checkEditText1);

        numbers[1] = (EditText) findViewById(R.id.checkEditText2);

        numbers[2] = (EditText) findViewById(R.id.checkEditText3);

        numbers[3] = (EditText) findViewById(R.id.checkEditText4);

        numbers[4] = (EditText) findViewById(R.id.checkEditText5);

        numbers[5] = (EditText) findViewById(R.id.checkEditText6);


        Button qrStartButton = (Button) findViewById(R.id.buttonQRscan);

        Button saveButton = (Button) findViewById(R.id.buttonSaveButton);

        Button resultButton = (Button) findViewById(R.id.buttonResultButton);


        qrStartButton.setOnClickListener(new View.OnClickListener() { //QR스캔 버튼을 클릭할 경우

            @Override

            public void onClick(View view) {

                startQRCode(); //QR스캔 시작! 카메라띄움

            }

        });


        saveButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                boolean okay = false;

                numberIsSaved = false;

                qrIsSaved = false;


                String string_cehck = episode_num.getText().toString();

                if (string_cehck.matches("")) {

                    ErrorDisplay("회차가 입력되지 않았습니다!!");

                    return;

                }

                for (int i=0; i<6; i++) {

                    string_cehck = numbers[i].getText().toString();

                    if (string_cehck.matches("")) {

                        ErrorDisplay("입력되지 않은 숫자가 있습니다!! 6개 모두 입력해주세요!");

                        numbers[i].selectAll();

                        return;

                    }

                }


                final int epNum = Integer.parseInt(episode_num.getText().toString());


                int[] num_arr = new int[6];

                num_arr[0] = Integer.parseInt(numbers[0].getText().toString());

                num_arr[1] = Integer.parseInt(numbers[1].getText().toString());

                num_arr[2] = Integer.parseInt(numbers[2].getText().toString());

                num_arr[3] = Integer.parseInt(numbers[3].getText().toString());

                num_arr[4] = Integer.parseInt(numbers[4].getText().toString());

                num_arr[5] = Integer.parseInt(numbers[5].getText().toString());


                final ArrayList<Integer> array = new ArrayList<Integer> (); //6개의 번호를 담는 arraylist


                for (int i=0; i<6; i++) {

                    if( 0 < num_arr[i] && num_arr[i] < 46) {

                        array.add(num_arr[i]);

                        okay = true;

                    }

                    else {

                        ErrorDisplay("1 ~ 45 사이의 숫자만 입력할 수 있습니다! 다시 입력해주세요!");

                        okay = false;

                        return;

                    }

                }


                if (okay == true) {

                    Collections.sort(array); //정렬


                    String confirm = Integer.toString(epNum)+"회 "+ Integer.toString(array.get(0)) + ", "+ Integer.toString(array.get(1)) + ", "

                                    + Integer.toString(array.get(2)) + ", "+ Integer.toString(array.get(3)) + ", "

                                    + Integer.toString(array.get(4)) + ", "+ Integer.toString(array.get(5)) + " 맞습니까?";


                    AlertDialog.Builder builder = new AlertDialog.Builder(CheckActivity.this);

                    builder.setTitle("확인") //대화상자의 제목 설정

                            .setMessage(confirm)

                            .setPositiveButton("확인", new DialogInterface.OnClickListener() { //확인을 누룰때 처리하는 코드 (포맷형식 변환 & 저장)

                                @Override

                                public void onClick(DialogInterface dialog, int which) {

                                    //포맷형식 생성

                                    //"000-010203040506"; 회차와 6개숫자로 구성

                                    String format = Integer.toString(epNum) + "-";

                                    for (int i=0; i<6; i++) {

                                        int num = array.get(i);

                                        if(num < 10) {

                                            format = format + "0" + Integer.toString(num);

                                        }

                                        else  {

                                            format = format + Integer.toString(num);

                                        }

                                    }

                                    Log.i("CheckActvity:", "번호저장전 " + format + " 생성됨"); //로그 기록!


                                    //저장진행!!

                                    buffer.append(format).append(";");

                                    try { //앱 내부 파일로 번호를 저장

                                        FileOutputStream fileOutput = openFileOutput("CheckNum", Context.MODE_PRIVATE);

                                        fileOutput.write(buffer.toString().getBytes());

                                        fileOutput.close();

                                        numberIsSaved = true;


                                        Toast toast = Toast.makeText(getApplicationContext(), "저장 완료하였습니다!", Toast.LENGTH_LONG);

                                        toast.show();

                                        for (int i=0; i<6; i++) {

                                            numbers[i].getText().clear(); // 저장이 완료되면 숫자들 모두 싹지우기, 회차는 그대로놓아둠 (사용자편의를 위해서.)

                                        }

                                    } catch (IOException e) { }


                                }

                            })

                            .setNegativeButton("취소", new DialogInterface.OnClickListener() {

                                @Override

                                public void onClick(DialogInterface dialog, int which) {

                                    Toast toast = Toast.makeText(getApplicationContext(), "저장 취소하였습니다.", Toast.LENGTH_LONG);

                                    toast.show();

                                    return;

                                }

                            })

                            .create() //다이얼로그생성

                            .show(); // 보여주기


                }

            }

        });


        resultButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                if (qrIsSaved || numberIsSaved) {

                    Intent intent = new Intent(CheckActivity.this, ResultActivity.class);

                    qrIsSaved = false;

                    numberIsSaved = false;

                    startActivity(intent);

                }

                else {

                    ErrorDisplay("QR코드 스캔하거나 직접 회차와 번호를 입력 후에 '결과보기'를 눌려주세요!");

                }

            }

        });



    }


    public void startQRCode() {

        new IntentIntegrator(this).initiateScan();

    }


    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == IntentIntegrator.REQUEST_CODE) {

            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

            if (result == null) {

                Toast.makeText(this, "QR코드 스캔을 취소합니다.", Toast.LENGTH_LONG).show();

            }

            else {

                Toast.makeText(this, "QR코드 스캔에 성공하였습니다. " + result.getContents(), Toast.LENGTH_LONG).show();

                final String QR_data = result.getContents(); //QR주소 저장.


                if(QrProcessing(QR_data) == true) { //QR주소로부터 각각의 횟차, 게임횟수등을 qr_token에 저장하는 처리.


                    //QR코드 코드를 불러와서, QR TOKEN을 사용한 저장? or 취소 처리하기위한 AlertDialog.Builder

                        String confirm = Qr_token[0]+"회, " + Integer.toString(Qr_token.length-1) + "판: ";

                        for (int i=1; i<Qr_token.length; i++) {

                            confirm = confirm + "(" + twoByTwo(Qr_token[i]) + ") ";

                        }


                        AlertDialog.Builder builder = new AlertDialog.Builder(CheckActivity.this);



                        builder.setTitle("QR코드 정보확인") //대화상자의 제목 설정

                                .setMessage(confirm)

                                .setPositiveButton("저장", new DialogInterface.OnClickListener() { //AlertDialog에서 확인을 누를 경우!

                                    @Override

                                    public void onClick(DialogInterface dialog, int which) {

                                        for (int i=1; i<Qr_token.length; i++) {

                                            //포맷형식 생성

                                            //"000-010203040506"; 회차와 6개숫자로 구성

                                            String format = Qr_token[0].substring(1,4) + "-" + Qr_token[i];

                                            Log.v("CheckActvity:", "번호저장전 " + format + " 생성됨"); //로그 기록!

                                            buffer.append(format).append(";");

                                            try { //앱 내부 파일로 번호를 저장

                                                FileOutputStream fileOutput = openFileOutput("CheckNum", Context.MODE_PRIVATE);

                                                fileOutput.write(buffer.toString().getBytes());

                                                fileOutput.close();

                                                qrIsSaved = true;

                                            } catch (IOException e) { }


                                        }

                                        Toast toast = Toast.makeText(getApplicationContext(), "QR코드 저장 완료!!", Toast.LENGTH_LONG);

                                        toast.show();

                                    }

                                })

                                .setNegativeButton("취소", new DialogInterface.OnClickListener() { //AlertDialog에서 취소를 누를 경우!

                                    @Override

                                    public void onClick(DialogInterface dialog, int which) {

                                        Toast toast = Toast.makeText(getApplicationContext(), "QR코드 저장 취소!!", Toast.LENGTH_LONG);

                                        toast.show();

                                        return;

                                    }

                                })

                                .create() //다이얼로그생성

                                .show(); // 보여주기



                    //QR코드 코드를 불러와서, QR TOKEN을 사용한 저장? or 취소 처리하기위한 AlertDialog.Builder 끝끝끝끝끝끝끝끝끝

                }

            }

        }

        else {

            super.onActivityResult(requestCode, resultCode, data);

        }

    }


    private boolean QrProcessing(String QR_data) {

        //"http://qr.645lotto.net/?v=0649q182125373839q040728303235q032122334142q011130333841q0313192736390000002379\n"

        String temp = QR_data.replace("http://qr.nlotto.co.kr/?v=", "");

        if (temp.equals(QR_data)) {

            android.util.Log.v("CheckActivity -> Qr_Processing()", " \"http://qr.nlotto.co.kr/?v=\"로 시작하지 않는 QR코드... ");

            return false;

        }

        Qr_token = temp.split("q");

        /*

            token[0] → 회차

            token[1] → 첫번째 (6개 숫자)

            token[2] → 두번째

            token[3] → 세번쨰

            token[4] → 네번째

            token[5] → 다섯번째

            **항상 제일마지막은 ex"0000 0023 79" 10자리 숫자가 붙어있음 잘라야함.

         */


        StringBuilder str = new StringBuilder( Qr_token[Qr_token.length-1]); //마지막 번째의 숫자 뒤에 숫자를 짜르기위한 StringBuiler

        str.delete(12, 22); // 12~22 인덱스의 char 삭제

        Qr_token[Qr_token.length-1] = str.toString(); //숫자를 자르고 정상적인 번호들만 저장.


        if ( Qr_token.length < 6 && Qr_token[0].length() != 4) { //QR코드토큰이 6이상이면 에러 (최대 5개 게임 + 횟수정보 == 5인덱스) && 첫번째 토큰의 정보는 횟수! 횟수는 최대 4자리 숫자 ex0348

            return false;

        }

        for (int i=1; i<6; i++) {

            if(Qr_token[i].length() != 12) {

                return false;

            }

        }

        if(Qr_token.length < 7 && Qr_token[Qr_token.length-1].length() == 12 ) {

            return true;

        }

        return false;

    }


    private void ErrorDisplay(String message) {

            AlertDialog.Builder builder = new AlertDialog.Builder(CheckActivity.this);

            builder.setTitle("에러")//대화상자의 제목 설정

                    .setMessage(message)

                    .setPositiveButton("확인",null)

                    .create() //다이얼로그생성

                    .show(); // 보여주기

    }


    private String twoByTwo(String len12) {

        String result = len12.substring(0,2) + "," + len12.substring(2,4) + "," + len12.substring(4,6) + "," + len12.substring(6,8) + "," + len12.substring(8,10) + "," + len12.substring(10,12);

        return result;

    }

}


ResultActivity.java

public class ResultActivity extends AppCompatActivity {

    ProgressDialog pd;

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

    String foundResultConvertedBonus;

    String foundResultConvertedDate;

    String foundResultConvertedEpisode;


    String jsonData;

    String[] buffer;

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

    String usersEpisode;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_result);

        TextView textViewResult = (TextView) findViewById(R.id.textViewResult);

        Button buttonGoBack = (Button) findViewById(R.id.buttonGoBack);


        buttonGoBack.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                finish();

            }

        });



        //데이터 불러오기

        try{

            FileInputStream fileInput= openFileInput("CheckNum");

            byte[] datas= new byte[fileInput.available()];

            if(fileInput.read(datas)!=-1) { //FileInputStream의 데이터가 바이트 형태인 datas 객체로 옮겨지면

                fileInput.close(); //FileInputStream을 닫는다.

                buffer = (new String(datas)).split(";"); //데이터 문자열을 ','로 분리하여 배열에 넣는다

            }

        }

        catch(IOException e){ }



        for (int i=0; i<buffer.length; i++) { //저장된 번호만큼 진행!

            //textViewResult.append(buffer[i] + "\n");

            usersEpisode = buffer[i].substring(0, 3);

            usersNumbers.add(buffer[i].substring(4, 6));

            usersNumbers.add(buffer[i].substring(6, 8));

            usersNumbers.add(buffer[i].substring(8, 10));

            usersNumbers.add(buffer[i].substring(10, 12));

            usersNumbers.add(buffer[i].substring(12, 14));

            usersNumbers.add(buffer[i].substring(buffer[i].length() - 2, buffer[i].length()));


            if (!usersEpisode.equals(foundResultConvertedEpisode)) { //회차 검색진행

                //json 가져오기.

                String urlString = "http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=" + usersEpisode;


                //new ResultActivity.JsonTask().execute(urlString);

                try {

                    jsonData = new JsonTask().execute(urlString).get();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                } catch (ExecutionException e) {

                    e.printStackTrace();

                }


                //jsonResult를 분석하여 6개의번호, 날짜, 횟차를 subString으로 쪼개어 가져옴.

                if (SearchResult(jsonData)) { //정상적으로 가지고왔으면 결과를 보여주기.

                    Toast toast = Toast.makeText(getApplicationContext(), "서버로부터 데이터를 정상적으로 가져왔습니다!", Toast.LENGTH_SHORT);

                    toast.show();

                }


                textViewResult.append(foundResultConvertedEpisode + "회 (" + foundResultConvertedDate + ") 당첨번호\n  " +

                        foundResultConvertedNumbers.get(0) + ", " + foundResultConvertedNumbers.get(1) + ", " + foundResultConvertedNumbers.get(2) + ", " +

                        foundResultConvertedNumbers.get(3) + ", " + foundResultConvertedNumbers.get(4) + ", " + foundResultConvertedNumbers.get(5) +

                        " + " + foundResultConvertedBonus + "\n\n 나의 번호\n");

            }


            if (usersEpisode.equals(foundResultConvertedEpisode)) {

                StringBuffer MyBuffer = new StringBuffer();

                MyBuffer.append(usersEpisode + "회: " + usersNumbers.get(0) + ","+ usersNumbers.get(1) + ","+ usersNumbers.get(2) + ","

                                                    + usersNumbers.get(3) + ","+ usersNumbers.get(4) + ","+ usersNumbers.get(5) + " - ");


                int collect = 0;

                boolean bonus = false;

                for (int j = 0; j < 6; j++) {

                    for (int k = 0; k < 6; k++) {

                        if (usersNumbers.get(j).equals(foundResultConvertedNumbers.get(k))) {

                            collect++;

                            break;

                        }

                        if (usersNumbers.get(j).equals(foundResultConvertedBonus)) {

                            bonus = true;

                            break;

                        }

                    }

                }

                textViewResult.append("   " + usersNumbers.get(0) + ", " + usersNumbers.get(1) + ", " + usersNumbers.get(2) + ", " +

                        usersNumbers.get(3) + ", " + usersNumbers.get(4) + ", " + usersNumbers.get(5) + " --> ");


                if (collect < 3) {

                    textViewResult.append("낙점. (" + Integer.toString(collect) + "개 동일)\n");

                    MyBuffer.append("낙점;");

                } else if (collect == 3) {

                    textViewResult.append("5등!! (3개 동일!)\n");

                    MyBuffer.append("5등;");

                } else if (collect == 4) {

                    textViewResult.append("4등!! (4개 동일!)\n");

                    MyBuffer.append("4등;");

                } else if (collect == 5 && !bonus) {

                    textViewResult.append("3등!! (5개 동일!!)\n");

                    MyBuffer.append("3!등;");

                } else if (collect == 5 && bonus) {

                    textViewResult.append("2등!! (5개 + 보너스 동일!!)\n");

                    MyBuffer.append("2등!!;");

                } else if (collect == 6) {

                    textViewResult.append("1등!! (6개 모두 동일!!)\n");

                    MyBuffer.append("1등!!!;");

                }

                try{ //앱 내부 파일로 번호를 저장

                    FileOutputStream fileOutput = openFileOutput("MyNumbers", MODE_APPEND);

                    fileOutput.write(MyBuffer.toString().getBytes());

                    fileOutput.close();

                    Toast toast = Toast.makeText(getApplicationContext(), "번호가 저장되었습니다!", Toast.LENGTH_SHORT);

                    toast.show();

                }catch (IOException e) { }

            }


            usersNumbers.clear();

        }

        try{ //저장된 것을 0으로 덮어씌우기

            FileOutputStream fileOutput = openFileOutput("CheckNum", Context.MODE_PRIVATE);

            fileOutput.write(00000000); //CheckNum에 0으로 덮어씌우기 (기존 번호들 모두 지움)

            fileOutput.close();

        }

        catch (IOException e) { }


    }


    private class JsonTask extends AsyncTask<String, String, String> {


        protected void onPreExecute() {

            super.onPreExecute();


            pd = new ProgressDialog(ResultActivity.this);

            pd.setMessage("Please wait");

            pd.setCancelable(false);

            pd.show();

        }


        protected String doInBackground(String... params) {

            HttpURLConnection connection = null;

            BufferedReader reader = null;


            try {

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

                connection = (HttpURLConnection) url.openConnection();

                connection.connect();

                InputStream stream = connection.getInputStream();

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


                StringBuffer buffer = new StringBuffer();

                String line = "";


                while ((line = reader.readLine()) != null) {

                    buffer.append(line+"\n");

                    Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-)

                }

                return buffer.toString();

            } catch (MalformedURLException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();

            } finally {

                if (connection != null) {

                    connection.disconnect();

                }

                try {

                    if (reader != null) {

                        reader.close();

                    }

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return null;

        }

        @Override

        protected void onPostExecute(String result) {

            super.onPostExecute(result);

            if (pd.isShowing()) {

                pd.dismiss();

            }

            if(result==null) {

                AlertDisplay("에러","데이터나 WiFi에 연결이되지 않았거나, 서버로부터 응답이없습니다!!");

            }

            else { //접속이 원할이잘되고 결과를 jsonResult에 얻음.

                jsonData=new String(result.toString());

            }

        }

    }


    private void AlertDisplay(String tittle, String message) {

        AlertDialog.Builder builder = new AlertDialog.Builder(ResultActivity.this);

        builder.setTitle(tittle)//대화상자의 제목 설정

                .setMessage(message)

                .setPositiveButton("확인",null)

                .create() //다이얼로그생성

                .show(); // 보여주기

    }


    private boolean SearchResult(String jsonData) {

        if (jsonData.contains("\"returnValue\":\"success\"")) { //제대로된 정보가 들어왔다는 뜻!

            int check = 0;

            String [] token = jsonData.split(",");

            for (int i=0; i<token.length-1; i++) {

                if(token[i].contains("\"bnusNo\"")) {

                    foundResultConvertedBonus = token[i].substring(token[i].length()-2,token[i].length());

                    check++;

                }

                else if(token[i].contains("\"drwtNo1\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwtNo2\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwtNo3\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwtNo4\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwtNo5\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwtNo6\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwNoDate\"")) {

                    foundResultConvertedDate = token[i].substring(13,23);

                    //13, 23

                    check++;

                }

                else if(token[i].contains("\"drwNo\"")) {

                    foundResultConvertedEpisode = token[i].substring(token[i].length()-3,token[i].length());

                    check++;

                }

            }


            foundResultConvertedBonus.replace(":", "0");

            for(int i=0; i<6; i++) {

                String temp = foundResultConvertedNumbers.get(i).replace(":", "0");

                foundResultConvertedNumbers.set(i, temp);

            }

            Collections.sort(foundResultConvertedNumbers); //정렬


            if (check == 9) {

                return true;

            }

            return false;

        }

        else if (jsonData.contains("\"returnValue\":\"fail\"")) {

            AlertDisplay("에러", "올바른 회차가 아니거나, 아직 결과가 나오지않은 회차입니다!");

        }

        else {

            AlertDisplay("에러","올바르지 않는 요청이거나 서버가 작동하지않습니다. 잠시후에 다시시도해주세요!");

        }

        return false;

    }


}


HistoryActivity.java

public class HistoryActivity extends AppCompatActivity {


    String urlString;

    Button okayButton;

    EditText userTextInput;


    ProgressDialog pd;

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

    String foundResultConvertedBonus;

    String foundResultConvertedDate;

    String foundResultConvertedEpisode;




    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_history);


        okayButton = (Button) findViewById(R.id.historyOkayButton);

        userTextInput = (EditText) findViewById(R.id.historyEditText);


        okayButton.setOnClickListener(new View.OnClickListener() { //회차의 확인을 눌렀을때.

            @Override

            public void onClick(View view) {

                String value = userTextInput.getText().toString();


                if(value.isEmpty()) { //회차 정보를 입력하지 않았다면...

                    AlertDisplay("에러","회차를 입력해주세요!!");

                }

                else { //회차를 입력했다면

                    int episode_number = Integer.parseInt(value);

                    if ( 0 < episode_number) {

                        urlString = "http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=" + value;

                        new JsonTask().execute(urlString);

                    }

                    else {

                        AlertDisplay("에러", "잘못된 숫자입니다!! 다시입력해주세요!");

                    }

                }

            }

        });

    }


    private class JsonTask extends AsyncTask<String, String, String> {


        protected void onPreExecute() {

            super.onPreExecute();


            pd = new ProgressDialog(HistoryActivity.this);

            pd.setMessage("Please wait");

            pd.setCancelable(false);

            pd.show();

        }


        protected String doInBackground(String... params) {



            HttpURLConnection connection = null;

            BufferedReader reader = null;


            try {

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

                connection = (HttpURLConnection) url.openConnection();

                connection.connect();



                InputStream stream = connection.getInputStream();


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


                StringBuffer buffer = new StringBuffer();

                String line = "";


                while ((line = reader.readLine()) != null) {

                    buffer.append(line+"\n");

                    Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-)

                }

                return buffer.toString();

            } catch (MalformedURLException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();

            } finally {

                if (connection != null) {

                    connection.disconnect();

                }

                try {

                    if (reader != null) {

                        reader.close();

                    }

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return null;

        }

        @Override

        protected void onPostExecute(String result) {

            super.onPostExecute(result);

            if (pd.isShowing()) {

                pd.dismiss();

            }

            if(result==null) {

                AlertDisplay("에러","데이터나 WiFi에 연결이되지 않았거나, 서버로부터 응답이없습니다!!");

            }

            else { //접속이 원할이잘되고 결과를 jsonResult에 얻음.


                //jsonResult를 분석하여 6개의번호, 날짜, 횟차를 subString으로 쪼개어 가져옴.

                if (SearchResult(result)) { //정상적으로 가지고왔으면 결과를 보여주기.

                    AlertDisplay(foundResultConvertedEpisode+"회 검색결과",

                            "날짜:     " + foundResultConvertedDate+ "\n" +

                                    "번호:     "+foundResultConvertedNumbers.get(0)+" "+ foundResultConvertedNumbers.get(1)+" "+foundResultConvertedNumbers.get(2)+" "

                                    +foundResultConvertedNumbers.get(3)+" "+ foundResultConvertedNumbers.get(4)+" "+foundResultConvertedNumbers.get(5)+"\n"+

                                    "보너스:  " + foundResultConvertedBonus );

                }

            }

        }

    }

    private void AlertDisplay(String tittle, String message) {

        AlertDialog.Builder builder = new AlertDialog.Builder(HistoryActivity.this);

        builder.setTitle(tittle)//대화상자의 제목 설정

                .setMessage(message)

                .setPositiveButton("확인",null)

                .create() //다이얼로그생성

                .show(); // 보여주기

    }


    private boolean SearchResult(String jsonData) {

        if (jsonData.contains("\"returnValue\":\"success\"")) { //제대로된 정보가 들어왔다는 뜻!

            int check = 0;

            String [] token = jsonData.split(",");

            for (int i=0; i<token.length-1; i++) {

                if(token[i].contains("\"bnusNo\"")) {

                    foundResultConvertedBonus = token[i].substring(token[i].length()-2,token[i].length());

                    check++;

                }

                else if(token[i].contains("\"drwtNo1\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwtNo2\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwtNo3\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwtNo4\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwtNo5\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwtNo6\"")) {

                    foundResultConvertedNumbers.add(token[i].substring(token[i].length()-2,token[i].length()));

                    check++;

                }

                else if(token[i].contains("\"drwNoDate\"")) {

                    foundResultConvertedDate = token[i].substring(13,23);

                    //13, 23


                    check++;

                }

                else if(token[i].contains("\"drwNo\"")) {

                    foundResultConvertedEpisode = token[i].substring(token[i].length()-3,token[i].length());

                    check++;

                }

            }


            foundResultConvertedBonus.replace(":", "0");

            for(int i=0; i<6; i++) {

                String temp = foundResultConvertedNumbers.get(i).replace(":", "0");

                foundResultConvertedNumbers.set(i, temp);

            }

            Collections.sort(foundResultConvertedNumbers); //정렬


            if (check == 9) {

                return true;

            }

            return false;

        }

        else if (jsonData.contains("\"returnValue\":\"fail\"")) {

            AlertDisplay("에러", "올바른 회차가 아니거나, 아직 결과가 나오지않은 회차입니다!");

        }

        else {

            AlertDisplay("에러","올바르지 않는 요청이거나 서버가 작동하지않습니다. 잠시후에 다시시도해주세요!");

        }

        return false;

    }

}


MyInfoActivity.java

public class MyInfoActivity extends AppCompatActivity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_my_info);


        ArrayAdapter[] adapter = new ArrayAdapter[1];

        Button remove_button = (Button) findViewById(R.id.myinfo_savednum_remove_button);

        final ListView myinfo_random_listview = (ListView) findViewById(R.id.myinfo_random_listview);


        //데이터 불러오기

        try{

            FileInputStream fileInput= openFileInput("SavedRandomNum");

            byte[] datas= new byte[fileInput.available()];

            if(fileInput.read(datas)!=-1){ //FileInputStream의 데이터가 바이트 형태인 datas 객체로 옮겨지면

                fileInput.close(); //FileInputStream을 닫는다.


                String[] buffer=(new String(datas)).split(","); //데이터 문자열을 ','로 분리하여 배열에 넣는다


                if (buffer[0].length() < 6) { //저장된 번호가 없다면... 리스트뷰 인비져블

                    myinfo_random_listview.setVisibility(View.INVISIBLE);

                }

                else {

                    adapter[0] = new ArrayAdapter(this, android.R.layout.simple_list_item_1,buffer);

                    myinfo_random_listview.setAdapter(adapter[0]);

                }

            }

        } catch(IOException e){ }


        remove_button.setOnClickListener(new View.OnClickListener() { //랜덤번호

            //버튼을 누르면 인텐트 날리기

            @Override

            public void onClick(View view) { //삭제버튼을 클릭할 경우


                try{ //저장된 것을 0으로 덮어씌우기

                    FileOutputStream fileOutput = openFileOutput("SavedRandomNum", Context.MODE_PRIVATE);

                    fileOutput.write(0); //SavedNum에 0으로 덮어씌우기 (기존 번호들 모두 지움)

                    fileOutput.close();


                    myinfo_random_listview.setVisibility(View.INVISIBLE); //리스트뷰 인비져블 처리


                    Toast toast = Toast.makeText(getApplicationContext(), "모두 삭제되었습니다!", Toast.LENGTH_SHORT);

                    toast.show();

                }catch (IOException e) { }

            }

        });


        ArrayAdapter[] adapterH = new ArrayAdapter[1];

        Button removeH_button = (Button) findViewById(R.id.myinfo_history_remove_button);

        final ListView historyListview = (ListView) findViewById(R.id.myinfo_history_listview);


        //데이터 불러오기

        try{

            FileInputStream fileInput= openFileInput("MyNumbers");

            byte[] datas= new byte[fileInput.available()];

            if(fileInput.read(datas)!=-1){ //FileInputStream의 데이터가 바이트 형태인 datas 객체로 옮겨지면

                fileInput.close(); //FileInputStream을 닫는다.


                String[] buffer=(new String(datas)).split(";"); //데이터 문자열을 ','로 분리하여 배열에 넣는다


                if (buffer[0].length() < 6) { //저장된 번호가 없다면... 리스트뷰 인비져블

                    historyListview.setVisibility(View.INVISIBLE);

                }

                else {

                    adapterH[0] = new ArrayAdapter(this, android.R.layout.simple_list_item_1,buffer);

                    historyListview.setAdapter(adapterH[0]);

                }

            }

        } catch(IOException e){ }



        removeH_button.setOnClickListener(new View.OnClickListener() { //랜덤번호

            //버튼을 누르면 인텐트 날리기

            @Override

            public void onClick(View view) { //삭제버튼을 클릭할 경우


                try{ //저장된 것을 0으로 덮어씌우기

                    FileOutputStream fileOutput = openFileOutput("MyDatas", Context.MODE_PRIVATE);

                    fileOutput.write(0); //SavedNum에 0으로 덮어씌우기 (기존 번호들 모두 지움)

                    fileOutput.close();


                    historyListview.setVisibility(View.INVISIBLE); //리스트뷰 인비져블 처리


                    Toast toast = Toast.makeText(getApplicationContext(), "모두 삭제되었습니다!", Toast.LENGTH_SHORT);

                    toast.show();

                }catch (IOException e) { }

            }

        });

    }

}


RandomActivity.java

public class RandomActivity extends AppCompatActivity {

    ArrayList<Integer> array = new ArrayList<Integer> (); //6개의 번호를 담는 arraylist

    StringBuffer buffer = new StringBuffer();


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_random);


        Button button_regen = (Button) findViewById(R.id.button_random_regen);

        Button button_save = (Button) findViewById(R.id.button_random_save);


        final TextView[] num = new TextView[6];

        num[0] = (TextView) findViewById(R.id.textView_rand_num1);

        num[1] = (TextView) findViewById(R.id.textView_rand_num2);

        num[2] = (TextView) findViewById(R.id.textView_rand_num3);

        num[3] = (TextView) findViewById(R.id.textView_rand_num4);

        num[4] = (TextView) findViewById(R.id.textView_rand_num5);

        num[5] = (TextView) findViewById(R.id.textView_rand_num6);

        final boolean[] already_saved = {false};


        Intent intent = getIntent();

        random_gen();

        for(int i=0; i<6; i++) {

            num[i].setText(Integer.toString(array.get(i)));

        }


        button_regen.setOnClickListener(new View.OnClickListener() { //다시생성하기 버튼을 클릭할 경우

            @Override

            public void onClick(View v) {

                array.clear();

                random_gen();

                for(int i=0; i<6; i++) {

                    num[i].setText(Integer.toString(array.get(i)));

                }

                already_saved[0]=false;

            }

        });


        button_save.setOnClickListener(new View.OnClickListener() { //저정하기 버튼을 클릭할 경우

            @Override

            public void onClick(View v) {

                if (already_saved[0]) { //이미 저장이 되었다면

                    Toast toast = Toast.makeText(getApplicationContext(), "이미 번호가 저장되었습니다!", Toast.LENGTH_SHORT);

                    toast.show();

                }

                else { //저장이 안되어진 번호라면

                    buffer.append(array.get(0)).append(" ").append(array.get(1)).append(" ")

                            .append(array.get(2)).append(" ").append(array.get(3)).append(" ")

                            .append(array.get(4)).append(" ").append(array.get(5)).append("\n");

                    try{ //앱 내부 파일로 번호를 저장

                        FileOutputStream fileOutput = openFileOutput("SavedRandomNum", MODE_APPEND);

                        fileOutput.write(buffer.toString().getBytes());

                        fileOutput.close();

                        Toast toast = Toast.makeText(getApplicationContext(), "번호가 저장되었습니다!", Toast.LENGTH_SHORT);

                        toast.show();

                        already_saved[0] = true; //한번 저장할 경우 중복저장을 막기위한 변수

                    }catch (IOException e) { }

                }

            }

        });

    }


    public void random_gen() {

        int check = 0; //6이되면 while문 빠져나옴

        while(true) {

            int rand = (int) (Math.random() * 45) + 1;

            if (array.contains(rand)) {

                continue;

            } else {

                array.add(rand);

                check ++;

                if(check == 6) break;

            }

        }

        Collections.sort(array); //정렬

    }

}


반응형