1

Je ne comprends pas ce qui ne va pas?NullPointerException mauvais contexte?

list_item

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="?android:attr/activatedBackgroundIndicator"> 


    <ImageView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/imageView" 
     android:src="@drawable/no_avatar"/> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/name" 
     android:layout_gravity="top|center_horizontal" 
     android:layout_marginLeft="10dp"/> 

    <CheckBox 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/checkbox" 
     android:id="@+id/checkBox" 
     android:clickable="true" 
     android:paddingLeft="@dimen/abc_action_bar_overflow_padding_start_material" 
     android:singleLine="false" 
     android:textAppearance="@color/colorAccent" 
     android:layout_gravity="right" /> 
</LinearLayout> 

fragment_list

<android.support.design.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/rootLayout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true"> 

     <ListView 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:id="@+id/listView" 
      android:layout_margin="@dimen/activity_vertical_margin"/> 

    <android.support.design.widget.FloatingActionButton 
     android:id="@+id/fab" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/ic_add_white_24dp" 
     app:layout_anchor="@id/listView" 
     app:layout_anchorGravity="bottom|right|end" 
     app:elevation="6dp" 
     app:pressedTranslationZ="12dp" 
     app:backgroundTint="@color/colorAccent" 
     app:rippleColor="@color/colorPrimary"/> 
</android.support.design.widget.CoordinatorLayout> 

FragmentList.java

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    View v = inflater.inflate(R.layout.fragment_list, container, false); 
    fab = (FloatingActionButton) getView().findViewById(R.id.fab); 
    listView = (ListView) v.findViewById(R.id.listView); 


    //обработка добавления человека - нажатие на fab 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override public void onClick(View v) { 
      //TODO добавление!!! 
      Toast.makeText(v.getContext(), "Новая запись добавлена", Toast.LENGTH_SHORT).show(); 
     } 
    }); 

    //создание курсора 
try{ 
    SQLiteOpenHelper databaseHelper = new DatabaseHelper(v.getContext()); 
    SQLiteDatabase db = databaseHelper.getWritableDatabase(); 
    Cursor cursor = db.query("PEOPLE", new String[] {"_id", "NAME", "CHECKBOX"}, null, null, null, null, null); 
    CursorAdapter listAdapter = new SimpleCursorAdapter(v.getContext(), R.layout.list_item, cursor, new String[]{"NAME", "CHECKBOX"}, new int[]{R.id.name, R.id.checkBox}, 0); 
     listView.setAdapter(listAdapter); 
     //переход к первой записи в курсоре 
     if (cursor.moveToFirst()){ 
      //получение данных из курсора 
      nameText = cursor.getString(1); 
      isAvatar = (cursor.getInt(2)==1); 
      //заполнение чекбокса, тест имени и аватар 
      CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox); 
      TextView textView = (TextView) v.findViewById(R.id.name); 
      ImageView image = (ImageView) v.findViewById(R.id.imageView); 
      checkBox.setChecked(isAvatar); 
      textView.setText(nameText); 
      if (checkBox.isChecked()) { 
       image.setImageResource(R.drawable.avatar); 
      } else image.setImageResource(R.drawable.no_avatar); 
     } 
    } catch (SQLiteException e){ 
     Toast.makeText(v.getContext(), "База данных недоступна", Toast.LENGTH_SHORT).show(); 
    } 

     //обработка нажатия по чекбоксу 
//  checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){ 
//   @Override 
//   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
//    checkBox.isChecked(); 
//   } 
//  }); 

     return v; 
} 





//обработка нажатия пункте списка 
public void onListItemClick(){ 

} 

//закрытие базы данных и курсора 
@Override 
public void onDestroy(){ 
    super.onDestroy(); 
    cursor.close(); 
    db.close(); 
} 

}

Pourquoi checkbox = (CheckBox) v.findViewById (R.id. checkBox) est null ? J'ai essayé beaucoup de variations, mais est devenu stupide ((

debug screenshot

+0

Merci d'avoir collé la capture d'écran, mais veuillez également coller la pile réelle. – ishmaelMakitla

+0

java.lang.NullPointerException à ru.bunakov.testapplication.fragments.FragmentList.onCreateView (FragmentList.java:46) –

+0

full stacktrace a plus de 95000 symboles –

Répondre

0

Vous gonflez la mise en page fragment_list qui ne contient pas la case, imageview ou mode texte. Voilà pourquoi vous obtenez cette erreur. mettre en œuvre cet adaptateur curseur

public class MyCursorAdapter extends CursorAdapter { 

    public MyCursorAdapter(Context context, Cursor cursor, int flags) { 
     super(context, cursor, 0); 
    } 

    @Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 
     return LayoutInflater.from(context).inflate(R.layout.mylist_row, parent, false); 
    } 

    @Override 
    public void bindView(View v, Context context, Cursor cursor) { 

     if (cursor.moveToFirst()){ 
      //получение данных из курсора 
      nameText = cursor.getString(1); 
      isAvatar = (cursor.getInt(2)==1); 
      //заполнение чекбокса, тест имени и аватар 
      CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox); 
      TextView textView = (TextView) v.findViewById(R.id.name); 
      ImageView image = (ImageView) v.findViewById(R.id.imageView); 
      checkBox.setChecked(isAvatar); 
      textView.setText(nameText); 
      if (checkBox.isChecked()) { 
       image.setImageResource(R.drawable.avatar); 
      } else image.setImageResource(R.drawable.no_avatar); 
     } 

    } 

} 

maintenant onCreateview

MyCursorAdapter todoAdapter = new MyCursorAdapter(this.getActivity(), cursor, 0); 
     lvItems.setAdapter(todoAdapter); 
+0

que dois-je faire pour le réparer? peux-tu me soutenir? –

+0

Voir la réponse mise à jour. J'ai mis en place l'adaptateur de curseur pour vous. –

+0

Pourquoi implémente CursorAdapter pas SimpleCursorAdapter? –

0

Vous êtes Loo roi jusqu'à checkBox sur la vue (v): CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox); Cependant v est affecté à (fragment_list) ici View v = inflater.inflate(R.layout.fragment_list, container, false); MAIS fragment_list ne contient pas checkBox et donc v.findViewById(R.id.checkBox) retourne NULL. Lorsque vous utilisez SimpleCursorAdapter comme vous voulez l'utiliser, vous devez créer une classe qui étend SimpleCursorAdapter, vous pouvez alors accéder/gonfler le fichier de disposition "row-item" en getView (final int pos, View view, ViewGroup parent) - vous pourrez alors dire: CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox) .

+0

je ne comprends pas comment faire mon propre adaptateur dans ce cas. pouvez-vous m'écrire des exemples de lignes de code? –

+0

J'ai passé plus de 6 heures avec ce problème et j'ai désespéré –

+0

Regardez [cet exemple simple de la façon de créer un adaptateur de curseur personnalisé] (http://blog.cluepusher.dk/2009/11/16/creating-a -custom-cursoradapter-for-android /) - Regardez aussi [cet exemple] (http://stackoverflow.com/questions/21519893/any-good-example-for-checkbox-with-simplecursoradapter) - bien que la personne voulût une fonctionnalité différente, cela montre comment inclure une case à cocher dans l'adaptateur - dans votre cas, je suppose que le checkBox est coché/décoché en fonction de la valeur de votre curseur – ishmaelMakitla