I just migrate to android studio from eclipse. I try one sample project just not working. I cannot figure it out. I hope someone can help me. I try to call sample class from my main activity. It seems like I cannot call the method from the sample.
package com.example.lzp93_000.sample;
import android.os.Bundle;
import android.app.*;
public class MainActivity extends Activity {
private sample s=new sample();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String y=sample.sampleMehod(); // <--- It's not working.
//It shows Cannot resolve Method.
}
}
package com.example.lzp93_000.sample;
public class sample {
public String sampleMethod()
{
String x="100";
return x;
}
}
Since you've not declared sampleMethod
as static
, it is an instance member, which means you need to call that method on an instantiated object, not the class itself.
If you want the method to be a static member of the class, simply declare it as such, and the rest of your code is fine:
public static String sampleMethod()
Otherwise, instantiate a sample
object, and call the method on that:
sample s = new sample();
String y = s.sampleMethod();
You have the method name misspelled in the code you've posted, by the way.
Additionally, following standard Java naming convention, the sample
class name should be capitalized - Sample
.
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.