2013-12-23 57 views
-1

我有一種方法,出於某種原因,只有在從主要活動調用它時纔有效。問題是我正試圖從另一個班級調用它。 有沒有辦法調用一個方法作爲主要活動?調用方法作爲主要活動

+0

它肯定會有助於查看您的代碼。 – EJK

+0

發佈你的logcat輸出也會有幫助。你需要更具體地瞭解什麼是不工作。 – EJK

回答

1

您可以隨時通過主尺蠖創建處理程序運行在主線程代碼:

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

然後,只需調用

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

這正是我想要的。 – Sochimickox

+0

當然,我可以讀你的思想=)。 「主要活動」和主線程(UI線程) - 它是完全不同的東西 – birdy

+0

那麼,我在談論的主要活動在android – Sochimickox

0

如果是靜態方法,請將其稱爲:MyActivityClass.myMethod(myArg1,myArg2)。

0

確保您的方法是靜態的,也是公開的而不是私有的。另外,不要忘記也包括課程。之後,您應該可以使用該類的任何對象的方法。

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. 
+0

請格式化代碼和答案時提供一個。 – Melquiades