[英]how to call a string from a method from another class Android
Hello I am new to android,java and I want to use the string from a method from another class. 您好,我是android,java的新手,我想使用另一个类的方法中的字符串。 Specifically I want to use the String s from to class Test to class MainActivity.
具体来说,我想使用String到类Test到MainActivity类。 I tried to call it like
我试图称它为
Test.AnswerQ1
but it says that cannot resolve symbol "AnswerQ1" 但它说无法解析符号“ AnswerQ1”
This is my Test class 这是我的测试课
public class Test extends Activity {
private RadioGroup radioGroupQuestion1;
private RadioButton radioButtonQuestion1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroupQuestion1 = (RadioGroup) findViewById(R.id.radioGroupQ1);
Button NextButton = (Button) findViewById(R.id.Q1NextButton);
NextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int selectedId = radioGroupQuestion1.getCheckedRadioButtonId();
radioButtonQuestion1 = (RadioButton) findViewById(selectedId);
String AnswerQ1 = radioButtonQuestion1.getText().toString();
String Question1 = getString(R.string.Q1);
System.out.println(Question1);
System.out.println(AnswerQ1);
Intent myIntent = new Intent(view.getContext(), Question2.class);
startActivityForResult(myIntent, 0);
}
});
}
And this is my MainActivity class 这是我的MainActivity类
public class MainActivity extends Activity{
String myData = Test.s;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println(myData);
}
}
Try with initializing string on the top of an onCreate method.
public class Test extends Activity {
public static String s = "hello world";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Don't declare a static member inside instance method. 不要在实例方法中声明静态成员。
You must declare a static member as class member not local member. 您必须将静态成员声明为类成员,而不是本地成员。
Example: 例:
public class Test extends Activity {
public static String s = "hello world";
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
You can make s public static
But there are many other solution. 您可以使
public static
但还有许多其他解决方案。 Dependent on your need, You can use Shared Preference
, Broadcast Listener
, Interface
etc. 根据您的需要,您可以使用
Shared Preference
, Broadcast Listener
, Interface
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.