如何从一个活动传递字符串并将其显示为另一个活动中的文本视图

时间:2013-12-16 05:55:53

标签: android android-intent textview

在我的应用程序中,我将从2个字符串中的服务器收集2个值,

String j1, j2;

j1 = strLine[11];  //Collecting values from the server
j2 = strLine[12];

并将它们传递给另一个活动,

Intent i = new Intent(getApplicationContext(),UserBookAppointSearchList.class);

i.putExtra("J1", j1);
i.putExtra("J2", j2);

startActivityForResult(i, 0);

在另一项活动中,我正在收集字符串,

TextView tv2;

String j1, j2; // strings to collect values from previous activity

 j1 = getIntent().getExtras().getString("J1");
 j2 = getIntent().getExtras().getString("J2");

 tv2 = (TextView) findViewById(R.id.msg2);
 tv2.setText(j1+":"+j2);

有人能告诉我这段代码有什么问题吗?

3 个答案:

答案 0 :(得分:2)

首先检查您是否从服务器获取任何内容。

j1 = strLine[11];  //Collecting values from the server
j2 = strLine[12];
Log.d("Getting From Server String 1", j1);
Log.d("Getting From Server String 2", j2);

然后也尝试改变获取上下文的方式。

Intent i = new Intent(getApplicationContext(), UserBookAppointSearchList.class);

Intent i = new Intent(YourActivity.this, UserBookAppointSearchList.class);

并在获取字符串后打印字符串:

j1 = getIntent().getExtras().getString("J1");
j2 = getIntent().getExtras().getString("J2");
Log.d("Getting From Server String 1", j1);
Log.d("Getting From Server String 2", j2);

答案 1 :(得分:0)

在接收活动时,在oncreate()内,执行此操作以检索值: -

String j1 = "";
String j2 = ""; // strings to collect values from previous activity
TextView tv2;

        Bundle bundle   = getIntent().getExtras();
        try {
             j1 = bundle.getString("J1");
             j2 = bundle.getString("J2");
        } catch (Exception e) {
             j1 = "";
             j2 = "";
        }

        tv2 = (TextView) findViewById(R.id.msg2);
        tv2.setText(j1+":"+j2);

答案 2 :(得分:0)

试试这个:

Intent i=new Intent(getApplicationContext(),Myforgetpassword.class);
                i.putExtra("username", "kiran"));
                startActivity(i);

并在第二个活动中:

 Intent i=getIntent();
 String username1 = i.getExtras().getString("username");