2013-05-08 3 views
0

내 주요 활동에서 스레드를 사용하여 연결하고 서버에서 결과를 가져옵니다.서버에서 데이터를 가져온 후 활동을 변경하는 방법

Thread thread = new Thread(new Runnable(){ 
@Override 
public void run() { 
    try { 

     ABDAServerConnection sc = new ABDAServerConnection(); 
     sc.getCategories();    
    } catch (Exception e) { 
     Log.i(TAG,"thread1: " + e); 
    } 
} 
}); 

thread.start(); 

연결이 성공적으로 실행 된 후 내 활동을 변경하고 싶습니다. 즉, 서버에서 결과를 얻습니다.

public class ABDAServerConnection { 

public void getCategories() { 
    HttpResponse response = null; 
    StringBuilder str = new StringBuilder(); 

    //Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(ABDAURLs.getCategories); 
    httppost.setHeader("Accept", "application/json"); 
    httppost.setHeader("Content-type", "application/json"); 

    String result = ""; 

    try { 

     // Execute HTTP Post Request 
     response = httpclient.execute(httppost); 

     try{ 
      InputStream in = response.getEntity().getContent(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8); 
      str = new StringBuilder(); 
      String line = null; 
      while((line = reader.readLine()) != null){ 
       str.append(line + "\n"); 
      } 
      in.close(); 
      result = str.toString(); 
      Log.i("NFC",result); 
      JSONObject jObject = new JSONObject(result); 
      JSONArray jArray = jObject.getJSONArray("results"); 

      for (int i=0; i < jArray.length(); i++) 
      { 
       JSONObject oneObject = jArray.getJSONObject(i); 
       // Pulling items from the array 
       int id = oneObject.getInt("category_id"); 
       String name = oneObject.getString("category_name"); 
       //Add this "MenuCategory" item to the global menu_category array 
       ABDACategories m1 = new ABDACategories(id,name); 
       GlobalList.getCategories().add(m1); 
      } 

      //AT THIS POINT, I WANT TO START ANOTHER ACTIVITY 


     }catch(Exception ex){ 
      result = "Error"; 
      Log.i("NFC","Problem: " +ex); 
     } 

    } catch (ClientProtocolException e) { 
     Log.i("NFC","ClientProtocolException: " +e); 
    } catch (IOException e) { 
     Log.i("NFC","IOException: " +e); 
    } 

    return; 
} 
} 

일반적으로, 내가 사용하는 거라고

startActivity(new Intent(MainActivity.this, AnotherActivity.class)); 

하지만 난 내 ABDAServerConnection 클래스 내에서 사용할 수 없습니다이 경우

. 서버에 성공적으로 접속 한 후 활동을 변경하는 방법을 제안 해 주시겠습니까?

답변

1

당신이 Activity에서이 클래스를 호출하고 있기 때문에 당신은 constructor

ABDAServerConnection sc = new ABDAServerConnection(MainActivity.this); 

다음

public class ABDAServerConnection 
{ 
    Context mContext; 
    public ABDAServerConnection(Context c) 
{ 
    mContext = c; 
} 

같은 생성자를 구축 자사의 Context은 다음 Intent

mContext.startActivity(new Intent(mContext, AnotherActivity.class)); 
+0

을 만들 보낼 수 있습니다 자세한 설명을 주셔서 감사합니다. – inankupeli

0

ABDAServerConnection 클래스의 생성자에 컨텍스트 클래스 (MainActivity.this)에 대한 참조를 저장하고 첫 번째 인수에서이를 사용하십시오.

관련 문제