2015-01-30 1 views
-2

별도의 클래스에서 asynctask를 사용하여 데이터베이스를 쿼리하는 응용 프로그램을 만들고 있습니다. 이 클래스는 문자열을 취하고 문자열이어야하며 (쿼리 여야 함) 결과를 ResultSet으로 가져옵니다. 그런 다음이 ResultSet을 onPostExecute로 전달해야합니다. 여기서 인터페이스를 사용하여 결과를 기본 스레드로 다시 가져옵니다. 그러나 로그 명령을 사용하여 asynctask가 onPostExecute에 도달하지 않는다는 것을 발견했습니다. 아무도 이걸 도와 줄 수 없나요?Asynctask는 UI 스레드에서 초기화 되더라도 onPostExecute에 도달하지 않습니다.

내 AsyncTask를 클래스 (getMyResults()는 더 이상 사용하지 않으며, doInBackground에 코드는 무관하다) :

편집 : 편집

public class DBConnector extends AsyncTask <String, Void, ResultSet> { 

    private Connection con; 
private Statement st; 
private ResultSet rs; 
public CallBackListener DBlistener; 



public ResultSet getMyResults(){ 
    return rs; 
} 

//public 


@Override 
protected ResultSet doInBackground(String... params) { 

String Query = params[0]; 
     System.out.println("Starting DBConnector"); 

//Code to get the database connection working 

    try{ 
     rs = st.executeQuery(Query); 
     System.out.println("Records from Database"); 
     /* 
     while(rs.next()){ 

      String StudentID = rs.getString("StudentID"); 
      String StudentName = rs.getString("StudentName"); 
      String StudentPassword = rs.getString("StudentPassword"); 
      System.out.println("Student ID: "+StudentID+" Student Name: "+StudentName+" Student Password: "+StudentPassword); 
     } 
     */ 
    }catch(Exception ex){ 
     System.out.println(ex); 
    } 

    System.out.println("Finished DBConnector"); 


    return rs; 
} 

@Override 
protected void onPostExecute(ResultSet rs) { 
    System.out.println("THIS IS WHERE IT ALL GOES WRONG"); 
    DBlistener.processFinish(rs); 
} 

}

을 그리고 내 인터페이스 (그건에서 자신의 파일 - 그 의미는 무엇입니까?) :

public interface CallBackListener { 
    void processFinish(ResultSet output); 
     } 

마지막으로 내 활동, I 관련없는 코드를 모두 버렸습니다.

public class CheckTimetable extends Activity implements CallBackListener { 
    ResultSet rs= null; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_check_timetable); 

     try { 
      Class.forName("android.os.AsyncTask"); 
     } catch (ClassNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

//이 문제는 제 문제를 해결하기위한 제안으로 추가되었지만 아무런 문제가 없습니다. 제 orginal 한 코드 행 COLS에

btnBuildTimetable.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
       BuildTable(rows, cols, "A"); //need mapping system to get TutorID from spinner and send it here 

//는 정수 2 edittexts }

BuildTable 버튼을 누르면
 } 
    }); 

} 


private void BuildTable(int rows, int cols, String GivenTutorID){ 
DBConnector connect = new DBConnector(); 
String StudentID = ""; 
String TutorID = ""; 
String VenueLocation = ""; 
String LessonDate = ""; 
String LessonStartTime = ""; 
String LessonEndTime = ""; 
connect.execute("SELECT * FROM Lessons WHERE Lessons.TutorID = '"+ GivenTutorID + "';"); 
connect.DBlistener = this;//should use TutorID here 
    /* 
try { 
    Thread.sleep(5000);//just used so that the resultset doesn't get no results - waits for connect.execute to finish. 
} 
catch (Exception e) {} 
*/ 
    System.out.println("WE GO IN BOYS"); 
while (rs == null){ 
    try { 
     Thread.sleep(100); 
    } catch (Exception e){} 
} 

rs = connect.getMyResults(); 

for (int i=1; i<=rows; i++){ 
    TableRow row = new TableRow(this); 
    row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); 
    for (int j=1; j<=cols;j++){ 
     try { 
      while (rs.next()) { 
       StudentID = rs.getString("StudentID"); 
       TutorID = rs.getString("TutorID"); 
       VenueLocation = rs.getString("VenueLocation"); 
       LessonDate = rs.getString("LessonDate"); 
       LessonStartTime = rs.getString("LessonStartTime"); 
       LessonEndTime = rs.getString("LessonEndTime"); 
      } 
     }catch(Exception ex) { 
      System.out.println("caught exception"); 
     } 
     TextView tv = new TextView(this); 
     tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 
       LayoutParams.WRAP_CONTENT)); 
     tv.setBackgroundResource(R.drawable.cell_shape); 
     tv.setPadding(5, 5, 5, 5); 
     tv.setText(LessonDate); 
     System.out.println(LessonDate); 
     System.out.println("Cell set"); 

      row.addView(tv); 

     } 
tblTutorTimetable.addView(row); 
    } 
    } 
     @Override 
     public void processFinish(ResultSet output) { 
      rs = output; 
      System.out.println("WE MADE IT"); 
     } 

, 그것은 코드 통과로부터 얻어진 AsyncTask를 그때까지 대기 실행되고 ResultSet가 null가 아닙니다. 두 번째 스레드 (asynctask)는 doInBackground가 끝날 때까지 끝나고 아무 것도 일어나지 않고 UI 스레드가 고정 된 상태로 유지됩니다.

이 인터페이스 또는 인터페이스에 관한 도움은 환상적입니다!

답변

0

BuildTable 단추를 누르면 코드를 거치며 asynctask를 실행 한 다음 ResultSet이 널이 될 때까지 대기합니다. 두 번째 스레드 (asynctask)는 doInBackground가 끝날 때까지 끝나고 아무 것도 일어나지 않고 UI 스레드가 고정 된 상태로 유지됩니다.

직접 asynctask를 기다리지 마십시오. 특히 Thread.sleep()으로 UI 스레드를 차단하지 마십시오.

비동기 작업 onPostExecute()은 UI 스레드에서 실행되며 스레드를 직접 차단할 때 실행되지 않습니다.

비동기 작업을 비동기 방식으로 사용하십시오. UI 스레드가 수행하는 모든 작업을 수행하고 UI 스레드 인 looper/handler에 제어를 반환하고 비동기 작업 결과로 UI를 업데이트하는 작업은 onPostExecute()입니다.

+0

그러나 내 UI는 ResultSet과 관련된 작업 만 수행 할 수 있습니다. 처음에는 시간을 되찾기위한 간단한 방법을 사용했지만, 클라우드 데이터베이스에서 결과를 얻으려면 AsyncTask 시간을주기 위해 일정 시간 동안 UI 스레드를 고정시키지 않으면 안되는 해결책이되었습니다. 결과 집합이 되자마자 AsyncTask에서 검색된 ResultSet을 얻으려면 어떻게해야합니까? 미리 감사드립니다. – user3925417

관련 문제