마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

아래 쪽에 있는 변수를 위로 가져오기

0 추천
public class MainActivity extends AppCompatActivity {

    private final int[] images = {R.drawable.image, R.drawable.image1, R.drawable.image2};

    TextView myUID;

    TextView txtview;

    TextView tt11;
   



    phpdo task;

    // NFC 기술이 감지할 수 있는 태그를 나열합니다.
    private final String[][] techList = new String[][] {
            new String[] {
                    NfcA.class.getName(),
                    NfcB.class.getName(),
                    NfcF.class.getName(),
                    NfcV.class.getName(),
                    NdefFormatable.class.getName(),
                    TagTechnology.class.getName(),
                    IsoDep.class.getName(),
                    MifareClassic.class.getName(),
                    MifareUltralight.class.getName(),
                    Ndef.class.getName()
            }
    };



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

        tt11 = findViewById(R.id.myUID2);
       




        var currentIndex = 0;


        ImageSwitcher imageSwitcher = findViewById(R.id.imageSwitcher);

        // ImageSwitcher에 팩토리 설정 (이미지를 담을 ImageView를 생성)
        imageSwitcher.setFactory(() -> {
            ImageView imageView = new ImageView(getApplicationContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
                    ImageSwitcher.LayoutParams.MATCH_PARENT,
                    ImageSwitcher.LayoutParams.MATCH_PARENT));
            return imageView;
        });

        // 초기 이미지 설정
        imageSwitcher.setImageResource(images[currentIndex]);

        super.onResume();
        currentIndex++;
        if (currentIndex == images.length) {
            currentIndex = 0;
        }
        imageSwitcher.setImageResource(images[currentIndex]);
    }


    

    @Override
    protected void onResume() {
        super.onResume();
// 특정한 이벤트가 발생했을 때 작동하는 인텐트입니다.
        @SuppressLint("UnspecifiedImmutableFlag") PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// 특정한 NFC 이벤트가 발생했을 때 인텐트를 생성합니다.
        IntentFilter filter = new IntentFilter();
// 태그가 스마트 폰 근처로 접근했을 때 이벤트가 발생합니다.
        filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
// NFC 이벤트로부터 인텐트를 얻어 디스패치를 활성화합니다.
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, new IntentFilter[]{filter}, this.techList);
    }

    // Foreground 상태에서 호출되는 새로운 인텐트입니다.
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onNewIntent(Intent intent) {
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            myUID = findViewById(R.id.myUID);
            myUID.setText(ByteArrayToHexString(Objects.requireNonNull(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID))));


            String id = myUID.getText().toString();


            task = new phpdo();
            txtview = findViewById(R.id.myUID1);

            task.execute(id);

        }

    }

    // 얻어낸 바이트 배열을 문자열로 반환합니다.
    private String ByteArrayToHexString(byte [] array) {
        int i, j, in;
        String [] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
        StringBuilder out= new StringBuilder();

        for(j = 0 ; j < array.length ; ++j)
        {
            in = (int) array[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out.append(hex[i]);
            i = in & 0x0f;
            out.append(hex[i]);
        }
        return out.toString();
    }


    @SuppressLint("StaticFieldLeak")
    private class phpdo extends AsyncTask<String,Void,String> {

        protected void onPreExecute(){

        }
        @Override
        protected String doInBackground(String... arg0) {

            try {
                String id =  arg0[0];


                String link = "http://sun76841.dothome.co.kr/3333.php?cccc=" + id;
                new URL(link);
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(link));
                HttpResponse response = client.execute(request);
                BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                StringBuilder sb = new StringBuilder();

                in.lines().findFirst().ifPresent(sb::append);
                in.close();
                return sb.toString();
            } catch (Exception e) {
                return "Exception: " + e.getMessage();
            }

        }

        @Override
        protected void onPostExecute(String result){
            txtview.setText(result);


            TextView title1 = findViewById(R.id.myUID1);


            String str =  title1.getText().toString();
            String[] mobNum = str.split("6");
            String ret1 = mobNum[0];
            String ret2 = mobNum[1];


            tt11.setText(ret1);



        }


    }



}

 

위 소스 중에서 맨 아래 부분에 있는

String ret2 = mobNum[1];

의 ret2 라는 변수를

 

위쪽에

onCreate  안에 있는

var currentIndex = 0;

 = 0;  부분에 0 대신

var currentIndex = ret2;

변수가 들어가게 해야 하는데 어떻게 해야 할까요?

변수를 위로 가져가야 하는데... 이건 어렵네요 ㅠㅠ

ret2 변수값에는  숫자 0과 1중에 하나만 들어갑니다.

 

 

맘여리노앙자 (500 포인트) 님이 3월 12일 질문

1개의 답변

0 추천
onCreate는 메인액티비티의 오버라이드 함수이고 마지막 변수는 포토라는 어싱크 타스크의 이너 클래스 내부에 있는 온포스트 익스큐트 오버라이드 함수입니다.
메인 액티비티에 전역으로 변수를 선언한다고 하더라도 이너클래스 변수를 공유할수 없습니다.
차라리 공통 유틸 오브젝트 클래스 하나 만드셔서 거기에 변수 선언하시고
그 유틸클래스 변수를 참조하셔서 사용하시면 좋을듯 합니다.
쭈쭈총각 (17,870 포인트) 님이 1일 답변
...