开发者

Android get data from another class

开发者 https://www.devze.com 2023-03-11 10:25 出处:网络
I\'ve tried to solve this before in another post but was unsuccessful. This is what I want to accomplish: When the user clicks the gpsbtn it will pull from the gps.printLocation method to get the long

I've tried to solve this before in another post but was unsuccessful. This is what I want to accomplish: When the user clicks the gpsbtn it will pull from the gps.printLocation method to get the long / lat. I want to auto populate the edittext but I think I could figure out how to do that with a quick google search. So if I could just store it the coords to a variable that would be all I want but my brain is not working. Full code:

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);

            }

        });

    }
}

Class that I want to pull info from:

public class gps extends Activity implements LocationListener {

    //private static final S开发者_开发百科tring[] 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();



    }

I am so lost! Thanks!


You could save the co-ordinates to the Shared Prefs which are available to all classes within an application. Shared Prefs

Or you can create a "Global" Class which extends from the Application class and write your own setter and getter methods to access data stored in this Global class.

public class MyApp extends Application {

      public String string1;

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

To get the data stored from any class use from any other class in the application:

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


Untested, but i'd think of using shared preferences:

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);
}

Shared preferences instances are atomic so as soon as you do a commit on the editor the changes can be read by the instance of sharedPreferences in your reader class.

Possible issues, default values for location, no location object available in the sharedPreferences only long and lat meaning you cant derive accuracy or time of location read.


In MainActivity write after under public class MainActivity extends AppCompatActivity {:

    public class MainActivity extends AppCompatActivity {
    public static String test = "OK it's working";
    ...

in another activity write:

    public class NameOfYourClass extends AppCompatActivity {
    String testInAnotherClass = MainActivity.test;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_suppported_apps);

    Toast.makeText(getApplicationContext(),testInAnotherClass , Toast.LENGTH_SHORT).show();
...

0

精彩评论

暂无评论...
验证码 换一张
取 消