D
D
Daniel2018-06-20 18:00:49
Java
Daniel, 2018-06-20 18:00:49

How to display data from ArrayList in RecycleView?

I am rewriting the application to use RecycleView. I write based on examples from the Internet.
There was a problem with displaying data from ArrayList in RecycleView. What is the problem? ListView worked great with it.
RecycleAdapter.java code:

spoiler
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private List<String> mTitles;

    public RecyclerAdapter(List<String> titles) {
        mTitles = titles;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextView;

        public ViewHolder(View v) {
            super(v);
            mTextView = (TextView) v.findViewById(R.id.rw_title);
        }
    }

    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                         int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recycler_item, parent, false);

        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        holder.mTextView.setText(mTitles.get(position));

    }

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


Android Monitor
spoiler
06-20 17:43:20.040 2268-2268/? I/zygote64: Late-enabling -Xcheck:jni
06-20 17:43:20.064 2268-2268/? I/zygote64: Reinit property: dalvik.vm.checkjni= false
06-20 17:43:20.086 2268-2268/? D/ActivityThread: ActivityThread,attachApplication
06-20 17:43:20.204 2268-2268/ru.stalkerweb.recycleviewsw D/HwFLClassLoader: get used feature list :/feature/used-list failed!
06-20 17:43:20.204 2268-2268/ru.stalkerweb.recycleviewsw D/HwFLClassLoader: USE_FEATURE_LIST had not init! 
06-20 17:43:20.244 2268-2268/ru.stalkerweb.recycleviewsw E/MemoryLeakMonitorManager: MemoryLeakMonitor.jar is not exist!
06-20 17:43:20.247 2268-2268/ru.stalkerweb.recycleviewsw E/Minikin: Could not get cmap table size!
06-20 17:43:20.283 2268-2268/ru.stalkerweb.recycleviewsw I/HwCust: Constructor found for class android.app.HwCustActivityImpl
06-20 17:43:20.284 2268-2268/ru.stalkerweb.recycleviewsw D/HwCust: Create obj success use class android.app.HwCustActivityImpl
06-20 17:43:20.293 2268-2268/ru.stalkerweb.recycleviewsw V/HwPolicyFactory: : success to get AllImpl object and return....
06-20 17:43:20.299 2268-2268/ru.stalkerweb.recycleviewsw I/HwCust: Constructor found for class android.app.HwCustHwWallpaperManagerImpl
06-20 17:43:20.299 2268-2268/ru.stalkerweb.recycleviewsw D/HwCust: Create obj success use class android.app.HwCustHwWallpaperManagerImpl
06-20 17:43:20.334 2268-2268/ru.stalkerweb.recycleviewsw V/HwWidgetFactory: : successes to get AllImpl object and return....
06-20 17:43:20.338 2268-2268/ru.stalkerweb.recycleviewsw V/ActivityThread: ActivityThread,callActivityOnCreate
06-20 17:43:20.429 2268-2268/? D/HwRTBlurUtils: check blur style for HwPhoneWindow-, themeResId : 0x7f0900a8, context : [email protected], Nhwext : 0, get Blur : disable with , null
06-20 17:43:20.431 2268-2268/? D/HwRTBlurUtils: check blur style for HwPhoneWindow-, themeResId : 0x7f0900a8, context : [email protected], Nhwext : 0, get Blur : disable with , null
06-20 17:43:20.486 2268-2268/? D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.23, mControlPoint1y = 0.06, mControlPoint2x = 0.09, mControlPoint2y = 0.97
06-20 17:43:20.487 2268-2268/? D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.6, mControlPoint1y = 0.9, mControlPoint2x = 0.8, mControlPoint2y = 1.0
06-20 17:43:20.489 2268-2268/? D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.23, mControlPoint1y = 0.06, mControlPoint2x = 0.09, mControlPoint2y = 0.97
06-20 17:43:20.490 2268-2268/? D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.6, mControlPoint1y = 0.9, mControlPoint2x = 0.8, mControlPoint2y = 1.0
06-20 17:43:20.512 2268-2268/? W/Utils: Utils_isSuperResolutionSupport [load libai_client.so failed]
06-20 17:43:20.526 2268-2268/? D/AndroidRuntime: Shutting down VM
06-20 17:43:20.530 2268-2268/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: ru.stalkerweb.recycleviewsw, PID: 2268
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{ru.stalkerweb.recycleviewsw/ru.stalkerweb.recycleviewsw.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3194)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302)
                                                     at android.app.ActivityThread.-wrap12(Unknown Source:0)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891)
                                                     at android.os.Handler.dispatchMessage(Handler.java:108)
                                                     at android.os.Looper.loop(Looper.java:166)
                                                     at android.app.ActivityThread.main(ActivityThread.java:7425)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
                                                  Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                                                     at ru.stalkerweb.recycleviewsw.MainActivity.onCreate(MainActivity.java:51)
                                                     at android.app.Activity.performCreate(Activity.java:7372)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3147)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302) 
                                                     at android.app.ActivityThread.-wrap12(Unknown Source:0) 
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891) 
                                                     at android.os.Handler.dispatchMessage(Handler.java:108) 
                                                     at android.os.Looper.loop(Looper.java:166) 
                                                     at android.app.ActivityThread.main(ActivityThread.java:7425) 
                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) 
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) 
06-20 17:43:20.543 2268-2268/? I/Process: Sending signal. PID: 2268 SIG: 9

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2018-06-20
@shevyrinn

You create an adapter before you create titles (i.e. when this variable is null). Everything that happens to this variable after the adapter is created is unimportant, since the reference inside is already null.
To simplify catching such situations, I recommend using the @NonNull / @Nullable annotations wherever possible. It is also possible to configure the IDE so that any field not marked with @NonNull is considered @Nullable.

D
Daniel, 2018-06-20
@shevyrinn

MainActivity.java

spoiler
public class MainActivity extends AppCompatActivity {

    URL url;
    List<String> titles;
    ArrayList<String> links;
    ArrayList<String> description;
    ArrayList<String> pubDate;
    ArrayList<String> author;
    ArrayList<String> category;
    String HHMurl= "https://stalkerweb.ru/feed";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        mRecyclerView.setHasFixedSize(false);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
   
        RecyclerView.Adapter mAdapter = new RecyclerAdapter(titles);
        mRecyclerView.setAdapter(mAdapter);
        try{
        titles = new ArrayList<>();
        links = new ArrayList<>();
        description = new ArrayList<>();
        pubDate = new ArrayList<>();
        author = new ArrayList<>();
        category = new ArrayList<>();

        RecycleClick.addTo(mRecyclerView).setOnItemClickListener(new RecycleClick.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {

                 //to do something

            }

        });
            new ProcessInBackground().execute();

        } catch(Exception e){
            //to do something
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

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

        return super.onOptionsItemSelected(item);
    }


    public InputStream getInputStream (URL url)
    {
        try {
            return url.openConnection().getInputStream();
        } catch (IOException e) {
            return null;
        }
    }

    private class ProcessInBackground extends AsyncTask<Integer, Void, Exception> {

        ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);

        Exception exception = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.setMessage("Загрузка...");
            progressDialog.show();
        }

        @Override
        protected Exception doInBackground(Integer... params) {

            try {
                url = new URL(HHMurl);
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                factory.setNamespaceAware(false);
                XmlPullParser xpp = factory.newPullParser();
                xpp.setInput(getInputStream(url), "UTF_8");
                boolean insideItem = false;
                int eventType = xpp.getEventType();

                while (eventType != XmlPullParser.END_DOCUMENT) {
                    if (eventType == XmlPullParser.START_TAG) {
                        if (xpp.getName().equalsIgnoreCase("item")) {
                            insideItem = true;
                        } else if (xpp.getName().equalsIgnoreCase("title")) {
                            if (insideItem) {
                                titles.add(xpp.nextText());
                            }
                        } else if (xpp.getName().equalsIgnoreCase("link")) {
                            if (insideItem) {
                                links.add(xpp.nextText());
                            }
                        } else if (xpp.getName().equalsIgnoreCase("content:encoded")) {
                            if (insideItem) {
                                description.add(xpp.nextText());
                            }
                        } else if (xpp.getName().equalsIgnoreCase("pubDate")) {
                            if (insideItem) {
                                pubDate.add(xpp.nextText());
                            }
                        } else if (xpp.getName().equalsIgnoreCase("dc:creator")) {
                            if (insideItem) {
                                author.add(xpp.nextText());
                            }
                        } else if (xpp.getName().equalsIgnoreCase("category")) {
                            if (insideItem) {
                                category.add(xpp.nextText());
                            }
                        }

                    } else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")) {
                        insideItem = false;
                    }

                    eventType = xpp.next();
                }


            } catch (XmlPullParserException | IOException e) {
                exception = e;
            }

            return exception;
        }

    }}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question