Java 关于editText,如何将字符串值返回给另一个类
我试图显示用户从主类插入到另一个类/窗口的textValue 在我的主课上,我做了这个方法Java 关于editText,如何将字符串值返回给另一个类,java,android,crash,android-edittext,return,Java,Android,Crash,Android Edittext,Return,我试图显示用户从主类插入到另一个类/窗口的textValue 在我的主课上,我做了这个方法 public String retChoice() { choices[0] ="sasda"; //editText.getText().toString(); //pass from click button to method. choices[1] ="asdsa";//editText2.getText().toString(); choices[2] = "asdsa
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);
}
无法直接从其他活动访问视图。您需要以另一种方式检索此值,例如使用Singleton、extras或SharedReference Android每次只保留一个渲染的活动
因此,当您试图在MainActivity上检索EditText值时,这些视图不会被创建,因此您将得到空指针异常。请不要因为没有得到正确答案而重新发布。试着把你原来的帖子做得更好,这样人们可以帮助你。在您的OP中,您多次被要求提供logcat。如果你这么做了,你现在可能已经有答案了对不起,哈哈,我是这个网站的新手。我应该这么做,没关系。看到我对你原来问题的回答了吗?谢谢蒂亚戈。现在我该如何处理这个问题?单身似乎是一种方式,但我不知道从哪里或如何开始。事实上,我正在查看你的另一个线程和额外的是你的方式去。在您的主要活动中,创建意图后,使用
Intent.putExtra(“finalChoice”,retChoice())在resultScreen上,不要创建mainactivity并检索选项,而是在onCreate方法上使用:resultScreen.getString(“finalChoice”)
ops,getIntent.getStringExtra(“finalChoice”)代码>好的,谢谢蒂亚戈!行