2014-10-10 2 views
-1

У меня есть фрагмент, который я хочу, чтобы отобразить ListViewошибка NullPointerException в моей ListView

вот часть моего кода

public class ExpensesDaily extends Fragment{ 

    @Override 
    public void onCreate(Bundle savedInstanceState){ 
     super.onCreate(savedInstanceState); 
     lvExpenses = (ListView) getActivity().findViewById(android.R.id.list); 
     Cursor expensesListCursor; 
     DbControl dbc = new DbControl(getActivity()); 
     try { 
      dbc.open(); 
      expensesListCursor = dbc.listExpenses(); 
      String[] from = new String[] {"description", "cost" }; 
      ListAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.list_expenses, expensesListCursor, from, new int[] { R.id.tvDescription, R.id.tvCost },0); 
      lvExpenses.setAdapter(adapter); 
     }catch (SQLException e){ 

     } 
    dbc.close(); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     final View rootView = inflater.inflate(R.layout.expenses_daily, container, false); 
     return rootView; 
    } 
} 

** DbControl класс **

public class DbControl { 

    private SQLiteDatabase database; 
    private MySQLiteHelper dbHelper; 

    public DbControl(Context context) { 
     dbHelper = new MySQLiteHelper(context); 

} 

    public void open() throws SQLException { 
     database = dbHelper.getWritableDatabase(); 
    } 

    public void close() { 
     dbHelper.close(); 
    } 

    public Cursor listExpenses(){ 
     Cursor cursor; 
     cursor = database.query(MySQLiteHelper.TABLE_EXPENSES, new String[] {"id _id", "description, cost"}, "forDate='" + date + "'", null, null, null, "id asc"); 


    if (cursor != null) { 
     cursor.moveToFirst(); 
    } 
    return cursor; 
} 

costs_daily.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/ll_expensesDaily" 
    android:baselineAligned="false"> 

<LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="horizontal" 
     > 
    <ListView 
     android:id="@android:id/list" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"> 
    </ListView> 

</LinearLayout> 
</LinearLayout> 

list_expenses.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" 
    android:padding="7dip"> 
    <TextView 
     android:layout_width="0dip" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.6" 
     android:id="@+id/tvDescription" /> 

    <TextView 
     android:layout_width="0dip" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.3" 
     android:id="@+id/tvCost" /> 

</LinearLayout> 

</LinearLayout> 

, но каждый раз, когда я загружаю фрагмент, он будет отображать эту ошибку

FATAL EXCEPTION: main java.lang.NullPointerException at com.code.imin.mymoneymanaged.ExpensesDaily.onCreate(ExpensesDaily.java:60) 

, который указывает на линии

lvExpenses.setAdapter(adapter) in class ExpensesDaily. 

ответ

3

lvExpenses = (ListView) getActivity().findViewById(android.R.id.list);

Вы не можете позвонить getActivity().findViewById на onCreate, потому что представление еще не было создано. Изменить эту логику onActivityCreated

enter image description here

+1

Вы хотите назвать свои Просмотреть объявления в onCreateView() (с использованием rootView.findViewById (...)) или сохранить rootView как переменную класса шириной и объявить их в onActivityCreated (). – wblaschko

+1

'getActivity(). FindViewById (android.R.id.list)' можно безопасно вызвать 'onActivityCreated' и он вернет представление просто отлично. Не нужно сохранять «rootView» в качестве поля. –

+0

@PedroOliveira не уверен, почему, но мне кажется, что мне нужно использовать rootView.findViewById (...) и не могу просто использовать getActivity(). FindViewById(), потому что это приведет к краху моего приложения с нулевым указателем – imin

Смежные вопросы