Страница 1 из 1

обновить значения в TextView, исключение

Добавлено: 27 мар 2015, 00:41
si4re
Подскажите как обновить значения в TextView?

textView1 инициализируется в onCreate() Activity.
Надо отобразить текст в textView1, когда происходит событие в listner'e GoogleApiClient.ConnectionCallbacks.

метод этого интерфейса:
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
переменная = mLastLocation.getLatitude();
textView1.setText(переменная); // в вот этом месте у меня происходит исключение. textView1 почему-то равно null

в общем задача стоит в следующем:
при изменении местоположения - отобразить новые координаты в TextView

Спасибо.
Полный код:

Код: Выделить всё

public class MainActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;
    LocationRequest mLocationRequest;

    TextView mLatitudeText;
    TextView mLongitudeText;
    Button button1;

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    private static final int REQUEST_RESOLVE_ERROR = 1001;



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

        TextView mLatitudeText = (TextView) findViewById(R.id.mLatitudeText);
        TextView mLongitudeText = (TextView) findViewById(R.id.mLongitudeText);
        Button button1 = (Button) findViewById(R.id.button1);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        Log.i("TAG","  mGoogleApiClient = new GoogleApiClient.Builder(this)");

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds

        View.OnClickListener onClickListener1 = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do here
                //update text
            }
        };

        button1.setOnClickListener(onClickListener1);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mGoogleApiClient.connect();
        Log.i("TAG","onResume() mGoogleApiClient.connect()");

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
            mGoogleApiClient.disconnect();
            Log.i("TAG","onPause() mGoogleApiClient.disconnect()");
        }

    }


    void handleLocation (Location location) {

        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();
    }


    @Override
    public void onConnected(Bundle bundle) {

        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (mLastLocation == null)
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
        else {
            handleLocation(mLastLocation);
        }

         } // end onConnected

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {


        if (result.hasResolution()) {

            try {
                result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
            }
            catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }

        } //end if
        else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Log.i("TAG", "Location services connection failed with code " + result.getErrorCode());
        }

    } // end onConnectionFailed

// methods OnlocationListner
    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

Re: обновить значения в TextView, исключение

Добавлено: 27 мар 2015, 06:19
klblk
Вы показываете полный код, в котором нет textView1 о котором говорите в сообщении выше.
Но все же думаю я вижу где проблема:
[syntax=java5]public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
....
TextView mLatitudeText;
TextView mLongitudeText;
Button button1;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
TextView mLatitudeText = (TextView) findViewById(R.id.mLatitudeText);
TextView mLongitudeText = (TextView) findViewById(R.id.mLongitudeText);
Button button1 = (Button) findViewById(R.id.button1);
...
}
[/syntax]

Вы создаете переменные класса, но в onCreate() работаете с локальными переменными, а все переменные класса не инициализируются и само собой они null.