0

我正在尝试更新一些TextViews. 我有 3 个Main_Activity.XML默认布局PortraitLandscape. 在TextView这些布局中都具有相同的andoid:id

我已经阅读了有关更新的所有内容TextView,但不知道为什么这会导致整个应用程序崩溃。

我想也许TextView txt = (TextView) findViewById(R.id.txtViewActiveTimeProp1)是返回一个空值,然后当我尝试时setText我得到一个空指针异常。有什么想法吗?我已经把

TextView txt = (TextView) findViewById(R.id.txtViewActiveTimeProp1);
String strPref = retrievePrefs("pref_active_times_prop1");
txt.setText(strPref); 

在完成Button onclick后很久发生的事件,setContentView结果与上述相同。验证了我用来TextView在所有 3 个布局中引用出口的 id。

public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    PreferenceManager.setDefaultValues(this, R.xml.preference, false);
    setContentView(R.layout.activity_main);

TextView txt = (TextView) findViewById(R.id.txtViewActiveTimeProp1);
String strPref = retrievePrefs("pref_active_times_prop1");
txt.setText(strPref);
}
4

2 回答 2

1

Hi You have to do findViewById inside onCreate method. since you are doing findViewById inside event listener it is returning null.

Do the below mentioned changes in your code.

public class MainActivity extends Activity {
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

PreferenceManager.setDefaultValues(this, R.xml.preference, false);
setContentView(R.layout.activity_main);

txt = (TextView) findViewById(R.id.txtViewActiveTimeProp1);
String strPref = retrievePrefs("pref_active_times_prop1");
txt.setText(strPref);
}

and inside your click listener

String strPref = retrievePrefs("pref_active_times_prop1");
txt.setText(strPref);

Hope this helps.

于 2012-08-27T12:44:00.600 回答
0

似乎值 String strPref = retrievePrefs("pref_active_times_prop1"); 即将到来 null ,打印 strPref 值并检查

于 2012-08-27T12:58:30.977 回答