String데이터를 putExtra() 와 getExtra() 로 넣고 받으려면 어떻게 해야하나요?

조회수 7705회

getExtra()와 putExtra()를 쓰는 방법이 뭔지 알려주세요.

어떻게 쓸거냐면, str이라고 string 변수가 있는데 이 값을 저장하고 싶습니다. 저장해서 그 데이터를 이 액티비티에서 다른 액티비티로 보내고 싶은데 어떻게 하면 좋을까요?

  Intent i = new Intent(FirstScreen.this, SecondScreen.class);   
  String keyIdentifer  = null;
  i.putExtra(strName, keyIdentifer );
and then in the SecondScreen.java

 public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.table);
        TextView userName = (TextView)findViewById(R.id.userName);
        Bundle bundle = getIntent().getExtras();

        if(bundle.getString("strName")!= null)
        {
            //TODO here get the string stored in the string variable and do 
            // setText() on userName 
        }

    }

저도 기본적인 질문이란건 알지만 여기서 막혀서 이렇게 질문드립니다..

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    아래처럼 다른 액티비티를 띄워줄 intent를 생성하고 그 인텐트에 전송할 값을 "put" 하시면 됩니다. "STRING_I_NEED"는 해당 문자열을 받기 위한 키 값입니다.

    Intent i = new Intent(FirstScreen.this, SecondScreen.class);   
    String strName = null;
    i.putExtra("STRING_I_NEED", strName);
    

    그리고 그 값을 받을때는 아래처럼 하시면 됩니다.

    String newString;
    if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
        if(extras == null) {
            newString= null;
        } else {
            newString= extras.getString("STRING_I_NEED");
        }
    } else {
        newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
    }
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)