programing

문자열 데이터에 putExtra() 및 getExtra()를 사용하는 방법

codeshow 2023. 8. 10. 21:41
반응형

문자열 데이터에 putExtra() 및 getExtra()를 사용하는 방법

누가 정확한 사용법을 알려줄 수 있습니까?getExtra()그리고.putExtra()의도적으로?사실 저는 문자열 변수를 가지고 있습니다. say str은 문자열 데이터를 저장합니다.이제 한 활동에서 다른 활동으로 이 데이터를 보내고 싶습니다.

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

그런 다음 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 
        }

    }

나는 그것이 매우 기본적인 질문이라는 것을 알지만 불행히도 나는 여기에 갇혀 있습니다.제발 도와주세요.

감사해요.

편집: 여기서 한 화면에서 다른 화면으로 전달하려는 문자열은 동적입니다.즉, 사용자 유형에 관계없이 문자열을 가져오는 편집 텍스트가 있습니다.그리고 나서의 도움으로.myEditText.getText().toString()입력한 값을 문자열로 받은 다음 이 데이터를 전달해야 합니다.

파일을 "넣는" 데 사용합니다...

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");
}

첫 화면.java

text=(TextView)findViewById(R.id.tv1);
edit=(EditText)findViewById(R.id.edit);
button=(Button)findViewById(R.id.bt1);

button.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
        String s=edit.getText().toString();

        Intent ii=new Intent(MainActivity.this, newclass.class);
        ii.putExtra("name", s);
        startActivity(ii);
    }
});

Second Screen.java

public class newclass extends Activity
{
    private TextView Textv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.intent);
        Textv = (TextView)findViewById(R.id.tv2);
        Intent iin= getIntent();
        Bundle b = iin.getExtras();

        if(b!=null)
        {
            String j =(String) b.get("name");
            Textv.setText(j);
        }
    }
}

최상의 방법...

활동 보내기

Intent intent = new Intent(SendingActivity.this, RecievingActivity.class);
intent.putExtra("keyName", value);  // pass your values and retrieve them in the other Activity using keyName
startActivity(intent);

활동 수신

 Bundle extras = intent.getExtras();
    if(extras != null)
    String data = extras.getString("keyName"); // retrieve the data using keyName 

데이터를 수신하는 가장 빠른 방법.

String data = getIntent().getExtras().getString("keyName","defaultKey");

//api 12가 필요합니다. //두 번째 매개 변수는 선택 사항입니다. keyName이 null이면defaultkey자료로서

이것이 제가 사용해온 것입니다. 누군가에게 도움이 되기를 바랍니다.순박하고 애정이 넘치는

데이터 전송

    intent = new Intent(getActivity(), CheckinActivity.class);
    intent.putExtra("mealID", meal.Meald);
    startActivity(intent);

데이터 가져오기

    int mealId;

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();

    if(bundle != null){
        mealId = bundle.getInt("mealID");
    }

건배!

구현이 매우 쉽습니다.intentAndroid에서..한 활동에서 다른 활동으로 이동하는 데 필요합니다. 우리는 두 가지 방법이 있습니다.putExtra();그리고.getExtra();이제 예시를 보여드리겠습니다.

    Intent intent = new Intent(activity_registration.this, activity_Login.class);
                intent.putExtra("AnyKeyName", Email.getText().toString());  // pass your values and retrieve them in the other Activity using AnyKeyName
                        startActivity(intent);

이제 우리는 가치를 얻어야 합니다.AnyKeyName매개 변수, 아래에 언급된 코드가 이 작업에 도움이 될 것입니다.

       String data = getIntent().getExtras().getString("AnyKeyName");
        textview.setText(data);

수신 값을 쉽게 설정할 수 있습니다.Intent,우리가 필요로 하는 것.

작은 부록: 키에 대해 사용자 자신의 이름을 만들 필요가 없습니다. Android는 이를 제공합니다. 예를 들어, 승인된 답변 수정:

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

그런 다음 값을 검색하려면 다음과 같은 방법을 사용합니다.

String newString;
Bundle extras = getIntent().getExtras();
if(extras == null) {
    newString= null;
} else {
    newString= extras.getString(Intent.EXTRA_TEXT);
}
Intent intent = new Intent(view.getContext(), ApplicationActivity.class);
                        intent.putExtra("int", intValue);
                        intent.putExtra("Serializable", object);
                        intent.putExtra("String", stringValue);
                        intent.putExtra("parcelable", parObject);
                        startActivity(intent);

응용 프로그램 활동

Intent intent = getIntent();
Bundle bundle = intent.getExtras();

if(bundle != null){
   int mealId = bundle.getInt("int");
   Object object = bundle.getSerializable("Serializable");
   String string = bundle.getString("String");
   T string = <T>bundle.getString("parcelable");
}

보내세요

startActivity(new Intent(First.this, Secend.class).putExtra("key",edit.getText.tostring));

얻다

String myData = getIntent.getStringExtra("key");

Intent 클래스에서 업데이트합니다.

  • 사용하다hasExtra()의도에 키에 대한 데이터가 있는지 확인하기 위해.
  • 지금 사용할 수 있습니다.getStringExtra()직접적으로.

데이터 전달

intent.putExtra(PutExtraConstants.USER_NAME, "user");

데이터 가져오기

String userName;
if (getIntent().hasExtra(PutExtraConstants.USER_NAME)) {
    userName = getIntent().getStringExtra(PutExtraConstants.USER_NAME);
}

항상 상수에 키를 넣는 것이 가장 좋습니다.

public interface PutExtraConstants {
    String USER_NAME = "USER_NAME";
}

더 단순함

발신자측

Intent i = new Intent(SourceActiviti.this,TargetActivity.class);
i.putExtra("id","string data");
startActivity(i)

수신측

Intent i = new Intent(SourceActiviti.this,TargetActivity.class);
String strData = i.getStringExtra("id");

의도 객체에 문자열 삽입

  Intent intent = new Intent(FirstActivity.this,NextAcitivity.class);
  intent.putExtra("key",your_String);
  StartActivity(intent);

생성 방법 get string의 다음 요약

String my_string=getIntent().getStringExtra("key");

그것은 쉽고 짧은 방법입니다.

FirstScreen.java에서

    Intent intent = new Intent(FirstScreen.this, SecondScreen.class);
    String keyIdentifier = null;
    intent.putExtra(strName, keyIdentifier);

SecondScreen.java에서

    String keyIdentifier;
    if (savedInstanceState != null)
        keyIdentifier= (String) savedInstanceState.getSerializable(strName);
    else
        keyIdentifier = getIntent().getExtras().getString(strName);

풋 기능

etname=(EditText)findViewById(R.id.Name);
        tvname=(TextView)findViewById(R.id.tvName);

        b1= (ImageButton) findViewById(R.id.Submit);

        b1.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                String s=etname.getText().toString();

                Intent ii=new Intent(getApplicationContext(), MainActivity2.class);
                ii.putExtra("name", s);
                Toast.makeText(getApplicationContext(),"Page 222", Toast.LENGTH_LONG).show();
                startActivity(ii);
            }
        });



getfunction 

public class MainActivity2 extends Activity {
    TextView tvname;
    EditText etname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity2);
        tvname = (TextView)findViewById(R.id.tvName);
        etname=(EditText)findViewById(R.id.Name);
        Intent iin= getIntent();
        Bundle b = iin.getExtras();

        if(b!=null)
        {

          String j2 =(String) b.get("name");

etname.setText(j2);
            Toast.makeText(getApplicationContext(),"ok",Toast.LENGTH_LONG).show();
        }
    }

데이터 푸시

import android.content.Intent;

    ...

    Intent intent = 
        new Intent( 
            this, 
            MyActivity.class );
    intent.putExtra( "paramName", "paramValue" );
    startActivity( intent );

위의 코드는 메인 내부에 있을 수 있습니다.activity. "MyActivity.class두 번째입니다.Activity우리는 시작하고 싶다; 그것은 당신의 것에 명시적으로 포함되어야 합니다.AndroidManifest.xmljava.

<activity android:name=".MyActivity" />

데이터 가져오기

import android.os.Bundle;

    ...

    Bundle extras = getIntent().getExtras();
    if (extras != null)
    {
        String myParam = extras.getString("paramName");
    }
    else
    {
        //..oops!
    }

예에서 는 이예서에, 의▁your다▁would▁be▁inside 안에 있을 것입니다.MyActivity.javajava.

갓카스

이 메서드는 통과만 가능합니다.strings그래서 당신이 시험을 통과해야 한다고 가정해 봅시다.ArrayList의 신에게에.ListActivity가능한 해결 방법은 쉼표로 구분된 문자열을 전달한 다음 다른 쪽에서 분할하는 것입니다.

대체 솔루션

사용하다SharedPreferences

간단한 첫 활동부터

    EditText name= (EditText) findViewById(R.id.editTextName);
    Button button= (Button) findViewById(R.id.buttonGo);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this,Main2Activity.class);
            i.putExtra("name",name.getText().toString());
           startActivity(i);
          }
    });

두 번째 활동에서는

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    TextView t = (TextView) findViewById(R.id.textView);
    Bundle bundle=getIntent().getExtras();
    String s=bundle.getString("name");
    t.setText(s);
}

원하는 경우 if/else 조건을 추가할 수 있습니다.

줄을 맨 앞에 놓다

Intent secondIntent = new Intent(this, typeof(SecondActivity));
            secondIntent.PutExtra("message", "Greetings from MainActivity");

그 후에 그것을 회수합니다.

var message = this.Intent.GetStringExtra("message");

그게 전부야 ;)

이 작업에는 인라인 코드 하나로 충분합니다.이것은 저에게 어렵지 않게 효과가 있었습니다.#안드로이드 개발자들을 위하여.String strValue=Objects.requireNonNull(getIntent().getExtras()).getString("string_Key");

정적 변수를 사용하여 편집 텍스트의 문자열을 저장한 다음 다른 클래스에서 해당 변수를 사용할 수 있습니다.이것이 당신의 문제를 해결하기를 바랍니다.

언급URL : https://stackoverflow.com/questions/5265913/how-to-use-putextra-and-getextra-for-string-data

반응형