I have two void method in the same class. Method2 get data from textview and it stored in a string. I want to get Method2 string in Method1 string. Note: It is an android project. Code is here:
class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
void Method2()
{
//this place i want to get str1 value like this:
// String str2=str1
}
void Method1(View view)
{
String str1=textView.getText().toString();
}
}
try this code
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static String s1 ;
public static String s2 ;
void Method1(View view) {
s1 = textView.getText().toString();
}
void Method2() {
s2 = s1 ;
}
}
Learn and follow Java coding standards. This simple class fails the test.
Method 1 should not return void; it should return the String from the View.
Method 2 should not have an empty parameter list; it should have a String parameter that lets you pass in the value you want.
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void method2(String s) {
//this place i want to get str1 value like this:
// String str2=str1
}
public String method1(View view) {
return textView.getText().toString();
}
}
You don't have an example of how method1
will get a reference to a View
.
This implementation will allow you to get the String
out of the View
and pass it to method2
. Is that what you want?
A simple way is to add a parameter to method2()
void method2(String str1) {
//this place i want to get str1 value like this:
// String str2=str1
}
And call it from method1
.
Assuming you want both methods to be of void
return type, you will need to use a class variable. In your code, str1
is local to Method1
, and cannot be accessed from outside Method1
. Using a class variable:
class MainActivity extends AppCompatActivity {
String str1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
void Method2() {
String str2 = str1;
}
void Method1(View view) {
str1 = textView.getText().toString();
}
}
Alternatively, if Method2
should be executed after Method1
:
class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
void Method2(String str) {
String str2 = str1;
}
void Method1(View view) {
String str1 = textView.getText().toString();
Method2(str1); //pass the string to Method1
}
}
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.