BaseAdapter返回null

时间:2016-09-08 06:14:36

标签: android android-layout nullpointerexception

我有一个带折叠单元视图的片段

这是mainfragment -

public class FriendFragmentMain extends Fragment {

private static final String TAG = FriendFragmentMain.class.getSimpleName();
private FriendsCellListAdapter friendsCellListAdapter;
private List<FriendsItem> friendsItems;
private String URL_FRIEND="http://212.224.76.127/friends/friends.json";
private FragmentActivity fragmentActivity;
private Activity mActivity;
private ListView friendsListView;

public static FriendFragmentMain newInstance(){
    FriendFragmentMain friendFragmentMain = new FriendFragmentMain();
    return friendFragmentMain;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.friend_fragment_main, container, false);

    friendsListView = (ListView) getActivity().findViewById(R.id.friend_super_list);

    friendsItems = new ArrayList<>();
    friendsCellListAdapter = new FriendsCellListAdapter(mActivity, friendsItems);
    friendsListView.setAdapter(friendsCellListAdapter);

    friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
            ((FoldingCell) view).toggle(false);
            friendsCellListAdapter.registerToggle(pos);
        }
    });

    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Cache.Entry entry = cache.get(URL_FRIEND);
    if (entry != null){
        try {
            String data = new String(entry.data, "UTF-8");
            try {
                parseJsonFriend(new JSONObject(data));
            } catch (JSONException e){
                e.printStackTrace();
            }
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    } else {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                URL_FRIEND, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                VolleyLog.d(TAG, "Response:" + response.toString());
                if (response != null) {
                    parseJsonFriend(response);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "ERROR:" + error.getMessage());
            }
        });
        AppController.getInstance().addToRequestQueue(jsonObjectRequest);
    }

    return view;
}

private void parseJsonFriend(JSONObject response){
    try {
        JSONArray friendArray = response.getJSONArray("friends");
        for (int i =0; i < friendArray.length(); i++){
            JSONObject friendObj = (JSONObject) friendArray.get(i);

            FriendsItem item = new FriendsItem();
            item.setId(friendObj.getInt("id"));
            item.setName(friendObj.getString("name"));
            item.setProfilePic(friendObj.getString("profilePic"));
            item.setBackgroundImage(friendObj.getString("backgroundImage"));
            item.setStatus(friendObj.getString("status"));
            item.setWork(friendObj.getString("work"));
            item.setLocation(friendObj.getString("location"));

            String friendUrl = friendObj.isNull("website")? null : friendObj
                    .getString("website");
            item.setWebsite(friendUrl);

            friendsItems.add(item);
        }
        friendsCellListAdapter.notifyDataSetChanged();
    } catch (JSONException e){
        e.printStackTrace();
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    mActivity = activity;
}
}

基本适配器看起来像这样 -

public class FriendsCellListAdapter extends BaseAdapter{
private HashSet<Integer> unfoldedIndexes = new HashSet<>();
private View.OnClickListener defaultMessageButton;
private View.OnClickListener defaultViewProfileButton;
private Activity activity;
private Context context;
private LayoutInflater inflater;

private List<FriendsItem> friendsItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();


public FriendsCellListAdapter(Activity activity, List<FriendsItem> friendsItems){
    this.activity = activity;
    this.friendsItems = friendsItems;
}

@Override
public int getCount() {
    return friendsItems.size();
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public Object getItem(int position) {
    return friendsItems.get(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (imageLoader == null)
        imageLoader = AppController.getInstance().getImageLoader();
    if (inflater==null)
        inflater = (LayoutInflater)activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    FriendsItem item = friendsItems.get(position);

    FoldingCell cell = (FoldingCell) convertView;
    ViewHolder viewHoler;

    if (cell == null){
        viewHoler = new ViewHolder();
        cell = (FoldingCell) inflater.inflate(R.layout.friends_cell, parent, false);

        viewHoler.profilePic = (NetworkImageView) cell.findViewById(R.id.friends_profile_pic);
        viewHoler.clientName = (LoginTextView) cell.findViewById(R.id.client_name);
        viewHoler.friendStatus = (LoginTextView) cell.findViewById(R.id.friend_status);
        viewHoler.backgroundImage = (NetworkImageView) cell.findViewById(R.id.friend_background_image);
        viewHoler.friendAvatar = (NetworkImageView) cell.findViewById(R.id.friends_avatar);
        viewHoler.friendName = (LoginTextView) cell.findViewById(R.id.friend_name);
        viewHoler.friendLocation = (LoginTextView) cell.findViewById(R.id.friend_location);
        viewHoler.friendURL = (LoginTextView) cell.findViewById(R.id.friend_url);
        viewHoler.friendWork = (LoginTextView) cell.findViewById(R.id.friend_work);
        cell.setTag(viewHoler);
    } else {
        if (unfoldedIndexes.contains(position)){
            cell.unfold(true);
        } else {
            cell.fold(true);
        }
        viewHoler = (ViewHolder) cell.getTag();
    }

    viewHoler.clientName.setText(item.getName());
    viewHoler.friendName.setText(item.getName());

    //chech for empty status
    if (!TextUtils.isEmpty(item.getStatus())){
        viewHoler.friendStatus.setText(item.getStatus());
        viewHoler.friendStatus.setVisibility(View.VISIBLE);
    } else {
        viewHoler.friendStatus.setVisibility(View.GONE);
    }

    //check for empty location
    if (!TextUtils.isEmpty(item.getLocation())){
        viewHoler.friendLocation.setText(item.getLocation());
        viewHoler.friendLocation.setVisibility(View.VISIBLE);
    } else {
        viewHoler.friendLocation.setVisibility(View.GONE);
    }

    //check for null url
    if (item.getWebsite() != null){
        viewHoler.friendURL.setText(Html.fromHtml("<a href=\""+item.getWebsite()+"\">" + item.getWebsite()+"</a>"));
        viewHoler.friendURL.setMovementMethod(LinkMovementMethod.getInstance());
        viewHoler.friendURL.setVisibility(View.VISIBLE);
    } else {
        viewHoler.friendURL.setVisibility(View.GONE);
    }

    //check for empty work
    if (!TextUtils.isEmpty(item.getWork())){
        viewHoler.friendWork.setText(item.getWork());
        viewHoler.friendWork.setVisibility(View.VISIBLE);
    }else {
        viewHoler.friendWork.setVisibility(View.GONE);
    }

    //profile pic
    viewHoler.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
    viewHoler.friendAvatar.setImageUrl(item.getProfilePic(), imageLoader);

    //background image
    viewHoler.backgroundImage.setImageUrl(item.getBackgroundImage(), imageLoader);

    return convertView;
}

public void registerToggle(int position){
    if (unfoldedIndexes.contains(position))
        registerFold(position);
    else
        registerUnfold(position);
}

public void registerFold(int position){unfoldedIndexes.remove(position);}

public void registerUnfold(int position){
    unfoldedIndexes.add(position);
}

private class ViewHolder{
    NetworkImageView profilePic;
    LoginTextView clientName;
    LoginTextView friendStatus;
    NetworkImageView backgroundImage;
    NetworkImageView friendAvatar;
    LoginTextView friendName;
    LoginTextView friendLocation;
    LoginTextView friendURL;
    LoginTextView friendWork;
}
}

现在当我运行它时会抛出 -

Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                          at com.evolustudios.askin.askin.src.fragments.FriendFragmentMain.onCreateView(FriendFragmentMain.java:60)

这个错误。我无法找出为什么抛出一个空对象?任何人都可以了解为什么它显示空对象。

视图在这里 - friends_cell

    <com.ramotion.foldingcell.FoldingCell xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    xmlns:folding-cell="http://schemas.android.com/apk/res-auto"
    folding-cell:additionalFlipsCount="2"
    folding-cell:animationDuration="1300"
    folding-cell:backSideColor="@color/bgBackSideColor">

    <include layout="@layout/friends_content_layout"/>

    <include layout="@layout/friends_cell_title_layout"/>

</com.ramotion.foldingcell.FoldingCell>

friends_cell_title_layout -

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false">

<!--LEFT Part -->
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="155dp"
    android:layout_weight="3"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="20dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="20dp"
    android:background="@color/feed_item_border">
    <com.android.volley.toolbox.NetworkImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/friends_profile_pic"
        android:scaleType="fitCenter"/>
</RelativeLayout>

<!--RIGHT Part-->
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:paddingBottom="20dp"
    android:paddingEnd="20dp"
    android:paddingStart="15dp"
    android:paddingTop="20dp"
    android:background="@color/feed_item_border">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:id="@+id/title_from_to_dots"
        android:layout_marginEnd="10dp"
        android:src="@drawable/from_to_purple"/>
    <com.evolustudios.askin.askin.src.customfonts.LoginTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/client_name"
        android:layout_alignTop="@+id/title_from_to_dots"
        android:layout_marginTop="-5dp"
        android:layout_toEndOf="@+id/title_from_to_dots"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:singleLine="true"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="16sp"/>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:id="@+id/friend_profile_divider"
        android:layout_below="@+id/client_name"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:layout_toEndOf="@+id/title_from_to_dots"
        android:src="@color/contentDividerLine"/>
    <com.evolustudios.askin.askin.src.customfonts.LoginTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/friend_status"
        android:layout_below="@+id/friend_profile_divider"
        android:layout_toEndOf="@+id/title_from_to_dots"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:singleLine="true"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="16sp"/>
</RelativeLayout>

和friend_content_layout -

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

    <!--Content header line-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/text_password"
        android:paddingBottom="7dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="7dp">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true"
            android:src="@drawable/menu_icon"/>
    </RelativeLayout>

    <!--Content header Image-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.android.volley.toolbox.NetworkImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/friend_background_image"
            android:scaleType="centerCrop"/>
    </RelativeLayout>

    <!--Content body layout-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="6dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="9dp">

        <!--avatar and name-->
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent">

            <com.android.volley.toolbox.NetworkImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/friends_avatar"
                android:layout_alignParentStart="true"
                android:layout_marginBottom="5dp"/>

            <com.evolustudios.askin.askin.src.customfonts.LoginTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/friend_name"
                android:layout_alignTop="@+id/friends_avatar"
                android:layout_marginBottom="2dp"
                android:layout_marginStart="10dp"
                android:layout_toEndOf="@+id/friends_avatar"
                android:textColor="@color/mainTextColor"
                android:textSize="18sp"
                android:textStyle="bold"/>

            <com.evolustudios.askin.askin.src.customfonts.LoginTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/friend_location"
                android:layout_alignStart="@+id/friend_name"
                android:layout_marginBottom="-2dp"
                android:layout_marginStart="3dp"
                android:layout_below="@+id/friend_name"
                android:textColor="#a9a9a9"
                android:textSize="12sp"/>
        </RelativeLayout>

        <!--Divider Line-->
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginBottom="6dp"
            android:layout_marginTop="9dp"
            android:src="@color/contentDividerLine"/>

        <!--Address Part-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:baselineAligned="false"
            android:orientation="horizontal">

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1">

                <com.evolustudios.askin.askin.src.customfonts.LoginTextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/url_badge"
                    android:textColor="#a9a9a9"
                    android:layout_alignParentStart="true"
                    android:text="WEBSITE"/>
                <com.evolustudios.askin.askin.src.customfonts.LoginTextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/friend_url"
                    android:layout_alignStart="@+id/url_badge"
                    android:layout_below="@+id/url_badge"
                    android:textColor="@color/mainTextColor"
                    android:textSize="18sp"
                    android:textStyle="bold"/>
            </RelativeLayout>
        </LinearLayout>

        <!--Divider Line-->
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginBottom="6dp"
            android:layout_marginTop="7dp"
            android:src="@color/contentDividerLine"/>

        <!--Work Part-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:baselineAligned="false"
            android:orientation="horizontal">

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1">

                <com.evolustudios.askin.askin.src.customfonts.LoginTextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/work_badge"
                    android:textColor="#a9a9a9"
                    android:layout_alignParentStart="true"
                    android:text="WORK"/>
                <com.evolustudios.askin.askin.src.customfonts.LoginTextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/friend_work"
                    android:layout_alignStart="@+id/work_badge"
                    android:layout_below="@+id/work_badge"
                    android:textColor="@color/mainTextColor"
                    android:textSize="18sp"
                    android:textStyle="bold"/>
            </RelativeLayout>
        </LinearLayout>

        <!--Buttons-->
        <com.evolustudios.askin.askin.src.customfonts.LoginTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/friend_send_message"
            android:layout_marginTop="16dp"
            android:background="@color/btnRequest"
            android:padding="10dp"
            android:text="Send Message"
            android:textAlignment="center"
            android:textColor="@color/mainTextColor"
            android:textSize="20sp"/>
        <com.evolustudios.askin.askin.src.customfonts.LoginTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/friend_view_profile"
            android:layout_marginTop="16dp"
            android:background="@color/btnRequest"
            android:padding="10dp"
            android:text="View Profile"
            android:textAlignment="center"
            android:textColor="@color/mainTextColor"
            android:textSize="20sp"/>
    </LinearLayout>
</LinearLayout>

1 个答案:

答案 0 :(得分:0)

在将import java.awt.Color; import java.awt.Component; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; /** * * @author Innocentus */ public class MultiLineJTable extends JTable{ public MultiLineJTable(){ super(); } public MultiLineJTable(Object[][] row, String[] col){ DefaultTableModel dtm = new DefaultTableModel(row,col); this.setModel(dtm); addFireEvent(); this.setDefaultRenderer(Object.class, new MultiLineCellRendererx()); } @Override public void setModel(TableModel dataModel) { if (dataModel == null) { throw new IllegalArgumentException("Cannot set a null TableModel"); } if (this.dataModel != dataModel) { TableModel old = this.dataModel; if (old != null) { old.removeTableModelListener(this); } this.dataModel = dataModel; dataModel.addTableModelListener(this); tableChanged(new TableModelEvent(dataModel, TableModelEvent.HEADER_ROW)); firePropertyChange("model", old, dataModel); if (getAutoCreateRowSorter()) { setRowSorter(new TableRowSorter<TableModel>(dataModel)); } addFireEvent(); } try { this.setDefaultRenderer(Object.class, new MultiLineCellRendererx()); } catch (Exception e) { } } public void refreshTable(){ JTable tbl = this; for (int row = 0; row < tbl.getRowCount(); row++){ int rowHeight = tbl.getRowHeight(); for (int column = 0; column < tbl.getColumnCount(); column++){ Component comp = tbl.prepareRenderer(tbl.getCellRenderer(row, column), row, column); rowHeight = Math.max(rowHeight, comp.getPreferredSize().height); } tbl.setRowHeight(row, rowHeight); } } private void addFireEvent(){ this.getModel().addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { switch (e.getType()) { case TableModelEvent.DELETE: refreshTable(); break; case TableModelEvent.INSERT: refreshTable(); break; case TableModelEvent.UPDATE: refreshTable(); break; } } }); } } class MultiLineCellRendererx extends JTextArea implements TableCellRenderer { public MultiLineCellRendererx() { setLineWrap(true); setWrapStyleWord(true); setSelectionColor(Color.GREEN); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setText((String)value); setSize(table.getColumnModel().getColumn(column).getWidth(),this.getPreferredSize().height); setSelectionColor(Color.GREEN); if (isSelected){ setBackground(table.getSelectionBackground()); setForeground(table.getSelectionForeground()); }else{ setBackground(table.getBackground()); setForeground(table.getForeground()); } return this; } } 传递给friendsItems

之前初始化friendsCellListAdapter
 friendsItems = new ArrayList<FriendsItem>(); // add this line
 friendsCellListAdapter = new FriendsCellListAdapter(mActivity, friendsItems);
 friendsListView.setAdapter(friendsCellListAdapter);