[英]Null Pointer exception when trying to update textviews
好的,應用程序應該做什么:
目前正在發生的是代碼一直運行直到最后一個方法調用(update();在代碼中標記)並且logcat在第146行報告了一個nullPointerException,我在代碼中標記了。
重要注意事項!
昨天我遇到了一個非常類似的問題,但是我嘗試做同樣的事情來解決這個問題但是沒有用。 我發布了它正在訪問的xml布局文件。 我昨天遇到的錯誤是布局文件沒有其中一個按鈕的定義(我現在刪除了)。
這是我的主要課程。
public class GPSMain extends Activity {
protected PowerManager powerManager;
protected PowerManager.WakeLock wL;
//text views to display latitude, longitude, speed and G force values
static TextView latituteField, longitudeField, kmphSpeedField, avgKmphField, topKmphField, accText, totalDistance;
//objects to store information for GPS locations and current, top, total and average speed
protected static double lat = 0, lon = 0, kmphSpeed = 0, avgKmph = 0, totalKmph = 0, topKmph = 0;
protected static float distanceBetweenPoints = 0.0f;
protected static Location previousLocation;
//accelerometer values
static String a = "x", b = "y", c = "z";
//context for Toast views
private Context context;
//The stop and start button
static Button button;
//switch to alternate between stop and start features
private int buttonSwitch = 2;
static int counter = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
context = this;
//gives the button the start value
button = (Button) findViewById(R.id.startbutton);
//calls the method to the initial button listener
switchButton();
//sets up the text views to display results
latituteField = (TextView) findViewById(R.id.lat);
longitudeField = (TextView) findViewById(R.id.lon);
totalDistance = (TextView) findViewById(R.id.totaldistance);
kmphSpeedField = (TextView) findViewById(R.id.kmph);
avgKmphField = (TextView) findViewById(R.id.avgkmph);
topKmphField = (TextView) findViewById(R.id.topkmph);
accText = (TextView) findViewById(R.id.acctext);
}
//defines the button functions
void switchButton(){
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(buttonSwitch%2==0){
buttonSwitch++;
startService();
}
else
{
buttonSwitch++;
stopService();
update(); //update method call
}
}
});
}
//rounds the float values from the accelerometer
static String roundTwoDecimalFloat(float a){
String formattedNum;
NumberFormat nf = new DecimalFormat();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
formattedNum = nf.format(a);
return formattedNum;
}
//starts the 2 services and changes the button from a start button to a stop button
void startService(){
setContentView(R.layout.stop);
GPSMain.button = (Button) findViewById(R.id.stopbutton);
switchButton();
Toast.makeText(context, "Accessing Accelerometer", Toast.LENGTH_LONG).show();
startService(new Intent(this, AccelerometerReader.class));
Toast.makeText(context, "Acquiring GPS Locations", Toast.LENGTH_LONG).show();
startService(new Intent(this, Calculations.class));
}
//stops the two services
void stopService(){
setContentView(R.layout.results);
Toast.makeText(context, "Terminating Accelerometer", Toast.LENGTH_LONG).show();
AccelerometerReader.myManager.unregisterListener(AccelerometerReader.mySensorListener);
stopService(new Intent(this, AccelerometerReader.class));
Toast.makeText(context, "Terminating Connection", Toast.LENGTH_LONG).show();
Calculations.locationManager.removeUpdates(Calculations.locationListener);
stopService(new Intent(this, Calculations.class));
}
//prints the results to the screen
static void update(){
146 latituteField.setText("Current Latitude: "+String.valueOf(lat));
longitudeField.setText("Current Longitude: "+String.valueOf(lon));
totalDistance.setText("Total Distance: "+String.valueOf(distanceBetweenPoints/1000));
kmphSpeedField.setText("Cuttent Speed (kmph): "+String.valueOf(kmphSpeed));
avgKmphField.setText("Average Speed (kmph): "+String.valueOf(avgKmph));
topKmphField.setText("Top Speed (kmph): "+String.valueOf(topKmph));
accText.setText("Accelerometer Values: "+" x: " + a + " y: " + b + " z: " + c);
}
}
這是xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearlayout1"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/hello"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/lat"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Current Latitude: unknown"
/>
<TextView
android:id="@+id/lon"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Current Longitude: unknown"
/>
<TextView
android:id="@+id/totaldistance"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Total Distance (km): unknown"
/>
<TextView
android:id="@+id/kmph"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Current Speed (kmph): unknown"
/>
<TextView
android:id="@+id/avgkmph"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Average Speed (kmph): unknown"
/>
<TextView
android:id="@+id/topkmph"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Top Speed (kmph): unknown"
/>
<TextView
android:id="@+id/acctext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Accelerometer Values: unknown"
/>
</LinearLayout>
問題是你在啟動TextView之前調用switchButton()
方法,即latituteField = (TextView) findViewById(R.id.lat);
因為你有空指針異常。 所以首先在調用switchButton()
之后寫入所有視圖元素的switchButton()
。 我修改了你的代碼。 請嘗試使用以下代碼
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
context = this;
// gives the button the start value
button = (Button) findViewById(R.id.startbutton);
// calls the method to the initial button listener
// sets up the text views to display results
latituteField = (TextView) findViewById(R.id.lat);
longitudeField = (TextView) findViewById(R.id.lon);
totalDistance = (TextView) findViewById(R.id.totaldistance);
kmphSpeedField = (TextView) findViewById(R.id.kmph);
avgKmphField = (TextView) findViewById(R.id.avgkmph);
topKmphField = (TextView) findViewById(R.id.topkmph);
accText = (TextView) findViewById(R.id.acctext);
switchButton();
}
進入更新方法嘗試使用txt=(TextView)findviewbyId(R.id.yourtextid);
當您調用setContentView()時,對先前建立的任何視圖的引用不再有效。
在onCreate()中你setContentView(R.layout.results)然后你建立latitudeField(和其他引用),假設它們沒有返回null,就可以了。 (你沒有提到你提供的XML 哪種布局)。
接下來,您將安裝按鈕偵聽器,該偵聽器調用startService()或stopService(),每個偵聽器都設置一個新的內容視圖,這兩個視圖都不會更新您的View引用; 所有先輩在這一點上都是無效的。 然后調用update(),它嘗試使用無效的引用。
更改視圖時更新引用,或在需要時獲取它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.