数组适配器返回null

时间:2016-09-17 16:51:37

标签: android android-fragments

我有两个适配器和一个片段,我想在两个视图,一个底部和一个回收器视图上显示提要。虽然Json正在使用列表适配器。它不适用于回收者的观点。

这是主要片段

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardExpand;
import it.gmariotti.cardslib.library.internal.CardHeader;
import it.gmariotti.cardslib.library.view.CardViewNative;
import jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout;


public class FeedFragmentAlternative extends Fragment{
private static final String TAG = FeedFragmentAlternative.class.getSimpleName();

private String URL_FEED = "http://api.androidhive.info/feed/feed.json";

private WaveSwipeRefreshLayout mWaveSwipeRefresh;
int duration = 200;

private List<FeedItem> FeedItems;

public static FeedFragmentAlternative newInstance(){
    FeedFragmentAlternative feedFragmentAlternative = new FeedFragmentAlternative();
    return feedFragmentAlternative;
}

private void refresh(){
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mWaveSwipeRefresh.setRefreshing(false);
        }
    },3000);
}

private ExpandablePager pager;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.feed_activity_alternate, container, false);
    final List<FeedItem> myFeedList = new ArrayList<>();
    final FeedExpandableAdapter adapter = new FeedExpandableAdapter(myFeedList);
    pager = (ExpandablePager) getActivity().findViewById(R.id.bottom_feed_container);
    pager.setAdapter(adapter);
    pager.setOnSliderStateChangeListener(new OnSliderStateChangeListener() {
        @Override
        public void onStateChanged(View page, int index, int state) {
            toggleContent(page, state, duration);
        }

        @Override
        public void onPageChanged(View page, int index, int state) {
            toggleContent(page, state, 0);
        }
    });

    final RecyclerView mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.feeds_list_recycler_view);
    mRecyclerView.setHasFixedSize(true);

    final FeedGridAdapter a = new FeedGridAdapter(myFeedList);
    a.setListener(new OnItemClickedListener() {
        @Override
        public void onItemClicked(int index) {
            pager.setCurrentItem(index, false);
            pager.animateToState(ExpandablePager.STATE_EXPANDED);
        }
    });

    mWaveSwipeRefresh = (WaveSwipeRefreshLayout)view.findViewById(R.id.feed_wave_swipe_layout_refresh_alternate);
    mWaveSwipeRefresh.setColorSchemeColors(Color.WHITE, Color.GREEN);
    mWaveSwipeRefresh.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            pager.setAdapter(adapter);
            mRecyclerView.setAdapter(a);
            FeedFragmentAlternative.newInstance();
            refresh();
        }
    });

    mWaveSwipeRefresh.setWaveColor(Color.parseColor("#80C5EFF7"));
    mWaveSwipeRefresh.setMaxDropHeight((int)(mWaveSwipeRefresh.getHeight() * 0.9));
    mRecyclerView.setAdapter(a);

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

        AppController.getInstance().addToRequestQueue(jsonReq);
    }
    return view;
}

private void toggleContent(final View page, final int state, int duration){
    final int headerHeight = (int) getResources().getDimension(R.dimen.header_height);
    if (page != null){
        ValueAnimator animator = state == ExpandablePager.STATE_EXPANDED ? ValueAnimator.ofFloat(1,0): ValueAnimator.ofFloat(0,1);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                page.findViewById(R.id.profile_name_header).setTranslationY(25 * (1 - ((Float) animation.getAnimatedValue())));
                page.findViewById(R.id.profile_name_header).setTranslationX(-headerHeight * (1 - ((Float)animation.getAnimatedValue())));
                page.findViewById(R.id.feed_time_stamp_header).setAlpha(((Float)animation.getAnimatedValue()));
                page.findViewById(R.id.profile_pic_header_image).setAlpha(((Float)animation.getAnimatedValue()));
                page.findViewById(R.id.feed_like_bottom_sheet).setAlpha(((Float) animation.getAnimatedValue()));
            }
        });
        animator.setDuration((long)(duration * 5));
        animator.setInterpolator(new FastOutSlowInInterpolator());
        animator.start();
    }
}

private void parseJsonFeed(JSONObject response){
    try {
        JSONArray feedArray = response.getJSONArray("feed");
        for (int i = 0;i < feedArray.length(); i++){
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            FeedItem item = new FeedItem();
            item.setId(feedObj.getInt("id"));
            item.setName(feedObj.getString("name"));

            String image = feedObj.isNull("image")? null : feedObj
                    .getString("image");
            item.setImge(image);
            item.setStatus(feedObj.getString("status"));
            item.setProfilePic(feedObj.getString("profilePic"));
            item.setTimeStamp(feedObj.getString("timeStamp"));

            String feedUrl = feedObj.isNull("url")? null : feedObj
                    .getString("url");
            item.setUrl(feedUrl);

            FeedItems.add(item);
        }

    } catch (JSONException e){
        e.printStackTrace();
    }
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    initCards();
}

private void initCards(){
    init_standard_header_with_expandcollapse_button();
}
private void init_standard_header_with_expandcollapse_button(){
    Card card = new Card(getActivity());
    CardHeader header = new CardHeader(getActivity());
    header.setButtonExpandVisible(true);
    card.addCardHeader(header);
    CardExpand expand = new CardExpand(getActivity());
    expand.setTitle("expanded");
    CardViewNative cardViewNative = (CardViewNative) getActivity().findViewById(R.id.feed_card_style);
    cardViewNative.setCard(card);
}
   }

网格适配器如下

public class FeedGridAdapter extends RecyclerView.Adapter<FeedGridAdapter.ViewHolder> {
private OnItemClickedListener listener;
private List<FeedItem> mFeedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();

public static class ViewHolder extends RecyclerView.ViewHolder{
    public LoginTextView ProfileNameCell;
    public LoginTextView FeedTimesStampCell;
    public NetworkImageView ProfilepicCell;
    public LoginTextView FeedStatusMgsCell;
    public FeedImageView FeedImageViewCell;
    public ViewGroup container;

    public ViewHolder(RelativeLayout v){
        super(v);
        container = v;
        ProfileNameCell = (LoginTextView) v.findViewById(R.id.client_name_alternate_cell);
        FeedTimesStampCell = (LoginTextView) v.findViewById(R.id.time_stamp_alternate_cell);
        ProfilepicCell = (NetworkImageView) v.findViewById(R.id.profile_pic_alternate_cell);
        FeedStatusMgsCell = (LoginTextView) v.findViewById(R.id.txtStatusMgs_alternate);
        FeedImageViewCell = (FeedImageView) v.findViewById(R.id.feedImage1_alternate);
    }
}

public FeedGridAdapter(List<FeedItem> feedItems){mFeedItems = feedItems;}

@Override
public FeedGridAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    RelativeLayout v = (RelativeLayout) LayoutInflater.from(parent.getContext())
            .inflate(R.layout.feed_card_alternate, parent, false);
    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.ProfileNameCell.setText(mFeedItems.get(position).getName());
    CharSequence timeStampCell = DateUtils.getRelativeTimeSpanString(
            Long.parseLong(mFeedItems.get(position).getTimeStamp()),
            System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
    holder.FeedTimesStampCell.setText(timeStampCell);
    if (!TextUtils.isEmpty(mFeedItems.get(position).getStatus())){
        holder.FeedStatusMgsCell.setText(mFeedItems.get(position).getStatus());
        holder.FeedStatusMgsCell.setVisibility(View.VISIBLE);
    } else {
        holder.FeedStatusMgsCell.setVisibility(View.GONE);
    }

    holder.ProfilepicCell.setImageUrl(mFeedItems.get(position).getImge(), imageLoader);

    if (mFeedItems.get(position).getImge() != null){
        holder.FeedImageViewCell.setImageUrl(mFeedItems.get(position).getImge(), imageLoader);
        holder.FeedImageViewCell.setVisibility(View.VISIBLE);
        holder.FeedImageViewCell
                .setResponseObserver(new FeedImageView.ResponseObserver() {
                    @Override
                    public void onError() {

                    }

                    @Override
                    public void onSuccess() {

                    }
                });
    } else {
        holder.FeedImageViewCell.setVisibility(View.GONE);
    }
    holder.container.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (listener != null)
                listener.onItemClicked(holder.getAdapterPosition());
        }
    });

}

@Override
public int getItemCount() {
    return mFeedItems.size();
}

public void setListener(OnItemClickedListener listener){this.listener = listener;}

}

和可扩展片段是

public class FeedExpandableAdapter extends ExpandablePagerAdapter<FeedItem> {
public FeedExpandableAdapter(List<FeedItem> items){super(items);}
private LayoutInflater inflater;
private Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();

@Override
public Object instantiateItem(ViewGroup container, int position) {
    final ViewGroup rootView = (ViewGroup) LayoutInflater.from(container.getContext()).inflate(R.layout.feed_page_alternative, container, false);

    if (inflater == null)
        inflater = (LayoutInflater)activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (imageLoader == null)
        imageLoader = AppController.getInstance().getImageLoader();

    LoginTextView name = (LoginTextView) rootView.findViewById(R.id.profile_name_header);
    LoginTextView timestamp = (LoginTextView) rootView.findViewById(R.id.feed_time_stamp_header);
    NetworkImageView profilepic = (NetworkImageView) rootView.findViewById(R.id.profile_pic_header_image);

    FeedImageView feedImageView = (FeedImageView) rootView.findViewById(R.id.feed_main_image_bottom_sheet);

    LoginTextView statusMgs = (LoginTextView) rootView.findViewById(R.id.body_bottom_panel_feed);

    name.setText(items.get(position).getName());

    CharSequence timeofStamp = DateUtils.getRelativeTimeSpanString(
            Long.parseLong(items.get(position).getTimeStamp()),
            System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
    timestamp.setText(timeofStamp);

    if (!TextUtils.isEmpty(items.get(position).getStatus())){
        statusMgs.setText(items.get(position).getStatus());
        statusMgs.setVisibility(View.VISIBLE);
    } else {
        statusMgs.setVisibility(View.GONE);
    }

    profilepic.setImageUrl(items.get(position).getProfilePic(), imageLoader);
    if (items.get(position).getImge() != null) {
        feedImageView.setImageUrl(items.get(position).getImge(), imageLoader);
        feedImageView.setVisibility(View.VISIBLE);
        feedImageView
                .setResponseObserver(new FeedImageView.ResponseObserver() {
                    @Override
                    public void onError() {
                    }

                    @Override
                    public void onSuccess() {
                    }
                });
    } else {
        feedImageView.setVisibility(View.GONE);
    }

    return attach(container, rootView, position);
}
}

显示的错误是这样的 -

  

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void com.telenav.expandablepager.ExpandablePager.setAdapter(android.support.v4.view.PagerAdapter)'                                                                                     at com.evolustudios.askin.askin.src.fragments.FeedFragmentAlternative.onCreateView(FeedFragmentAlternative.java:86)

任何人都可以告诉我为什么它返回null? 它可能重复,但我无法弄清楚为什么它返回null

xml - feed_card_alternate

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="350dp"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<it.gmariotti.cardslib.library.view.CardViewNative
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/feed_card_style"
    style="@style/card_external">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/frame_list_card_item_alternate"
        android:background="@drawable/cardpanel"
        android:paddingTop="0dp">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:paddingLeft="15dp"
                android:paddingRight="15dp"
                android:id="@+id/feed_top_panel_alternate"
                android:paddingBottom="25dp">
                <com.android.volley.toolbox.NetworkImageView
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:id="@+id/profile_pic_alternate_cell"
                    android:scaleType="fitCenter"
                    android:paddingTop="15dp"/>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="10dp"
                    android:paddingTop="15dp">
                    <com.evolustudios.askin.askin.src.customfonts.LoginTextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:id="@+id/client_name_alternate_cell"
                        android:textSize="15dp"
                        android:textStyle="bold"/>
                    <com.evolustudios.askin.askin.src.customfonts.LoginTextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:id="@+id/time_stamp_alternate_cell"
                        android:textColor="@color/timestamp"
                        android:textSize="13dp"/>
                </LinearLayout>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:id="@+id/feed_other_content_alternate"
                android:layout_below="@+id/feed_top_panel_alternate">
                <com.evolustudios.askin.askin.src.customfonts.LoginTextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/txtStatusMgs_alternate"
                    android:paddingBottom="5dp"
                    android:paddingLeft="15dp"
                    android:paddingRight="15dp"
                    android:paddingTop="13dp" />
                <com.evolustudios.askin.askin.src.customfonts.LoginTextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/txtUrl_alternate"
                    android:linksClickable="true"
                    android:paddingBottom="10dp"
                    android:paddingLeft="15dp"
                    android:paddingRight="15dp"
                    android:textColor="@color/link" />
                <com.evolustudios.askin.askin.src.Utils.FeedImageView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/feedImage1_alternate"
                    android:background="#80FFFFFF"
                    android:scaleType="fitXY"
                    android:visibility="visible" />
            </LinearLayout>
        </RelativeLayout>


    </FrameLayout>

</it.gmariotti.cardslib.library.view.CardViewNative>

feed_activity_alternate.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/feed_wave_swipe_layout_refresh_alternate">
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/feeds_list_recycler_view"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:scrollbars="vertical"
        tools:listitem="@layout/feed_item_list_new">
    </android.support.v7.widget.RecyclerView>

    <com.telenav.expandablepager.ExpandablePager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/bottom_feed_container"
        android:layout_gravity="bottom"
        app:animation_duration="200"
        app:collapsed_height="@dimen/header_height"/>
</jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout>

feed_pa​​ge_alternative

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:background="@color/pumice">

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

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="250sp"
    android:layout_gravity="center_horizontal"
    android:orientation="horizontal"
    android:paddingTop="10dp"
    android:id="@+id/feed_bottom_panel_first_container">

    <com.evolustudios.askin.askin.src.Utils.FeedImageView
        android:layout_width="270sp"
        android:layout_height="match_parent"
        android:background="@color/edward"
        android:id="@+id/feed_main_image_bottom_sheet"
        android:scaleType="fitCenter"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:scrollbars="none">
        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/feed_extra_iamge_list_view_bootom_panel">
        </ListView>
    </ScrollView>

</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:id="@+id/feed_bottom_panel_second_container"
    android:baselineAligned="false"
    android:orientation="horizontal"
    android:weightSum="5">
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/ic_sentiment_very_satisfied_black_24dp"
            android:scaleType="fitCenter"
            android:padding="5dp"/>
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="5dp"
            android:src="@drawable/ic_sentiment_satisfied_black_24dp"
            android:scaleType="fitCenter"/>
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/ic_sentiment_neutral_black_24dp"
            android:scaleType="fitCenter"
            android:padding="5dp"/>
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/ic_sentiment_dissatisfied_black_24dp"
            android:scaleType="fitCenter"
            android:padding="5dp"/>
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/ic_sentiment_very_dissatisfied_black_24dp"
            android:scaleType="fitCenter"
            android:padding="5dp"/>
    </RelativeLayout>

</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:id="@+id/feed_bottom_panel_third_container"
    android:baselineAligned="false"
    android:orientation="horizontal"
    android:weightSum="5">
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/very_liked_number_bottom_panel"
            android:text="100"
            android:gravity="center"
            android:textColor="@color/ming"/>
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/liked_number_bottom_panel"
            android:text="100"
            android:gravity="center"
            android:textColor="@color/ming"/>
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/neutral_number_bottom_panel"
            android:text="100"
            android:gravity="center"
            android:textColor="@color/ming"/>
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/not_liked_number_bottom_panel"
            android:text="100"
            android:gravity="center"
            android:textColor="@color/ming"/>
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/very_not_liked_number_bottom_panel"
            android:text="100"
            android:gravity="center"
            android:textColor="@color/ming"/>
    </RelativeLayout>

</LinearLayout>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none"
    android:paddingLeft="22dp"
    android:paddingRight="22dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp">
    <com.evolustudios.askin.askin.src.customfonts.LoginTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/body_bottom_panel_feed"
        android:text="Body"
        android:textSize="20dp"/>
</ScrollView>

1 个答案:

答案 0 :(得分:0)

更改,

pager = (ExpandablePager) getActivity().findViewById(R.id.bottom_feed_container);

pager = (ExpandablePager) view.findViewById(R.id.bottom_feed_container);

同样改变,

final RecyclerView mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.feeds_list_recycler_view);

final RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.feeds_list_recycler_view);