在Listview中使用自定义适配器和自定义类时,应用崩溃

时间:2019-06-24 14:48:06

标签: java android firebase-realtime-database

在我们的应用中,日记列表应包含日记图片,后跟日记名称,为此我们使用了自定义类和自定义适配器。但是该应用程序崩溃了。

//This is Word class (custom class)

public class Word
{
String dname;

public Word()
{
    //default constructor
}

public Word(String dname) {
    this.dname=dname;
}

/*public void setDiaryName(String dname)
{
    this.dname=dname;
}*/

public String getDiaryName()
{
    return dname;
}
}



//the custom adapter

public class ContentAdapter extends ArrayAdapter<Word>
{
    Display d;
    public ContentAdapter(Activity context, ArrayList<Word>title)

{
    super(context, 0, title);
}

public View getView(int position, View convertView, ViewGroup parent) {

    // Check if the existing view is being reused otherwise inflate the view

    View listItemView = convertView;

    if (listItemView == null) {

        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.contents, parent, false);

    }

    Word w = getItem(position);

    TextView mt = (TextView) listItemView.findViewById(R.id.exp);

    mt.setText(w.getDiaryName());

    mt.setVisibility(View.VISIBLE);

    return listItemView;
}
}




//the fragment in which list of diaries is displayed
public class HistoryFragment extends Fragment 
{
    Word di;
    ListView lv;
    DatabaseReference reference;
    FirebaseAuth mAuth = FirebaseAuth.getInstance();
    Activity context;
    public HistoryFragment(){
    //default constructor
    }
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
    final View view = inflater.inflate(R.layout.scrolllist, container, false);

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference uidRef = rootRef.child("image").child(uid);
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //List<String> cities = new ArrayList<>();
            final ArrayList<Word> cities = new ArrayList<>();
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                String cityName = ds.getKey();
                cities.add(new Word(cityName));
            }
            ListView listView = (ListView)view.findViewById(R.id.list_of_ds);
            ContentAdapter arrayAdapter = new ContentAdapter(context,cities);
            listView.setAdapter(arrayAdapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            //Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
        }
    };
    uidRef.addListenerForSingleValueEvent(valueEventListener);
    return view;
}

}

运行应用程序时,在选择历史记录片段时,发生以下错误- java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.Object android.content.Context.getSystemService(java.lang.String)'

    //scrolllist.xml (for listview)    
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/drawable_gradient">
<ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list_of_ds"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ListView>


<Button
    android:id="@+id/add_images"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add Images"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"/>

<Button
    android:id="@+id/new_diary"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Diary?"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"/>

</RelativeLayout>





//contents.xml (the custom view of diary pic and diary name)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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">

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="88dp">



    <ImageView

        android:id="@+id/image_of_user"

        android:layout_width="88dp"

        android:layout_height="88dp"

        android:src="@drawable/diarypic"
        android:layout_marginTop="20dp"/>



    <RelativeLayout

        android:id="@+id/text_container"

        android:layout_width="match_parent"

        android:layout_height="88dp"

        android:layout_alignParentBottom="true"

        android:layout_alignParentRight="true"

        android:layout_alignParentTop="true"

        android:layout_toRightOf="@id/image_of_user"

        android:orientation="vertical"

        android:paddingLeft="16dp"

        android:layout_marginTop="20dp">



        <TextView

            android:id="@+id/exp"

            android:layout_width="match_parent"

            android:layout_height="44dp"

            android:layout_weight="1"

            android:gravity="bottom"

            android:textAppearance="?android:textAppearanceMedium"

            android:textColor="@android:color/background_dark"

            android:textStyle="bold"

            android:text="lutti" />

    </RelativeLayout>
</RelativeLayout>
</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

您的活动上下文为空。您尚未初始化它。

public class Word
{
String dname;

public Word()
{
    //default constructor
}

public Word(String dname) {
    this.dname=dname;
}

/*public void setDiaryName(String dname)
{
    this.dname=dname;
}*/

public String getDiaryName()
{
    return dname;
}
}



//the custom adapter

public class ContentAdapter extends ArrayAdapter<Word>
{
    Display d;
    public ContentAdapter(Context context, ArrayList<Word>title)

{
    super(context, 0, title);
}

public View getView(int position, View convertView, ViewGroup parent) {

    // Check if the existing view is being reused otherwise inflate the view

    View listItemView = convertView;

    if (listItemView == null) {

        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.contents, parent, false);

    }

    Word w = getItem(position);

    TextView mt = (TextView) listItemView.findViewById(R.id.exp);

    mt.setText(w.getDiaryName());

    mt.setVisibility(View.VISIBLE);

    return listItemView;
}
}




//the fragment in which list of diaries is displayed
public class HistoryFragment extends Fragment 
{
 Context context;

    Word di;
    ListView lv;
    DatabaseReference reference;
    FirebaseAuth mAuth = FirebaseAuth.getInstance();
    public HistoryFragment(){
    //default constructor
    }

//The following method will get the context from the activity to which the fragment is attached 
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
    }
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
    final View view = inflater.inflate(R.layout.scrolllist, container, false);

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference uidRef = rootRef.child("image").child(uid);
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //List<String> cities = new ArrayList<>();
            final ArrayList<Word> cities = new ArrayList<>();
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                String cityName = ds.getKey();
                cities.add(new Word(cityName));
            }
            ListView listView = (ListView)view.findViewById(R.id.list_of_ds);
            ContentAdapter arrayAdapter = new ContentAdapter(context,cities);
            listView.setAdapter(arrayAdapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            //Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
        }
    };
    uidRef.addListenerForSingleValueEvent(valueEventListener);
    return view;
}
}