1

Ich kann nicht verstehen, was los ist?NullPointerException falscher Kontext?

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(); 
} 

}

Warum CheckBox checkBox = (CheckBox) v.findViewById (R.id. checkBox) ist null ? ich viele Variationen versucht, wurde aber dumm ((

debug screenshot

+0

Vielen Dank für das Einfügen des Screenshots, aber bitte fügen Sie auch den eigentlichen Stacktrace ein. – ishmaelMakitla

+0

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

+0

full stacktrace hat mehr 95000 Symbole –

Antwort

0

Sie aufblasen fragment_list Layout, das nicht Checkbox, Imageview oder Textansicht enthält. Deshalb sollten Sie diesen Fehler bekommen. implementieren diesen Cursor-Adapter

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); 
     } 

    } 

} 

jetzt in onCreateview

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

was muss ich tun, um es zu beheben? Kannst du mich unterstützen? –

+0

Siehe die aktualisierte Antwort. Ich habe den Cursor-Adapter für Sie implementiert. –

+0

Warum implementiert CursorAdapter nicht SimpleCursorAdapter? –

0

Sie sind loo König bis checkBox auf der Ansicht (v): CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox); Noch v zugeordnet ist (fragment_list) hier View v = inflater.inflate(R.layout.fragment_list, container, false); ABER fragment_list enthält keine checkBox und so v.findViewById(R.id.checkBox) kehrt null. Wenn Sie den SimpleCursorAdapter verwenden, wie Sie ihn verwenden möchten, müssen Sie eine Klasse erstellen, die SimpleCursorAdapter erweitert. Sie können dann auf die Layoutdatei "row-item" in getView (final int pos, View view, ViewGroup parent) zugreifen/sie können dann sagen: CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox) .

+0

ich kann nicht verstehen, wie in diesem Fall meinen eigenen Adapter machen. kannst du mir ein paar Beispielzeilen schreiben? –

+0

Ich habe mehr als 6 Stunden mit diesem Problem verbracht und verzweifelt –

+0

Betrachten Sie [dieses einfache Beispiel, wie man einen benutzerdefinierten Cursor-Adapter erstellt] (http://blog.cluepusher.dk/2009/11/16/creating-a -custom-cursoradapter-for-android /) - Schauen Sie auch [dieses Beispiel] (http://stackoverflow.com/questions/21519893/any-good-example-for-checkbox-with-simplecursoradapter) - obwohl die Person wollte eine andere Funktionalität, dies zeigt, wie ein Kontrollkästchen im Adapter enthalten - in Ihrem Fall nehme ich an, dass das Kontrollkästchen auf einem gewissen Wert von Ihrem Cursor – ishmaelMakitla