2015-11-30 4 views
1

Я искал по всему Интернету и просто не могу найти решение моей проблемы. И проблема в том, что я не могу вставить свои координаты GPS в TextView. Аварии приложения на этой линииAndroid Studio crash on findViewById

TextView latText = (TextView) findViewById(R.id.Latitude); 

Я установил

setContentView(R.layout.activity_show_gps); 

, прежде чем пытаться findViewById, но она до сих пор не работает. Также у меня есть id на этом TextView, так что это не проблема.

Вот полный код:

package com.example.user1.gpsgpsgps; 

import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Display; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.TextView; 

public class ShowGPS extends AppCompatActivity implements LocationListener { 

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

     LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     ShowGPS locationListener = new ShowGPS(); 

     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     double lat = location.getLatitude(); 
     double lon = location.getLongitude(); 

     TextView latText = (TextView) findViewById(R.id.Latitude); 
     TextView lonText = (TextView) findViewById(R.id.Longitude); 

     latText.setText("Nothing works..."); 
     lonText.setText("Nothing works here either..."); 
    } 

    @Override 
    public void onStatusChanged(String s, int i, Bundle bundle) { 

    } 

    @Override 
    public void onProviderEnabled(String s) { 

    } 

    @Override 
    public void onProviderDisabled(String s) { 

    } 
} 

А вот мой activity_show_gps.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
android:paddingBottom="@dimen/activity_vertical_margin" 
tools:context="com.example.markus.gps.GPSActivity"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/Latitude" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="48dp" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/lon" 
    android:id="@+id/Longitude" 
    android:layout_below="@+id/Latitude" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="28dp" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/acc" 
    android:id="@+id/Accuracy" 
    android:layout_below="@+id/Longitude" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="27dp" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/alt" 
    android:id="@+id/Altitude" 
    android:layout_below="@+id/Accuracy" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="28dp" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/time" 
    android:id="@+id/Time" 
    android:layout_centerVertical="true" 
    android:layout_alignStart="@+id/Altitude" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/refreshGPS" 
    android:id="@+id/RefreshGPSButton" 
    android:layout_marginTop="34dp" 
    android:layout_below="@+id/Time" 
    android:layout_centerHorizontal="true" 
    android:onClick="onRefreshGPSButtonClick" /> 

</RelativeLayout> 

Это, как я называю, чтобы начать GPS (в основном):

public void onGPSButtonClick(View view) { 
    Intent intent = new Intent(this, ShowGPS.class); 
    startActivity(intent); 
} 

Я пытался получить эту работу в течение почти 6 часов, и скоро я потеряю сознание. Есть идеи?

ответ

2
ShowGPS locationListener = new ShowGPS(); 

Никогда не используйте новый оператор класса, который расширяет Activity. Используя новый оператор, Activity не проходит через свой жизненный цикл, onCreate не вызывается и вы не создаете иерархию View. Более важный действительныйContext не прилагается к вашему Activity, что делает findViewById непригодным

Эта линия

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 

должен быть

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); 

ShowGPS реализует уже LocationListener, вам не нужно инстанцировать его только для перечня

+0

Это сработало. Спасибо вам большое, вы сделали мой день! – xpoopx

+0

приветствуются – Blackbelt

0

Инициализировал ваш TextView внутри вашего Oncreate после setContentView и имел ваш объект textView как глобальный экземпляр.

Смежные вопросы