E / RecyclerView:没有连接适配器;跳过布局。使用ASYNC TASK

时间:2017-05-25 02:43:42

标签: android android-asynctask android-recyclerview

我遇到了问题,当我试图查看以下片段时,显示"跳过布局"。任何人都可以帮我解决这个问题。 我得到了这个"没有附加适配器;跳过布局。"当我在ThirdFragment UI ayout上点击任何图像视图时,而不是在图像显示在Thirdfragment UI布局中时。

ThirdFrament.java

public class ThirdFragment extends Fragment implements RecyclerViewAdapter.ItemListener {

    static final String url = "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesData.txt" ;

    RecyclerView recyclerView;
    RecyclerViewAdapter adapter;
    AutoFitGridLayoutManager layoutManager;

    private static List<JsonURLFullModel> cart;

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

        View rootView= inflater.inflate(R.layout.fragment_third, container, false);

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

        new JSONTask().execute(url, this);




        // Inflate the layout for this fragment
        return rootView;
    }




    public class JSONTask extends AsyncTask<Object, String, ThirdFragModel> {
        //     Url , , return_value_of_doInBackground


        //private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //dialog.show(); // this is for ProgressDialog
        }

        @Override
        protected ThirdFragModel doInBackground(Object... params) {

            //send and receive data over the web
            // can be used to send and receive "streaming" data whose length is not
            // known in advance
            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {

                URL url = new URL(params[0].toString());
                RecyclerViewAdapter.ItemListener itemListener = (RecyclerViewAdapter.ItemListener) params[1];
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                InputStream stream = connection.getInputStream(); // this is used to store
                // the response, response is always stream

                reader = new BufferedReader(new InputStreamReader(stream));
                // BufferedReader reads the stream line by line and then store in the reader

                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }

                String finalJson = buffer.toString(); // this contails whole JSON data from the URL
                JSONObject parentObject = new JSONObject(finalJson);
                JSONArray parentArray = parentObject.getJSONArray("movies"); // "movies" is the JSON Array-object in JSON data URL

                List<JsonURLFullModel> movieModelList = new ArrayList<>();
                //StringBuffer finalBufferedaData = new StringBuffer();

                for (int i = 0; i < parentArray.length(); i++) {
                    JSONObject finalObject = parentArray.getJSONObject(i); // getting first json object from JSON ARRAY "movies"
                    JsonURLFullModel movieModel = new JsonURLFullModel();

                    movieModel.setMovie(finalObject.getString("movie"));
                    movieModel.setImage(finalObject.getString("image"));

                    movieModelList.add(movieModel); // adding the final object in list
                    //finalBufferedaData.append(movieName +"-"+ year +"\n");
                }

                ThirdFragModel thirdFragModel= new ThirdFragModel(itemListener,movieModelList);


                return thirdFragModel;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (connection != null)
                    connection.disconnect();
                try {
                    if (reader != null)
                        reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }


        @Override
        protected void onPostExecute(ThirdFragModel result) {
            super.onPostExecute(result);
            //jsonfull.setText(result);
            //dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)

            adapter = new RecyclerViewAdapter(getActivity(), result.getMovieModelList(), result.getItemListener());



            /**
             AutoFitGridLayoutManager that auto fits the cells by the column width defined.
             **/

            layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
            recyclerView.setLayoutManager(layoutManager);


            recyclerView.setAdapter(adapter);
            /**
             Simple GridLayoutManager that spans two columns
             **/
        /*GridLayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);*/

            //AnimationUtils.animate(jsonFullL1, true);

        }

    }

    public void moveToLoginActivity() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
    }

    @Override
    public void onItemClick(int mPosition,List<JsonURLFullModel> mValues ) {

        Log.d("Fragposition",mPosition+":"+mValues);
        Toast.makeText(getActivity(), mValues.get(mPosition).getMovie() + " is clicked", Toast.LENGTH_SHORT).show();
        //Intent intent = new Intent(getActivity(), FullScreenViewActivity.class);
        Intent intent = new Intent(getActivity(), FullScreenViewInitialActivity.class);
        intent.putExtra("position", mPosition);
        intent.putExtra("values", (Serializable) mValues);
        startActivity(intent);

    }


    public static List<JsonURLFullModel> getCart() {
        if(cart == null) {
            cart = new Vector<JsonURLFullModel>();
        }

        return cart;
    }
}

这是我在ThirdFragment类中使用的适配器类,如上所示

RecyclerViewAdapter.java

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

    static List<JsonURLFullModel> mValues;
    Context mContext;
    private ItemListener mListener;
    static int mPosition;


    public RecyclerViewAdapter(Context context, List<JsonURLFullModel> values, ItemListener itemListener) {

        mValues = values;
        mContext = context;
        mListener=itemListener;
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView textView;
        public ImageView imageView;
        public RelativeLayout relativeLayout;
        JsonURLFullModel item;

        public ViewHolder(View v) {

            super(v);

            v.setOnClickListener(this);
            textView = (TextView) v.findViewById(R.id.textView1);
            imageView = (ImageView) v.findViewById(R.id.imageView1);
            relativeLayout = (RelativeLayout) v.findViewById(R.id.relativeLayout);

        }

        public void setData(final JsonURLFullModel item) {
            this.item = item;

            Log.d("INFO",item.getImage());

            //https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit

            Picasso.with(mContext)
                    .load(item.getImage())
                    .error(R.drawable.ferrari)
                    .noPlaceholder()
                    .noFade()
                    .fit()
                    .into(imageView, new com.squareup.picasso.Callback() {
                        @Override
                        public void onSuccess() {
                            //Success image already loaded into the view
                            Log.d("INFO","success");
                        }

                        @Override
                        public void onError() {
                            //Error placeholder image already loaded into the view, do further handling of this situation here
                            Log.d("INFO","error");
                        }
                    });

            /*imageView.post(new Runnable() {

                @Override
                public void run(){

                    Glide.with(mContext).load(item.getImage()).asBitmap().override(1080, 600).into(imageView);

                }
            });*/

            textView.setText(item.getMovie());


        }


        @Override
        public void onClick(View view) {
            if (mListener != null) {
                mListener.onItemClick(getAdapterPosition(),mValues); // this.getPosition() is depricated
                                                                // in API 22 and we got getAdapterPosition()
            }
        }
    }

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

        View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_view_item, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder Vholder, int position) {
        Vholder.setData(mValues.get(position));
        mPosition=position;

    }

    @Override
    public int getItemCount() {

        return mValues.size();
    }

    //Below interface implimentation can be found in ThirdFragment
    // you can write below interface separetly or in you can write in this class like below
    public interface ItemListener {
        void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
    }


}

FullScreenViewInitialActivity.java

public class FullScreenViewInitialActivity extends FragmentActivity {

    ImageFragmentPagerAdapter imageFragmentPagerAdapter;
    ViewPager viewPager;
    static ArrayList<JsonURLFullModel> mValues;
    static int position;

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


        addToBagButton = (Button) findViewById(R.id.b_add_to_bag);

        Intent i = getIntent();
        position=i.getIntExtra("position",0);
        Log.d("Acposition",""+position);
        mValues = (ArrayList<JsonURLFullModel>) getIntent().getSerializableExtra("values");


        imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
        viewPager = (ViewPager) findViewById(R.id.intial_pager);
        viewPager.setAdapter(imageFragmentPagerAdapter);

        viewPager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        CircleIndicator circleIndicator = (CircleIndicator) findViewById(R.id.imageIndicator);
        circleIndicator.setViewPager(viewPager);

        /*viewPager.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                Intent intent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewActivity.class);
                intent.putExtra("position", position);
                intent.putExtra("values", (Serializable) mValues);
                startActivity(intent);
            }
        });*/


        final List<JsonURLFullModel> cart = ThirdFragment.getCart();

        final JsonURLFullModel selectedProduct = mValues.get(position);




        addToBagButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                cart.add(selectedProduct);
                Log.d("cart",""+cart.size());
                //finish();

                Button b_add_to_bag = (Button) findViewById(R.id.b_add_to_bag);
                b_add_to_bag.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent reviewOrderIntent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewReviewActivity.class);
                        startActivity(reviewOrderIntent);
                    }
                });


            }
        });

        if(cart.contains(selectedProduct)) {
            addToBagButton.setEnabled(false);
            addToBagButton.setText("Item in Cart");
        }

    }


    public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
        public ImageFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

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

        @Override
        public Fragment getItem(int position) {
            SwipeFragment fragment = new SwipeFragment();
            return SwipeFragment.newInstance(position);
        }
    }

    public static class SwipeFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
            ImageView imageView = (ImageView) swipeView.findViewById(R.id.imageView);
            /*Bundle bundle = getArguments();
            int position = bundle.getInt("position");*/

            //JsonURLFullModel imageFileName = mValues.get(position);
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
            /*options.inJustDecodeBounds = true;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;*/
                URL url = new URL(mValues.get(position).getImage());
                Log.d("position",""+position);
                Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream(),null, options);
                if (bitmap !=  null)
                    imageView.setImageBitmap(bitmap);
                else
                    System.out.println("The Bitmap is NULL");


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(), mValues.get(position).getMovie(), Toast.LENGTH_SHORT).show();
                }
            });


            return swipeView;
        }



        static SwipeFragment newInstance(int position) {
            SwipeFragment swipeFragment = new SwipeFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("position", position);
            swipeFragment.setArguments(bundle);
            return swipeFragment;
        }
    }




}

third_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

        <!--removed from recycler view
        app:layout_behavior="@string/appbar_scrolling_view_behavior"-->

    </RelativeLayout>

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

recycler_view_item.xml

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

    <android.support.v7.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        card_view:cardCornerRadius="@dimen/margin10"
        card_view:cardElevation="@dimen/margin10"
        card_view:cardMaxElevation="@dimen/margin10"
        card_view:contentPadding="@dimen/margin10"
        card_view:cardPreventCornerOverlap="false"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp">


        <RelativeLayout
            android:id="@+id/relativeLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_gravity="center">

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:scaleType="fitXY"
                android:padding="5dp"
                android:layout_alignParentTop="true"/>


            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:textColor="@color/colorPrimary"
                android:layout_marginTop="10dp"
                android:layout_below="@+id/imageView1" />


        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

activity_fullscreen_view_initial

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fillViewport="true"
        android:layout_weight="1">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_above="@+id/cart_button_layout"
            android:layout_alignParentTop="true"
            android:orientation="vertical">


            <android.support.v4.view.ViewPager
                android:id="@+id/intial_pager"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" />

            <me.relex.circleindicator.CircleIndicator
                android:id="@+id/imageIndicator"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:layout_alignBottom="@+id/intial_pager"
                android:layout_marginBottom="10dp" />

        </LinearLayout>

    </ScrollView>

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true"
        >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <include
        layout="@layout/full_screen_size_picker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    </LinearLayout>
    </ScrollView>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/cart_button_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="bottom"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">


        <Button
            android:id="@+id/b_save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dp"
            android:layout_weight="1"
            android:background="#D3D3D3"
            android:text="save"
            android:textColor="#000000" />

        <Button
            android:id="@+id/b_add_to_bag"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_weight="1"
            android:background="@color/colorPrimary"
            android:text="add to bag"
            android:textColor="#FFF" />


    </LinearLayout>


</LinearLayout>

swipe_fragment.xml

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

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/imageView"
        android:layout_gravity="center_horizontal"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

在执行AsyncTask之前,尝试使用空适配器设置RecyclerView的设置。

   View rootView= inflater.inflate(R.layout.fragment_third, container, false);
    recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);

 -->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);

    new JSONTask().execute(url, this);

然后在RecyclerViewAapter中创建一个方法来加载填充的列表<JsonURLFullModel&gt;来自AsyncTask的onPostExecute。

    public void loadJson(List<JsonURLFullModel> jsonList){
           mValues = jsonList;
           notifyDataSetChanged();
    }

如果使用runOnUiThread尝试从Asynctask加载Ui线程不起作用

   runOnUiThread(new Runnable() {
    @Override
    public void run() {
        adapter.loadJson(...)
    }
});

编辑1 将loadJson添加到RecyclerViewAapter.class

@Override
public int getItemCount() {

    return mValues.size();
}

public void loadJson(List<JsonURLFullModel> jsonList){
           mValues = jsonList;
           notifyDataSetChanged();
    }

//Below interface implimentation can be found in ThirdFragment
// you can write below interface separetly or in you can write in this class like below
public interface ItemListener {
    void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
}

在PostExecute中调用该方法

@Override
    protected void onPostExecute(ThirdFragModel result) {
        super.onPostExecute(result);
        //jsonfull.setText(result);
        //dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)

        getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
        adapter.loadJson(result.getMovieModelList());
        }
        });



    }

还要在onCreateView

中添加RecyclerView的布局管理器
 View rootView= inflater.inflate(R.layout.fragment_third, container, false);
    recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);

 -->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);
    layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
    recyclerView.setLayoutManager(layoutManager);