Android从另一个类获取数据

问题描述:

我试图在另一个帖子之前解决此问题,但未成功。这是我想要完成的:当用户点击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://*.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

您可以将坐标保存到适用于应用程序内所有类的共享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

未经检验的,但我想使用共享的喜好:

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只有长和纬度意味着你不能派生精度或读取位置的时间。