将方法称为主要活动

时间:2013-12-23 22:13:59

标签: java android methods

我有一个方法,由于某种原因,只有在从主活动调用它时才能正常工作。问题是我试图从另一个类调用它。 有没有办法将方法称为主要活动?

4 个答案:

答案 0 :(得分:1)

您可以通过在主循环器上创建Handler来始终在主线程中运行代码:

Handler handler= new Handler(Looper.getMainLooper());

然后致电

handler.post(new Runnable(
  @Override
  public void run () {
    //  code that should be running from UI Thread
  }
));

答案 1 :(得分:0)

如果是静态方法,请将其命名为:MyActivityClass.myMethod(myArg1,myArg2)。

答案 2 :(得分:0)

确保您的方法是静态的,也是公开的而不是私有的。另外,不要忘记包括课程。之后,您应该能够使用该类对象的任何方法。

答案 3 :(得分:0)

当您使用来自不同类的方法时,您需要创建定义方法的类的实例。考虑以下两个类:

public class Test{ 

 public void showMesage(){ 
 System.out.println("I am method showMessage from class Test!"); 
 } 
 } 

 public class TestCall{ 

 public void run(){ 
 Test.showMesage(); 
 } 
 } 


 Class Test has a method named "showMessage". The method "run" in TestCall class is trying to use the showMessage method. This will generate similar error that you are having. To resolve that, you need to make an instance of the class Test inside the run method like this: 

 public void run(){ 
 Test t = new Test(); // create an instance 
 t.showMesage(); // use t to refer any method of class Test 
 } 

 Or, you can make the method showMessage static like this: 

 public static void showMesage(){ 
 System.out.println("I am method showMessage from class Test!"); 
 } 

 Now, you don't need to change the run method anymore. If you have any questions, post 'em. 

 Additional Suggestion: 

 You can always write a method which will extract the array list for you like this: 

 import java.util.ArrayList; 

 public class Test{ 

 ArrayList al = null; 

 public void populateList(){ 
 al = new ArrayList(); 
 al.add("Apple"); 
 al.add("Mango"); 
 } 

 public ArrayList getList(){ 
 return this.al; 
 } 
 } 

 import java.util.ArrayList; 

 public class TestCall{ 

 public void run(){ 
 Test t = new Test(); 
 t.populateList(); 
 ArrayList aList = t.getList(); 
 System.out.println(aList.get(0)); 
 System.out.println(aList.get(1)); 
 } 

 public static void main(String[] strARgs){ 

 new TestCall().run(); 
 } 

 } 

 Further response: 

 In that case, you can declare the ArrayList as static so that you can access that arraylist from other class directly. For example, class Mango as a arraylist named aList like: 

 class Mango { 

 public static ArrayList aList = null; //this is a global variable 

 //some methods and stuff 
 ....... 
 ..... 
 } 

 This aList now can be accessed easily from other classes like: 

 import Mango; 
 class Apple { 
 ArrayList aList = Mango.AList; // direct call 
 ... 
 .... 
 } 
 Another thing, before you access the arraylist, you need to make sure that the event that populates the arraylist(dynamically) has been called already from the same class where you are trying to access the arraylist.