尝试在空对象上调用虚方法'void android.widget.TextView.setText(java.lang.CharSequence)'

时间:2016-04-19 16:08:49

标签: java android android-fragments

我正在尝试从数据库向textview(In fragment)插入一些数据。 这是片段:

SQLiteOpenHelper deck_helper = new DeckDatabaseHelper(getActivity());
    SQLiteDatabase db = deck_helper.getReadableDatabase();
    TextView name = (TextView) getActivity().findViewById(R.id.textView2);
    Cursor cursor = db.query("DECK", new String[]{"NAME"}, "_id=?",
            new String[]{Integer.toString(1)}, null, null, null);
        try {

            if (cursor.moveToFirst()) {
                String nameText = cursor.getString(0);
                name.setText(nameText);

            }
            cursor.close();
            db.close();
        } catch (SQLException e) {
            Toast toast = Toast.makeText(getActivity(),
                    "Database unavailable", Toast.LENGTH_SHORT);
            toast.show();
        }

和DeckDatabaseHelper

 public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE DECK (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + "NAME TEXT, "
            + "CLASS TEXT, "
            +  "IMAGE_CLASS INTEGER"
            + ");");
    ContentValues values = new ContentValues();
    values.put("NAME", "Mage");
    values.put("CLASS", "Mage");
    values.put("IMAGE_CLASS", "123");
    db.insert("DECK",null,values);

}

我认为Textview应该显示“Mage”,但是会出现此错误

  

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.TextView.setText(java.lang.CharSequence)'                                                                                       在com.example.nikolaypavlin.deck.Fragments.DeckManagerFragment.onCreateView(DeckManagerFragment.java:54)

我确信textView2存在

<FrameLayout 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"
tools:context="com.example.nikolaypavlin.deck.Fragments.DeckManagerFragment">

<!-- TODO: Update blank fragment layout -->

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listView"
    android:headerDividersEnabled="false"
    android:visibility="visible" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button"
    android:layout_gravity="right|center_vertical" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/textView2"
    android:layout_gravity="right|top" />

0 个答案:

没有答案