我正在尝试在加载时将数据加载到textviews中。我的应用程序使用片段并有三个选项卡。我能够将数据加载到前两个选项卡中,但是当我尝试将数据加载到第三个选项卡时,我得到一个空指针异常。这是代码:
public void readAndLoadDataFromFile()
{
String[] fieldNamesInFile = new String[50];
double[] valuesInFile = new double[50];
// read all the data from file
readAllDataFromFile(fieldNamesInFile, valuesInFile);
// Tab 1
double value1 = valuesInFile[Arrays.asList(fieldNamesInFile).indexOf("Field1")];
// copy the data into the fields
((EditText) findViewById(R.id.editText1)).setText(String.valueOf(value1)); // OK
// Tab 2
double value2 = valuesInFile[Arrays.asList(fieldNamesInFile).indexOf("Field2")];
// copy the data into the fields
((EditText) findViewById(R.id.editText2)).setText(String.valueOf(value2)); // OK
// Tab 3
double value3 = valuesInFile[Arrays.asList(fieldNamesInFile).indexOf("Field3")];
// copy the data into the fields
((EditText) findViewById(R.id.editText3)).setText("123"); // null pointer exception
}
Tab 3的布局XML文件如下(前两个选项卡类似):
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" >
<TextView
android:id="@+id/textView3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Text 3:"
android:clickable="true"
android:gravity="right"
android:layout_weight="2"
android:layout_marginRight="2dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="@+id/editText3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="right"
android:layout_weight="1"
android:layout_marginLeft="2dp"
android:ems="10"
android:text="25"
android:inputType="numberDecimal"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
</TableLayout>
</ScrollView>
我错过了什么?
答案 0 :(得分:0)
有时项目只需要重建R文件。您可以在Eclipse中尝试“清理”选项(选择项目 - &gt;清理并选择您的项目)。您也可以检查R文件以查看条目是否存在。 R文件位于gen
目录中。如果不是,您可以尝试删除R文件,并在再次编译时让它重建,看看它是否出现。
要检查的另一件事是确保被访问的R文件不是Android R文件。检查您的导入,或者通过将((EditText) findViewById(com.yourproject.app.R.id.editText3)).setText("123");
部分设置为您的包名称将行更改为com.yourproject.app
来强制执行此操作。这样做可以确保您获得正确的R文件。
答案 1 :(得分:0)
通过强制导航转到特定标签并加载视图来修复(黑客入侵)此问题。
ActionBar actionBar = getActionBar();
actionBar.setSelectedNavigationItem(2); // go to Tab 3
double value3 = valuesInFile[Arrays.asList(fieldNamesInFile).indexOf("Field3")];
// copy the data into the fields
((EditText) findViewById(R.id.editText3)).setText("123"); // no more null pointer exception
不以自己为荣,但至少它现在解决了这个问题。