Search code examples
androidlocationlocationlistener

How to access custom view from public void function in Android?


I want to access custom view from public void onLocationChanged in public class MyCurrentLocationListener implements LocationListener. MyActivity:

public class MyActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "net.motameni.alisapp.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    MyCurrentLocationListener locationListener = new MyCurrentLocationListener();
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}

and MyCurrentLocationListener is this:

public class MyCurrentLocationListener implements LocationListener {

public void onLocationChanged(Location location) {
    TextView textView = (TextView) findViewById(R.id.location_message);
    textView.setTextSize(40);
    textView.setText("hello");
    setContentView(textView);
}

What is wrong???


Solution

  • You can not do UI changes from non UI function.

    for doing this either you have to pass your view object to listener method, Or you have to create a method in your activity class that receive value from listener and updated value of your view.

    update code in your oncreate:

    TextView tv = (TextView)findViewById(R.id.tv1);
    MyCurrentLocationListener locationListener = new MyCurrentLocationListener(tv);
    

    and in your listener class create a constructor -

      TextView textView;
      public MyCurrentLocationListener (TextView  tv){
            textView = tv;
      }
    

    and form location change -

    public void onLocationChanged(Location location) {
    
     textView.setTextSize(40);
     textView.setText("hello");
    }
    

    this is the best way.