TextView setText问题

时间:2011-09-05 20:13:35

标签: android

我在从数据库

获取文本后尝试在TextView中设置文本
<TextView 
    android:textAppearance="?android:attr/textAppearanceMedium" 
    android:text="2510.33" 
    android:layout_width="wrap_content" 
    android:id="@+id/so_you_spent"  
    android:layout_height="wrap_content"
    android:gravity="right">
</TextView> 

这是活动:

public class SummaryOverall extends Activity{

    private CfmDbAdapter db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.summary_overall);

        db = new CfmDbAdapter(this);
        db.open();

        fillData();
    }

    private void fillData() {       
        TextView tv = (TextView)findViewById(R.id.so_you_spent);

        Cursor itemCursor = db.fetchAllItemsInOverallSummary();
        if (itemCursor.moveToFirst()) {
            String value = itemCursor.getString(0);         
            tv.setText(value);  //nullpointer exception 
        }                   
    }


}

它向我抛出NullPointerException。为什么呢?

2 个答案:

答案 0 :(得分:2)

  1. 检查itemCursor是否返回您告诉我们的内容(321)
  2. 检查电视是否为空
  3. 如果1为真,请检查数据库连接或查询 如果2为真,那么您可能正在使用不在 summary_overall 布局中的ID

    <强>编辑:
    尝试从xml中删除android:text="2510.33"

答案 1 :(得分:1)

试试这段代码---- :::

并确保xml文件中有textview id idOk .... summary_overall

删除android:text =“2510.33”并设置为android:text =“”

private void fillData() {       
    TextView tv = (TextView)findViewById(R.id.so_you_spent);

    Cursor itemCursor = db.fetchAllItemsInOverallSummary();
    if (itemCursor.moveToFirst()) {
        String value = itemCursor.getString(0); //value taken "321" - string   
        if(value!=null&&value!=""&&tv!=null) {
            tv.setText(value);     
        } else { 
            tv.setText("NO value Found...");     
        }
    }                   
}