2012-07-19 5 views
0

현재 확장 클래스가 Thread입니다. 그 클래스에서 나는 웹 페이지 (그냥 JSON 데이터)의 내용을 얻었고 그것을 파싱했다. 그것은 어떤 JSON 객체를 얻었는지에 달려 있습니다. 왜냐하면 그 객체는 어떤 액션을 취할 것인지 또는 어떤 View를 보여야하는지 결정하기 때문입니다.스레드에서 호출 클래스로 콜백

하지만 현재 내가하고있는 방법은 모든 가능한 JSON 요청에 대해 하나의 클래스를 확인하고 그것에 기반한 작업을 수행하는 것입니다.

예, 내 수업은 좀 다음과 같습니다 당신이 상상할 수 있듯이

public class Communicator extends Thread 
{ 
    Thread threadToInterrupt = null; 
    String URL = null; 

    public Houses (String URL) 
    { 
     threadToInterrupt = Thread.currentThread(); 
     setDaemon(true); 

     this.URL = URL; 
    } 

    public void run() 
    { 
     // Code to get the JSON from a web page 
     // Finally parse the result into a String 
     String page = sb.toString(); 

     JSONObject jObject = new JSONObject(page); 
     if (!jObject.isNull("house")) 
     { 
      // do alot of stuff 
     } 
     else if (!jObject.isNull("somethingelse")) 
     { 
      // do alot of other stuff 
     } 
    } 
} 

,이 클래스가 곧 JSON 검사와 코드가 많이로 뒤범벅이 될 것이다. 이것은 올바른 생각이 아닙니다.

콜백 메소드를 호출하는 것이 더 좋을 수도 있습니다. 내가 이런 식으로 내 클래스를 변경할 수 있도록 :


public class MyClass 
{ 
    public void MyFunc() 
    { 
     (new Communicator("http://url.tld", "House", this.MyCallback)).start(); 
    } 

    public void MyCallback(JSONObject jObject) 
    { 
     // Then i can perform actions here... 
    } 
} 

public class Communicator extends Thread 
{ 
    Thread threadToInterrupt = null; 
    String URL = null; 

    public Houses (String URL, String JsonString, object CallbackMethod) 
    { 
     // ... code 
    } 

    public void run() 
    { 
     // .... 

     JSONObject jObject = new JSONObject(page); 
     if (!jObject.isNull(this.JsonString)) 
     { 
      // THen call the CallbackMethod... 
      CallbackMethod (jObject); 
     } 
    } 
} 

좋은 생각 인 경우 확실하지. 그렇다면 내 예제에서와 같이 콜백을 어떻게 만듭니 까? 어떻게 든 가능할까요?

답변

0

당신은 콜백하지만 MyJsonHandler 같은 핸들러 객체를 사용하지 않습니다 :

public class MyClass 
{ 
    public void MyFunc() 
    { 
     (new Communicator("http://url.tld", "House", new MyJsonHandler())).start(); 
    } 

} 

public class MyJsonHandler() { 

     public void handle(JsonObject jo) { 
     // ... 
      } 

} 

을 또는 당신이 필요로 할 때 바로 그 자리에 새로운 MyJsonHandler를 만들 :

public void run() 
    { 
     // .... 

     JSONObject jObject = new JSONObject(page); 
     if (!jObject.isNull(this.JsonString)) 
     { 
      // THen call the CallbackMethod... 
      new MyJsonHandler().handle(jObject); 
     } 
    } 
관련 문제