how i display my list in mode list or grid

时间:2016-10-20 12:42:14

标签: android

Please I need your help, I need to display my list in mode list or grid, that's why I use recyclerview but that does not work and give me the following error related to "recyclerView.setLayoutManager(new LinearLayoutManager(this));

However when I used listview before that worked fine!

can you help me please, thanks

this my activity_videos

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:id="@+id/parentLayout"
    tools:context=".UI.Videos">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="#FFFFFF"
            app:popupTheme="@style/AppTheme.PopupOverlay" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Videos"
                android:textColor="#303F9F"
                android:layout_gravity="center"
                android:id="@+id/Videos" />

        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

        <include
            layout="@layout/content_videos"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header_main"
            app:menu="@menu/activity_main_drawer"/>

    </android.support.v4.widget.DrawerLayout>

</android.support.design.widget.CoordinatorLayout>

my content video :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".UI.Videos"
    tools:showIn="@layout/activity_videos">

      <Space
        android:layout_width="20px"
        android:layout_height="20px"
        android:id="@+id/space" />

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/activity_main_swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/space"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="56dp">


        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:scrollbars="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>


    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

my cutom list adabtor :

public class CustomListViewAdapterV extends RecyclerView.Adapter<CustomListViewAdapterV.ViewHolder>  {

    List<Video> videoList;
    Context context;

    // Constructors
    public CustomListViewAdapterV(Context context, ArrayList<Video> objects) {

        this.context = context;
        videoList = objects;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_videos, parent, false);
        return new ViewHolder(v);
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Video item = videoList.get(position);
        holder.textViewTitle.setText(item.getTitle());
        // holder.textViewCreated_time.setText(item.getCreated_time());
        //  holder.textViewId.setText(item.getId());
        Picasso.with(context).load(item.getThumbnail_medium_url()).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).into(holder.imageView);

        holder.rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

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

    public static class ViewHolder extends RecyclerView.ViewHolder {
        RelativeLayout rootView;
        ImageView imageView;
        TextView textViewTitle;
      //  public final TextView textViewCreated_time;
     //   public final TextView textViewId;
        private ViewHolder(View rootView) {
            super(rootView);
            this.imageView = imageView;
            this.textViewTitle = textViewTitle;
         //   this.textViewCreated_time = textViewCreated_time;
         //   this.textViewId = textViewId;
        }



        public static void create(RelativeLayout rootView) {
           ImageView imageView = (ImageView) rootView.findViewById(R.id.imageView);
            TextView textViewTitle = (TextView) rootView.findViewById(R.id.textViewTitle);
       //     TextView textViewCreated_time = (TextView) rootView.findViewById(R.id.textViewCreated_time);
       //     TextView textViewId = (TextView) rootView.findViewById(R.id.textViewId);
        }
    }
}

and this is my mainactivity:

public class Videos extends MainActivity {

    private View parentView;
    private ArrayList<Video> videoList;
    private CustomListViewAdapterV adapter;
    SwipeRefreshLayout mSwipeRefreshLayout;
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new CustomListViewAdapterV(Videos.this, videoList);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_videos);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        videoList = new ArrayList<>();
        parentView = findViewById(R.id.parentLayout);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


        mSwipeRefreshLayout.setColorSchemeResources(R.color.blue, R.color.green, R.color.blue);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        doYourUpdate();
                    }
                }
        );
           ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                   Intent intent = new Intent(getApplicationContext(), Daylimotion.class);
                    startActivity(intent);
            }
        });
                if (InternetConnection.isNetworkAvailable(getApplicationContext())) {

                    //Creating an object of our api interface
                    ApiInterface api = ApiClientV.getApiInterface();
                    /**
                     * Calling JSON
                     */
                    Call<VideoList> call = api.getJsn();
                    /**
                     * Enqueue Callback will be call when get response...
                     */
                    call.enqueue(new Callback<VideoList>() {
                        @Override
                        public void onResponse(Call<VideoList> call, Response<VideoList> response) {
                            //Dismiss Dialog
                            if(response.isSuccessful()) {
                                /**
                                 * Got Successfully
                                 */

                               videoList = response.body().getList();
                               // adapter.notifiyDataSetChanged();

                                /**
                                 * Binding that List to Adapter
                                 */
                                //This is to show data for first time when we run the app.
                                adapter = new CustomListViewAdapterV(Videos.this, videoList);
                                recyclerView.setAdapter(adapter);

                            } else {
                                Snackbar.make(parentView, R.string.string_some_thing_wrong, Snackbar.LENGTH_LONG).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<VideoList> call, Throwable t) {
                        }
                    });
                } else {
                    Snackbar.make(parentView, R.string.string_internet_connection_not_available, Snackbar.LENGTH_LONG).show();
                }
            }

    private void doYourUpdate() {

            mSwipeRefreshLayout.setRefreshing(false); // Disables the refresh icon
        }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.show, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int layoutId = R.layout.list_item;

        int spanCount = 2;
        switch (item.getItemId()) {
            case R.id.linearVertical:  // Vertical scrollable using LinearLayoutManager.
                recyclerView.setLayoutManager(new LinearLayoutManager(this));
                break;

            case R.id.staggeredGridviewVertical:  // Vertical scrollable using StaggeredGridLayoutManager.
                recyclerView.setLayoutManager(new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL));
                break;

        }

              return super.onOptionsItemSelected(item);

    }

the error that have is :

FATAL EXCEPTION: main
                                                                                 Process: com.example.sajdour.fcg_sajdour, PID: 23620
                                                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sajdour.fcg_sajdour/com.example.sajdour.fcg_sajdour.UI.Videos}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
                                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3254)
                                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
                                                                                     at android.app.ActivityThread.access$1100(ActivityThread.java:222)
                                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                     at android.os.Looper.loop(Looper.java:158)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:7229)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
                                                                                     at com.example.sajdour.fcg_sajdour.UI.Videos.onCreate(Videos.java:46)
                                                                                     at android.app.Activity.performCreate(Activity.java:6876)

3 个答案:

答案 0 :(得分:1)

You should create grid layout manager:

recyclerView.setLayoutManager(new GridLayoutManager(this, 2));

About error. Your recycler view is null in onCreate(). You should invoke findViewById(R.id.myRecycler) after setContentView() and before recyclerView methods invocation. In your case:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_videos);

    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new CustomListViewAdapterV(Videos.this, videoList);
    ...
}

答案 1 :(得分:1)

your recyclerView is null. initialize recyclerview after calling super.onCreate() & setContentView(). Change the first 5 lines in your oncreate method of your Videos Activity

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_videos);

recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new CustomListViewAdapterV(Videos.this, videoList);

答案 2 :(得分:0)

Your actual problem is that you are trying to do stuff before these two. These two should come before anything to avoid the error you got

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_videos);

So, something like:

 //A bunch of code
 @Override
protected void onCreate(Bundle savedInstanceState) {
    //PAY ATTENTION HERE
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_videos);

    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new CustomListViewAdapterV(Videos.this, videoList);
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    //even more code