2010-07-03 4 views
2

"가까운 현재 위치"체크 박스가있는 검색 필드와리스트 뷰를 사용하여 결과를 보여주는 활동이 있습니다. onSaveInstanceState 및 onRestoreInstanceState 메소드를 구현하여 활동의 라이프 사이클에 있습니다. 액티비티가 파괴되어 다시 돌아 오면 결과가있는 목록보기가 사라지지만 onSaveInstanceState에 아무 것도 저장하지 않은 상태에서 검색 상자의 텍스트와 체크 박스 상태가 복원됩니다. 왜? "자동으로"저장되는 항목과 onSaveInstanceState에 저장해야하는 항목은 무엇입니까?간단한 안드로이드 애플리케이션의 라이프 사이클에 대한 또 다른 질문

public class Atable extends Activity { 
    private EditText mSearch; 
    private static final int ACTIVITY_EDIT=0; 
    private Button mSearchButton; 
    private TextView mNoresults; 
    private TextView mytext; 
    private ListView lv; 
    private CheckBox checkBox; 
    private LocationManager locationManager;  


    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState);   

     setContentView(R.layout.main); 

     lv= (ListView)findViewById(R.id.listview); 

     mNoresults = (TextView) findViewById(R.id.noresults); 
     mNoresults.setVisibility(View.GONE); 

     mSearchButton = (Button)this.findViewById(R.id.button); 
     checkBox = (CheckBox) findViewById(R.id.local_check);   

     locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
     final Criteria criteria = new Criteria(); 
     criteria.setAccuracy(Criteria.ACCURACY_FINE); 

     mSearchButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       mNoresults.setVisibility(View.GONE); 
       mSearch = (EditText) findViewById(R.id.search); 
       String tmp_str = mSearch.getText().toString().replace(" ","+");   

       HttpClient httpclient = new DefaultHttpClient();  

       // Prepare a request object 
       String url = "http://www.atable.org/getRestaurantByQuery/?query=" + tmp_str;    

       if (checkBox.isChecked()) { 

        //get location 
        String provider = locationManager.getBestProvider(criteria, true);     
        Location location = locationManager.getLastKnownLocation(provider); 

        if (location!=null) { 

         String lat = String.valueOf(location.getLatitude()); 
         String lng = String.valueOf(location.getLongitude()); 

         url += "&lat="+lat+"&lng="+lng;     
        } 
       } 

       HttpGet httpget = new HttpGet(url); 

       // Execute the request 
       HttpResponse response; 
       try { 
        response = httpclient.execute(httpget); 
        HttpEntity entity = response.getEntity(); 

        if (entity != null) { 

         InputStream instream = entity.getContent(); 

         Reader r = new InputStreamReader(instream);      

         Gson gson = new Gson(); 
         final RestaurantList restaurantList = gson.fromJson(r, RestaurantList.class); 

         int nResults = restaurantList.getSize(); 

         if (nResults>0) { 

          lv.setVisibility(View.VISIBLE); 

          lv.setAdapter(new ArrayAdapter<String>(Atable.this ,android.R.layout.simple_list_item_1,restaurantList.getRestaurantNames())); 

          lv.setOnItemClickListener(new OnItemClickListener() { 

           public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

            Intent intent = new Intent(Atable.this, RestaurantDescription.class); 
            Restaurant tmp_resto = restaurantList.getRestaurant((int)id); 

            String tmp_categories = tmp_resto.getCategories().get(0); 
            for (int i=1; i<tmp_resto.getCategories().size(); i++) { 
             tmp_categories+=", "+tmp_resto.getCategories().get(i); 
            } 

            String address = tmp_resto.getStreet()+", "+tmp_resto.getStreetNumber()+"\n"+tmp_resto.getCity()+ 
                " "+tmp_resto.getPostalCode()+"\n"+tmp_resto.getCountry(); 

            intent.putExtra("name", tmp_resto.getName()); 
            intent.putExtra("address", address);         
            intent.putExtra("rating", tmp_resto.getRating()); 
            intent.putExtra("price_range", tmp_resto.getPriceRange()); 
            intent.putExtra("categories", tmp_categories); 
            intent.putExtra("latitude", tmp_resto.getLatitude()); 
            intent.putExtra("longitude", tmp_resto.getLongitude()); 
            startActivityForResult(intent, ACTIVITY_EDIT); 
           } 
          }); 

         } 

         else { 
          lv.setVisibility(View.GONE); 
          mNoresults.setVisibility(View.VISIBLE); 
         } 

         //Closing the input stream will trigger connection release 
         instream.close(); 
        } 


       } catch (ClientProtocolException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     }); 

    } 

    //Start a location listener 
    LocationListener onLocationChange=new LocationListener() { 
     public void onLocationChanged(Location loc) { 
      //sets and displays the lat/long when a location is provided 
      /*String latlong = "Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude(); 
      mytext.setText(latlong);*/ 
     } 

     public void onProviderDisabled(String provider) { 
     // required for interface, not used 
     } 

     public void onProviderEnabled(String provider) { 
     // required for interface, not used 
     } 

     public void onStatusChanged(String provider, int status, 
     Bundle extras) { 
     // required for interface, not used 
     } 
    }; 

    //pauses listener while app is inactive 
    @Override 
    public void onPause() { 
     super.onPause(); 
     locationManager.removeUpdates(onLocationChange); 
    } 

    //reactivates listener when app is resumed 
    @Override 
    public void onResume() { 
     super.onResume(); 
     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,onLocationChange); 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    protected void onRestoreInstanceState(Bundle savedInstanceState) {  
     Toast.makeText(this, "onRestoreInstanceState", Toast.LENGTH_LONG).show(); 
     super.onRestoreInstanceState(savedInstanceState); 
    } 

    @Override 
    protected void onSaveInstanceState(Bundle outState) {  
     Toast.makeText(this, "onSaveInstanceState", Toast.LENGTH_LONG).show(); 
     super.onSaveInstanceState(outState); 
    } 

} 

답변

2

먼저 UI 스레드에서 네트워크 요청을 수행하지 마십시오. 작업 기간 동안 UI가 응답하지 않게하고 위험을 유발하는 위험은 ANRs입니다. 서버에 쿼리하려면 AsyncTask을 사용해보십시오.

기본적으로 활동은 뷰 계층 구조 상태를 저장하고 복원합니다. 각 View의 구현은 상태의 어떤 부분을 저장하고 복원해야하는지 결정해야합니다. ListView은 보통 특별한 경우입니다.

ListView은 현재 목록 위치 및 항목 선택에 대한 상태를 저장하지만 어댑터가 없으면이 모든 것이 쓸모가 없습니다. 저장된 뷰 계층 구조 상태가 Activity#onRestoreInstanceState에 복원되기 전에 어댑터를 설정하면 ListView은 뷰 상태를 데이터와 다시 동기화하려고 시도합니다.

onSaveInstanceState을 호출하고 결과 데이터를 사용할 수있는 경우 저장된 검색 결과를 Bundle에 쓸 수 있습니다.

onCreate에서 제공된 Bundlenull이 아닌지 확인하고 이전 쿼리의 데이터가있는 경우 확인하십시오. 맞다면 다시 읽으십시오. 그것을 사용하여 새 어댑터를 구성하고 ListViewsetAdapter을 호출하십시오. ListView에서 가져와야합니다.