RecyclerView无法显示从服务器检索的数据

时间:2016-06-27 16:26:17

标签: java android

如何使用RecyclerView显示数据?无论何时成功从服务器检索数据,始终不会在屏幕上显示(空白屏幕)。

MainActivity

package com.transvision.bertho.transvisiondashboardapp;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import page.DefaultFragment;
import page.HomeFragment;
import page.ProfileFragment;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_test);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

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

        Fragment fragment = null;
        fragment = new DefaultFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.root, fragment);
        fragmentTransaction.commit();

    }

    @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.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        Fragment fragment = null;
        String title = getString(R.string.app_name);

        if (id == R.id.nav_camera) {
            fragment = new HomeFragment();
            title = "Home";
        } else if (id == R.id.nav_gallery) {
            fragment = new ProfileFragment();
            title = "Profile";
        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.root, fragment);
            fragmentTransaction.commit();

            getSupportActionBar().setTitle(title);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    public void showToast(String output){
        Toast.makeText(this.getBaseContext(), output, Toast.LENGTH_SHORT).show();
    }

}

HomeFragment

package page;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.transvision.bertho.transvisiondashboardapp.R;

import java.util.ArrayList;
import java.util.List;

import adapter.ChannelAdapter;
import butterknife.Bind;
import butterknife.ButterKnife;
import model.Channel;
import model.ChannelResponse;
import rest.ApiClient;
import rest.ApiInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{

    @Bind(R.id.movies_recycler_view) RecyclerView recyclerView;
    @Bind(R.id.swipe_layout) SwipeRefreshLayout swipeRefreshLayout;

    private static final String TAG = HomeFragment.class.getSimpleName();

    private ChannelAdapter adapter;
    List<Channel> listChannel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, rootView);

        listChannel = new ArrayList<>();

        setUpSwipeLayout();
        setUpAdapter();
        setUpRecyclerview();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                load();
            }
        }, 500);

        return rootView;
    }

    protected void setUpSwipeLayout()
    {
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
        swipeRefreshLayout.setOnRefreshListener(this);
    }

    private void setUpAdapter(){
        if(adapter == null){
            adapter = new ChannelAdapter(listChannel, R.layout.list_channel, getActivity());
        }
    }

    private void setUpRecyclerview(){
        recyclerView.clearOnScrollListeners();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    }

    private void load(){
        swipeRefreshLayout.setRefreshing(true);
        ApiInterface apiService = ApiClient.getChannel().create(ApiInterface.class);
        Call<ChannelResponse> call = apiService.getItems();

        call.enqueue(new Callback<ChannelResponse>() {
            @Override
            public void onResponse(Call<ChannelResponse> call, Response<ChannelResponse> response) {
//                try {
//
//                }catch (Exception e){
//                    Log.e(TAG, e.getMessage());
//                }

                listChannel = response.body().getItems();
                adapter = new ChannelAdapter(listChannel, R.layout.list_channel, getActivity());
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();

                Log.e(TAG, "CONNECTION SUCCESS");
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Call<ChannelResponse> call, Throwable t) {
                Log.e(TAG, t.toString());
                showToast("CONNECTION ERROR");
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

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

    @Override
    public void onDetach() {
        super.onDetach();
    }

    public void showToast(String output){
        Toast.makeText(getActivity(), output, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRefresh() {
        load();
    }
}

ChannelAdapter

package adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.transvision.bertho.transvisiondashboardapp.R;

import java.util.List;

import model.Channel;


public class ChannelAdapter extends RecyclerView.Adapter<ChannelAdapter.ChannelViewHolder> {

    private List<Channel> channels;
    private int rowLayout;
    private Context context;

    public ChannelAdapter(List<Channel> channels, int rowLayout, Context context) {
        this.channels = channels;
        this.rowLayout = rowLayout;
        this.context = context;
    }

    public static class ChannelViewHolder extends RecyclerView.ViewHolder {

        LinearLayout moviesLayout;

        TextView name;
        TextView description;
        TextView definition;

        public ChannelViewHolder(View v) {
            super(v);
            moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
            name = (TextView) v.findViewById(R.id.title);
            definition = (TextView) v.findViewById(R.id.subtitle);
            description = (TextView) v.findViewById(R.id.description);
        }
    }

    @Override
    public ChannelViewHolder onCreateViewHolder(ViewGroup parent,
                                                            int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
        return new ChannelViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ChannelViewHolder holder, final int position) {
        holder.name.setText(channels.get(position).getName());
        holder.definition.setText(channels.get(position).getDefinition());
        holder.description.setText(channels.get(position).getDescription());
    }

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


}

当我跑步时,我得到日志

06-27 23:15:32.524 2537-2537/com.transvision.bertho.transvisiondashboardapp W/PathParser: Points are too far apart 4.000000596046461
06-27 23:15:33.532 2537-2537/com.transvision.bertho.transvisiondashboardapp W/PathParser: Points are too far apart 4.000000596046461
06-27 23:15:33.673 2537-2543/com.transvision.bertho.transvisiondashboardapp W/art: Suspending all threads took: 56.004ms
06-27 23:15:33.703 2537-2537/com.transvision.bertho.transvisiondashboardapp E/RecyclerView: No adapter attached; skipping layout
06-27 23:15:34.639 2537-2543/com.transvision.bertho.transvisiondashboardapp W/art: Suspending all threads took: 16.331ms
06-27 23:15:35.225 2537-2543/com.transvision.bertho.transvisiondashboardapp W/art: Suspending all threads took: 113.297ms
06-27 23:15:35.234 2537-2537/com.transvision.bertho.transvisiondashboardapp I/Choreographer: Skipped 60 frames!  The application may be doing too much work on its main thread.
06-27 23:15:35.696 2537-2537/com.transvision.bertho.transvisiondashboardapp E/HomeFragment: CONNECTION SUCCESS
06-27 23:16:00.184 2537-2543/com.transvision.bertho.transvisiondashboardapp W/art: Suspending all threads took: 6.098ms

我调试后,我明白了 enter image description here

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<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/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

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

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

app_bar_main.xml

<?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"
    tools:context="com.transvision.bertho.transvisiondashboardapp.MainActivity">

    <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="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

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

    <FrameLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

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

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/movies_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>

list_channel.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/movies_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:minHeight="72dp"
    android:orientation="horizontal"
    android:padding="16dp">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:paddingRight="16dp"
            android:textStyle="bold"
            android:textColor="@color/colorBlack"
            android:textSize="16sp" />


        <TextView
            android:id="@+id/subtitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingRight="16dp"
            android:textColor="@color/colorGreyLight" />

        <TextView
            android:id="@+id/description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:maxLines="3"
            android:paddingRight="16dp"
            android:textColor="@color/colorGreyLight" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="35dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/rating_image"
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:layout_centerInParent="true"
            android:scaleType="centerCrop"
            android:src="@drawable/star"
            android:tint="@color/colorAccent" />


        <TextView
            android:id="@+id/rating"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:text="5.0" />
    </LinearLayout>

</LinearLayout>

我的代码中可能存在错误,请为此案例提供帮助

1 个答案:

答案 0 :(得分:0)

请在适配器类中更改以下代码,

@Override
public ChannelViewHolder onCreateViewHolder(ViewGroup parent,
                                                        int viewType) {
    View view = LayoutInflater.from(context).inflate(rowLayout, parent, false);
    return new ChannelViewHolder(view);
}