2014-04-24 34 views
-1

我是android開發中的新手,已經花了幾個小時。 (eclipse + adt) 這裏有一些額外的單詞,所以我可以發表這個。調用run_time.setText(「t」)時獲取空指針異常setText導致nullPointerException,非常簡單,但沒有想法(android)

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_start_run);  
     TextView run_time = (TextView) findViewById(R.id.run_time); 

     try { 
      run_time.setText("t"); 
     }catch(Exception e) { 
      Log.i("Log", e.getMessage()+"Error!"); // LogCat message 
     } 

     if (savedInstanceState == null) { 
      getSupportFragmentManager().beginTransaction() 
        .add(R.id.container, new PlaceholderFragment()).commit(); 
     } 

    } 

layout activity_start_run.xml 

<LinearLayout 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:orientation="horizontal" > 

    <TextView 
    android:id="@+id/run_time" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="ghjghjghjghjghjghj" /> 

</LinearLayout> 
+0

實際上是所謂的'activity_start_run.xml'這個佈局文件? – nKn

+0

是的,文件名應該是正確的,非常令人沮喪 – user3570219

+0

如果您100%肯定佈局名稱是這樣的,那麼在R和二進制XML文件中的資源ID不同步的情況下清理並重新生成。 – laalto

回答

0

此空指針異常是因爲您的資源未正確加載嘗試清理項目並再次運行將解決。

R.id.run_time這是從加載R.java這是自動生成的文件。清理和重建項目將解決這個問題。

MainActivity.java

package com.example.stacktest; 

import android.os.Bundle; 
import android.app.Activity; 
import android.util.Log; 
import android.widget.TextView; 

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     TextView run_time = (TextView) findViewById(R.id.run_time); 
     try { 
      run_time.setText("t"); 
     }catch(Exception e) { 
      Log.i("Log", e.getMessage()+"Error!"); // LogCat message 
     } 
    } 
} 

和activity_main.xml中

<LinearLayout 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:orientation="horizontal" > 

    <TextView 
     android:id="@+id/run_time" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="ghjghjghjghjghjghj" /> 

</LinearLayout> 
+1

你打算髮布多少份基本相同的答案? – laalto

+0

好吧,我評論的: \t/** \t如果(savedInstanceState == NULL){ \t \t \t getSupportFragmentManager()調用BeginTransaction() \t \t \t \t \t。新增(R.id.container,新。 。PlaceholderFragment())提交(); \t \t} \t \t */ 而沒有更多的錯誤。 – user3570219

相關問題