【问题标题】:How to return a String value to another class in regards to editText [duplicate]关于editText [重复] 如何将字符串值返回给另一个类
【发布时间】:2013-05-17 22:30:33
【问题描述】:

我正在尝试显示用户从主类插入到另一个类/窗口的 textValue。

在我的主课上我做了这个方法

public String retChoice()
{
    choices[0] ="sasda"; //editText.getText().toString(); //pass from click button to method.
    choices[1] ="asdsa";//editText2.getText().toString(); 
    choices[2] = "asdsads";  //editText3.getText().toString();
    finalChoice =rand.nextInt(2);

    displayChoice = choices[finalChoice];

    return displayChoice; 
}

有效的

但是这个

public String retChoice()
{
    choices[0] = editText.getText().toString(); //pass from click button to method.
    choices[1] = editText2.getText().toString(); 
    choices[2] = editText3.getText().toString();
    finalChoice =rand.nextInt(2);

    displayChoice = choices[finalChoice];

    return displayChoice; 
}

应用程序完全崩溃。

这是我的另一个类,我将展示它的选择。

public class resultScreen extends Activity {



MainActivity ma = new MainActivity(); 
//Method supposedly retrieves the string data from MainActivity Class but somehow displayed null instead. 
//Find a way to keep the string variable when transfering from one class to another class. 
String finalResult = ma.retChoice(); 
 public void onCreate(Bundle resultScreen){
 super.onCreate(resultScreen);
 setContentView(R.layout.resultscreen);
  //ma.displayChoice.toString(); 

  String str = finalResult;

  TextView text = (TextView) findViewById(R.id.textView1);
  text.setText(str);
        }

【问题讨论】:

  • 请不要因为没有得到正确答案而转发。尝试使您的原始帖子更好,以便人们可以帮助您。在您的 OP 中,您被要求多次提供 logcat。如果你这样做了,你现在可能会有答案了
  • 对不起大声笑,我是这个网站的新手。我应该这样做。
  • 没关系。查看我对您原始问题的回答

标签: java android crash android-edittext return


【解决方案1】:

您不能直接从其他活动访问视图。您需要通过其他方式检索此值,例如使用 Singleton、extras 或 SharedPreferences。

Android 每次只保留一个活动。

因此,当您尝试检索 MainActivity 上的 EditText 值时,不会创建这些视图,因此您将获得空指针异常。

【讨论】:

  • 谢谢蒂亚戈。现在我将如何解决这个问题?单例似乎是要走的路,但我不知道从哪里开始或如何开始。
  • 实际上,我正在查看您的另一个主题,而附加内容是您的最佳选择。在您的主要活动上,在创建 Intent 之后,使用intent.putExtra("finalChoice", retChoice()); 并在您的结果屏幕上,而不是创建一个主要活动并检索选择,在您的 onCreate 方法上使用:resultScreen.getString("finalChoice")
  • 操作,getIntent.getStringExtra("finalChoice");
  • 好的,谢谢蒂亚戈!会做
猜你喜欢
  • 1970-01-01
  • 2013-09-13
  • 2019-06-07
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多