0

버튼이있는 활동이 있습니다. 버튼을 클릭하면 새로운 활동이 시작되고이 활동에서 다양한 데이터가 웹에서 가져옵니다.하지만 버튼을 클릭하면 첫 번째 활동이 3 ~ 4 초 후 두 번째 활동은 준비된 데이터로 시작됩니다. 두 번째 활동이 표시되기 전에 앱에서 데이터를 가져 오려고 시도합니다. 그러나 첫 번째로 두 번째 활동을 사용자가 볼 수있게하려는 후 가져 오는 데이터를 시작해야합니다. 나는 활동의 라이프 사이클을 조사하고 ONSTART()로 가져 오는하지만 난 그렇게 할 수있는 방법Android 액티비티가 표시된 후 무언가하기

@Override 
protected void onStart() { 
      super.onStart(); 
      //Fetch data 
} 

를 작동하지 않는 한 바뀌? 여기

내 모든 코드 (단지 두 번째 활동)이다 : 위의 코드와

public class GuzergahActivity extends android.support.v4.app.FragmentActivity{ 

     private GoogleMap map; 
     private GuzergahOverlay overlay; 
     private WebView webview; 
     private ImageView imageview; 
     private ProgressDialog dialog; 
     private int flag; 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     overridePendingTransition(0, 0); 
     setContentView(R.layout.guzergah); 
     flag=this.getIntent().getExtras().getInt("flag"); 
     setUpMapIfNeeded(); 
     setUpView(); 
     } 

     @Override 
     protected void onResume() { 
      super.onResume(); 
      setUpMapIfNeeded(); 
     } 

     @Override 
     protected void onDestroy() { 
     if (dialog!=null) { 
      dialog.dismiss(); 
     } 
     super.onDestroy(); 
     } 

     private void setUpMapIfNeeded() { 
      // Do a null check to confirm that we have not already instantiated the map. 
      if (map == null) { 
       map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.guzergah_fragment)).getMap(); 
       if(map!=null){ 
        setUpMap(); 
       } 
      } 
     } 

    private void setUpMap(){ 

     try { 
      String result=new MyNewTask().execute().get(); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ExecutionException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     overlay.setOverlay(map); 
     map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.910526,32.804435),15)); 
     map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); 
    } 


    private void setUpView() { 
      //Binding imageview,webview...and setting up their features 
    } 

    private class MyNewTask extends AsyncTask<String,Integer,String> 
    { 
     @Override 
     protected void onPreExecute() 
     { 

      dialog= new ProgressDialog(GuzergahActivity.this); 
      dialog.setIndeterminate(true); 
      dialog.setCancelable(false); 
      dialog.setMessage("Downloading! Please wait...!"); 
      dialog.show(); 

     } 


     @Override 
     protected String doInBackground(String... params) 
     { 
      /* Fetching data is in this class - GuzergahOverlay*/ 
      overlay = new GuzergahOverlay(flag); 

      return "Done"; 

     } 

     @Override 
     protected void onPostExecute(String result) 
     { 
      super.onPostExecute(result); 
      Log.i("result","" +result); 
      if(result!=null){ 
       dialog.dismiss(); 
      } 
     } 

    } //end MyNewTask 
} 



public class GuzergahOverlay { 

private MarkerOptions beytepe_kampusu; 
private MarkerOptions sihhiye_kampusu; 
private ArrayList<PolylineOptions> lines; 
private ArrayList<MarkerOptions> stops; 

public GuzergahOverlay(int mode) { 
    beytepe_kampusu=new MarkerOptions().position(new LatLng(39.87159,32.735435)).title("Hacettepe Üniversitesi Beytepe Yerleşkesi").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_beytepe)); 
    sihhiye_kampusu=new MarkerOptions().position(new LatLng(39.931599,32.862365)).title("Hacettepe Üniversitesi Sıhhıye Yerleşkesi").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_sihhiye)); 
    getLinesAndStops(mode); //Here is fetching geopoint and preparing lines and stops arraylists 
} 

private void getLinesAndStops(int mode) { 

    // Fetching data from Parse.com 
      // Fillinp up lines and stops arraylists 
} 




public void setOverlay(GoogleMap map){ 
    map.addMarker(beytepe_kampusu); 
    map.addMarker(sihhiye_kampusu); 
    for(PolylineOptions polyline : lines){ 
     map.addPolyline(polyline); 
    } 
    for(MarkerOptions marker : stops){ 
     map.addMarker(marker); 
    } 
} 
} 

, I 버튼을 클릭, 첫 번째 활동은 잠시 동안 보유 및 데이터 finished.Progress 대화 상자를 가져 오는 경우 두 번째 활동은 볼 수 있습니다 몇 밀리 초 동안 표시됩니다.

+0

두 번째 활동에있는 나의 진행 표시가 성공했다면 –

답변

1

UI 스레드에서 모든 코드를 실행하는 것처럼 들립니다. 좋은 예제를 줄 수있는 더 많은 코드가 있으면 좋을 것입니다.

private class BackgroundTask extends AsyncTask<Void, Void, Void> { 

    // Before running code in separate thread 
    @Override 
    protected void onPreExecute() { 
     // setup loading dialog 
    } 

    @Override 
    protected Void doInBackground(Void... arg0) { 
     // do long running code 
     return null; 
    } 

    // after executing the code in the thread 
    @Override 
    protected void onPostExecute(Void arg) { 
     // dismiss your dialog 

    } 

} 

그리고에서 onCreate 내부 : 두 번째 활동에서

new BackgroundTask().execute(); 

편집 : 나는 제안 코드를 보았다 이제

이 같은 것을 시도 :

private void setUpMap(){ 
     map.moveCamera(CameraUpdateFactory.newLatLngZoom(new  LatLng(39.910526,32.804435),15)); 
     map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); 
     new Handler().postDelayed(new Runnable() { 
      public void run() { 
       try { 
        String result = new MyNewTask().execute(); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (ExecutionException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       /* 
       * you should move this call to onPostExecute 
       * then you will not need to call execute().get() 
       * which takes away the advantage of AsyncTask 
       * as it then is run on UI thread 
       */ 

       overlay.setOverlay(map); 
      } 
     }, 2000); 

    } 

지도를 설정하는 것은 UI 작업이 많기 때문에 마커 등을로드하기 전에 잠시 기다리는 것이 좋을 것 같습니다. 또한 대화 상자가 닫히기 전에 제대로 표시되도록해야합니다.

+0

나는 나의 질문을 편집, 나는 UI와 비동기 작업을 분리 할 수 ​​없다고 생각한다 ... –

+0

지도에 마커를 추가하는 모든 호출은 UI 스레드에 있어야하지만 onPostExcecute에있을 수있다. .onPostExecute (result); 메서드의 맨 아래로 – cYrixmorten

+0

당신이 찾고있는 행동을 잘하면 내 대답을 업데이트했습니다. – cYrixmorten

1

데이터 가져 오기 방법을 AsyncTask으로 옮겨야합니다. UI 스레드에서 원격 소스의 데이터를 가져 오면 안됩니다. 이런 방식으로 백그라운드 스레드로 작업을 이동하면 UI의 우선 순위가 높아져서 비동기 작업이 완료되는 동안 빠르게로드해야합니다. onCreate 또는 onStart에서 작업을 시작할 수도 있습니다. 그러면 성능이 향상됩니다.

+0

답장을 보내 주셔서 감사합니다. 코드를 사용하여 질문을 편집했습니다. 다시 볼 수 있습니까? –

+0

@SedatKURT 편집자가 올바른 방향으로 향하고있는 것처럼 보입니다. 지금 문제는 무엇입니까? – mattgmg1990

+0

질문 끝에서 "위의 코드를 사용하면 버튼을 클릭하면 첫 번째 활동이 잠시 동안 유지되고 데이터를 가져올 때 두 번째 활동이 표시됩니다. 진행 대화 상자가 몇 밀리 초 동안 표시됩니다."이것은 내 문제입니다. : –

관련 문제