2011-06-07 118 views
1

我試圖在另一個帖子之前解決此問題,但未成功。這是我想要完成的:當用戶點擊gpsbtn時,它將從gps.printLocation方法中獲取long/lat。我想自動填充edittext,但我想我可以通過快速的谷歌搜索找出如何做到這一點。所以,如果我能將它存儲到一個變量中,那將是我想要的,但我的大腦不工作。全碼:Android從另一個類獲取數據

public class Location extends Activity { 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // Full Screen 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
       WindowManager.LayoutParams.FLAG_FULLSCREEN); 

     setContentView(R.layout.location); 

     // Go button 
     Button gobtn = (Button) findViewById(R.id.gobtn); 
     final EditText Zipcodeinput = (EditText) findViewById(R.id.Zipcode); 
     gobtn.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View view) { 
       // Edit text validation field 
       Pattern pattern = Pattern.compile("[0-9][0-9][0-9][0-9][0-9]"); // string needs 5 digits 
       // argument to matcher is string to validate 
       Matcher matcher = pattern.matcher(Zipcodeinput.getText() 
         .toString()); 
       if (!matcher.matches()) // on Success 
       { 
        // invalid 
        // pop up ERROR message 
        Toast.makeText(getBaseContext(), " Invalid Input ", 
          Toast.LENGTH_LONG).show(); 

       } else { 
        // validation successful 
        // Change to Listings Page 
        Intent filterIntent = new Intent(view.getContext(), 
          Listings.class); 
        startActivityForResult(filterIntent, 0); 
       } 
      } 
     }); 

     // button to get to list view 
     Button gpsbtn = (Button) findViewById(R.id.gps); // temp use of gps 
                  // button 
     gpsbtn.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View view) { 

       // Toast.makeText(getApplicationContext(), "Please wait...", 
       // Toast.LENGTH_LONG).show(); 
       Intent gpsIntent = new Intent(view.getContext(), gps.class); 
       startActivityForResult(gpsIntent, 0); 

      } 

     }); 

    } 
} 

類,我想從拉動信息:

public class gps extends Activity implements LocationListener { 

    //private static final String[] S = { "Out of Service", 
      //"Temporarily Unavailable", "Available" }; 

    private TextView output2; 
    private LocationManager locationManager; 
    private String bestProvider; 
    double latitude,longitude; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.gps); 
     try { 
     // Get the output UI 
     //output = (TextView) findViewById(R.id.output); 
     output2 = (TextView) findViewById(R.id.output2); 

     // Get the location manager 
     locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 

     // List all providers: 
     List<String> providers = locationManager.getAllProviders(); 
     for (String provider : providers) { 
      printProvider(provider); 
     } 

     Criteria criteria = new Criteria(); 
     bestProvider = locationManager.getBestProvider(criteria, false); 
     //output.append("\n\nBEST Provider:\n"); 
     printProvider(bestProvider); 

     //output.append("\n\nLocations (starting with last known):"); 
     Location location = locationManager.getLastKnownLocation(bestProvider); 
     printLocation(location); 
     } 
     catch (Exception e) 
     { 
      Toast.makeText(getBaseContext(), "Error Getting GPS" , Toast.LENGTH_LONG); 
     } 

    } 

    /** Register for the updates when Activity is in foreground */ 
    @Override 
    protected void onResume() { 
     super.onResume(); 

    } 

    /** Stop the updates when Activity is paused */ 
    @Override 
    protected void onPause() { 
     super.onPause(); 
     locationManager.removeUpdates(this); 
    } 

    public void onLocationChanged(Location location) { 
     printLocation(location); 
    } 

    public void onProviderDisabled(String provider) { 
     // let okProvider be bestProvider 
     // re-register for updates 
    } 

    public void onProviderEnabled(String provider) { 
     // is provider better than bestProvider? 
     // is yes, bestProvider = provider 
    } 

    public void onStatusChanged(String provider, int status, Bundle extras) { 
     //output.append("\n\nProvider Status Changed: " + provider + ", Status=" 
      // + S[status] + ", Extras=" + extras); 
    } 

    private void printProvider(String provider) { 
     //LocationProvider info = locationManager.getProvider(provider); 
     //output.append(info.toString() + "\n\n"); 
    } 





    //PRINTS the long and lat. Take out round before release 

    private void printLocation(Location location) { 
     output2.append("Lat:"+location.getLatitude()+"\nLong: "+location.getLongitude()); 
     latitude = Math.round(location.getLatitude()); 
     longitude = Math.round(location.getLongitude()); 

     Toast.makeText(getBaseContext(), "Lat: " + latitude + "| Long: " + longitude, Toast.LENGTH_LONG).show(); 



    } 

我這麼輸了!謝謝!

+1

相似或相同的問題? http://stackoverflow.com/questions/6265885/android-how-to-change-activity-field-from-locationlistener-onlocationchanged/6265928#6265928 – 2011-06-07 13:42:08

+1

有沒有辦法從一個單獨的類訪問它?我想保持更有條理的分開。 – Nick 2011-06-07 14:12:01

回答

3

您可以將座標保存到適用於應用程序內所有類的共享Prefs。 Shared Prefs

或者您可以創建一個「應用程序」類的「全局」類,並編寫自己的setter和getter方法來訪問存儲在此Global類中的數據。

public class MyApp extends Application { 

     public String string1; 

     public String getState(){ 
     return string1; 
     } 
     public void setState(input){ 
     this.string1 = input; 
     } 
} 

要想從任何類使用存儲從其它類應用程序中的數據:

MyApp appState = ((MyApp)getApplicationContext()); 
String x = appState.getState(); 
appState.setState(x); 
+0

多數民衆贊成真棒...我從來不知道這個邏輯..你可以參考任何教程關於這個....關於全球使用數據 – 2012-06-01 07:29:41

1

未經檢驗的,但我想使用共享的喜好:

public static final String USER_LATITUDE = "user.lat"; 
public static final String USER_LONGTITUDE = "user.long"; 
public static final String USER_SHARED_PREFS = "user.prefs"; 

private void printLocation(Location location) { 

    SharedPreferences prefs = getSharedPreferences(USER_SHARED_PREFS, MODE_PRIVATE); 
    Editor editor = prefs.edit(); 
    long latitude = Math.round(location.getLatitude()); 
    long longitude = Math.round(location.getLongitude()); 

    editor.putLong(USER_LATITUDE, latitude).commit(); 
    editor.putLong(USER_LONGTITUDE, longitude).commit(); 

} 

private void doSTuff(){ 
    SharedPreferences prefs = getSharedPreferences(USER_SHARED_PREFS, MODE_PRIVATE); 
    prefs.getLong(USER_LATITUDE, 0); 
    prefs.getLong(USER_LONGTITUDE, 0); 
} 

共享偏好實例是原子的,所以只要您在編輯器上進行提交,您的閱讀器類中的sharedPreferences實例就可以讀取這些更改。

可能的問題,位置的默認值,沒有位置對象可用在sharedPreferences只有長和緯度意味着你不能派生精度或讀取位置的時間。