Hello I am new to android,java and I want to use the string from a method from another class. Specifically I want to use the String s from to class Test to class MainActivity. I tried to call it like
Test.AnswerQ1
but it says that cannot resolve symbol "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
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. Dependent on your need, You can use Shared Preference
, Broadcast Listener
, Interface
etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.