EndLessAdapter + Asynctask + Custom Fragmentlist

Я хотел бы реализовать EndlessAdapter от commonsware в моем приложении, это Listfragment с пользовательским ListView и lazyadapter, который расширяет Baseadapter.

Проблема:

  • Я получаю исключение в cacheInBackground(); когда я звоню MyAsyncTask, какую-либо помощь, чтобы решить? Я использовал Endlessadapter v1.2 (последний) в качестве библиотеки.

             @Override
                      protected boolean cacheInBackground() {
                          new MyAsyncTask(this, data.size()).execute();
    
                        return hasMoreData;
                      }
    
  • Lazyadapter работает хорошо без EndlessAdapter.

12-30 15:29:21.404: E/EndlessAdapter(334): исключение в cacheInBackground() 12-30 15:29:21.404: E/EndlessAdapter(334): java.lang.NullPointerException 12-30 15:29:21.404: E/EndlessAdapter(334): по адресу br.com.example.nightid.endlessadapter.EndlessCustomView$DemoAdapter.cacheInBackground(EndlessCustomView.java:132) 12-30 15:29:21.404: E/EndlessAdapter(334): по тел.commonsware.cwac.endless.EndlessAdapter.getView(EndlessAdapter.java:250) 12-30 15:29:21.404: E/EndlessAdapter(334): at android.widget.AbsListView.obtainView(AbsListView.java:1430) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.widget.ListView.makeAndAddView(ListView.java:1745) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.widget.ListView.fillDown(ListView.java:670) 12-30 15:29:21.404: E/EndlessAdapter(334): at android.widget.ListView.fillFromTop(ListView.java:727) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.widget.ListView.layoutChildren(ListView.java:1598) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.widget.AbsListView.onLayout(AbsListView.java:1260) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.view.View.layout(View.java:7175) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.widget.FrameLayout.onLayout(FrameLayout.java:338) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.view.View.layout(View.java:7175) 12-30 15:29:21.404: E/EndlessAdapter(334): at android.widget.FrameLayout.onLayout(FrameLayout.java:338) 12-30 15:29:21.404: E/EndlessAdapter(334): на android.view.View.layout(View.java:7175) 12-30 15:29:21.404: E/EndlessAdapter(334): на android.widget.FrameLayout.onLayout(FrameLayout.java:338) 12-30 15:29:21.404: E/EndlessAdapter(334): на android.view.View.layout(View.java:7175) 12-30 15:29:21.404: E/EndlessAdapter(334): на андроиде.support.v4.view.ViewPager.onLayout(ViewPager.java:1520) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.view.View.layout(View.java:7175) 12-30 15:29:21.404: E/EndlessAdapter(334): на android.widget.LinearLayout.setChildFrame(LinearLayout.java:1254) 12-30 15:29:21.404: E/EndlessAdapter(334): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1130) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.widget.LinearLayout.onLayout(LinearLayout.java:1047) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.view.View.layout (View.java:7175) 12 -30 15:29:21.404: E/EndlessAdapter(334): на android.widget.FrameLayout.onLayout(FrameLayout.java:338) 12-30 15:29:21.404: E/EndlessAdapter(334): на android.view.View.layout(View.java:7175) 12-30 15:29:21.404: E/EndlessAdapter(334): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1254) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.widget.LinearLayout.layoutVertical (LinearLayout.java:1130) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.widget.LinearLayout.onLayout (LinearLayout. Java:1047) 12-30 15:29:21.404: E/EndlessAdapter(334): at android.view.View.layout(View.java:7175) 12-30 15:29:21.404: E/EndlessAdapter(334): на android.widget.FrameLayout.onLayout(FrameLayout.java:338) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.view.View.layout(View.java:7175) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.widget.FrameLayout.onLayout(FrameLayout.java:338) 12-30 15:29:21.404: E/EndlessAdapter(334): в android.view.View.layout (Просмотреть. Java:7175) 12-30 15:29:21.404: E/EndlessAdapter(334): at android.view.ViewRoot.performTraversals(ViewRoot.java:1140) 12-30 15:29:21.404: E/EndlessAdapter(334): at android.view.ViewRoot.handleMessage(ViewRoot.java:1859) 12-30 15:29:21.404: E/EndlessAdapter(334): at android.os.Handler.dispatchMessage(Handler.java:99) 12-30 15:29:21.404: E/EndlessAdapter(334): на android.os.Looper.loop(Looper.java:123) 12-30 15:29:21.404: E/EndlessAdapter(334): на android.app.ActivityThread.main(ActivityThread.java:3683) 12-30 15:29:21.404: E/EndlessAdapter(334): at java.lang.reflect.Method.invokeNative(собственный метод) 12-30 15:29:21.404: E/EndlessAdapter(334): в java.lang.reflect.Method.invoke(Method.java:507) 12-30 15:29:21.404: E/EndlessAdapter(334): на com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 12-30 15:29:21.404: E/EndlessAdapter(334): на com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 12-30 15:29:21.404: E/EndlessAdapter(334): на dalvik.system.NativeStart.main(собственный метод) 12-30 15:30:53.096: E/dalvikvm(334): не удалось найти класс 'com.actionbarsherlock.widget.SearchView$11', на который ссылается метод com.actionbarsherlock.widget.SearchView.

EndlessCustomView:

public class EndlessCustomView extends ListFragment{
    // All static variables
        static final String URL = "http://api.androidhive.info/music/music.xml";
        // XML node keys
        static final String KEY_SONG = "song"; // parent node
        static final String KEY_ID = "id";
        static final String KEY_TITLE = "title";
        static final String KEY_ARTIST = "artist";
        static final String KEY_DURATION = "duration";
        static final String KEY_THUMB_URL = "thumb_url";

        ListView list;
        DemoAdapter adapter=null;
        ArrayList<HashMap<String, String>> songsList = null;

//      @Override
//      public void onActivityCreated(Bundle savedInstanceState) {
//      // TODO Auto-generated method stub
//      super.onActivityCreated(savedInstanceState);
//      
//      setRetainInstance(true);
//      
//      songsList = new ArrayList<HashMap<String, String>>();
//      
//      if (getActivity() != null) {
//          
//      adapter = new DemoAdapter(getActivity(), songsList); 
//      adapter.setRunInBackground(false);
//      setListAdapter(adapter);
//      }
//      
//      }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onViewCreated(view, savedInstanceState);
//          

////            new MyAsyncTask().execute();
            setRetainInstance(true);
            songsList = new ArrayList<HashMap<String, String>>();

            if (getActivity() != null) {

            adapter = new DemoAdapter(getActivity(), songsList); 
            adapter.setRunInBackground(false);
            setListAdapter(adapter);
            }

        }

        class DemoAdapter extends EndlessAdapter implements IItemsReadyListener{
              private RotateAnimation rotate=null;
              private View pendingView=null;
              private FragmentActivity activity;
              private ArrayList<HashMap<String, String>> data;
              public ImageLoader imageLoader; 
              private List<HashMap<String, String>> mOriginalNames;
              private boolean hasMoreData=true;




              DemoAdapter(FragmentActivity fragmentActivity, ArrayList<HashMap<String, String>> d) {

                super(new LazyAdapter(fragmentActivity, d));

                rotate=new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
                        0.5f, Animation.RELATIVE_TO_SELF,
                        0.5f);

                rotate.setRepeatMode(Animation.RESTART);
                rotate.setRepeatCount(Animation.INFINITE);
              }

              @Override
              protected View getPendingView(ViewGroup parent) {


                  View row = getActivity().getLayoutInflater().inflate(R.layout.row, null);

                      View child=row.findViewById(android.R.id.text1);

                      child.setVisibility(View.GONE);

                      child=row.findViewById(R.id.throbber);
                      child.setVisibility(View.VISIBLE);
                      child.startAnimation(rotate);



                return(row);
              }



              @Override
              protected boolean cacheInBackground() {
                  new MyAsyncTask(this, data.size()).execute();

                return hasMoreData;
              }

              public void onItemsReady(ArrayList<HashMap<String, String>> data) {
                  songsList.addAll(data);
                  adapter.onDataReady();  // Tell the EndlessAdapter to remove it's pending
                                          // view and call notifyDataSetChanged()
                  hasMoreData = songsList.isEmpty();
                }

              @Override
              protected void appendCachedData() {
//              if (getWrappedAdapter().getCount()<75) {
//                @SuppressWarnings("unchecked")
//                LazyAdapter a=(LazyAdapter)getWrappedAdapter();
//                for (int i = 0; i < data.size(); i++) {
//                    a.add(data.get(i));
//                }
//              }
              }



        public class MyAsyncTask extends AsyncTask<Void,Void,ArrayList<HashMap<String, String>>>{
            IItemsReadyListener listener;
            private final ProgressDialog dialog=new ProgressDialog(getActivity());

            int startPoint;

            public MyAsyncTask(IItemsReadyListener listener, int startPoint) {
                // TODO Auto-generated constructor stub
                this.listener = listener;
                this.startPoint = startPoint;
            }

            @Override
            protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {

                XMLParser parser = new XMLParser();
                String xml = parser.getXmlFromUrl(URL); // getting XML from URL
                Document doc = parser.getDomElement(xml); // getting DOM element

                NodeList nl = doc.getElementsByTagName(KEY_SONG);
                // looping through all song nodes <song>
                for (int i = 0; i < nl.getLength(); i++) {
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    Element e = (Element) nl.item(i);
                    // adding each child node to HashMap key => value
                    map.put(KEY_ID, parser.getValue(e, KEY_ID));
                    map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
                    map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
                    map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
                    map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

                    // adding HashList to ArrayList
                    songsList.add(map);
                }
                return (songsList);
            }

            @Override
            protected void onPreExecute()
            {
                dialog.setMessage("Loading ...");
                dialog.show();
                dialog.setCancelable(false);
            }

            @Override
            protected void onPostExecute(ArrayList<HashMap<String, String>> result)
            {
                listener.onItemsReady(songsList);
                 // Getting adapter by passing xml data ArrayList

                }

            }
    }



}

LazyAdapter:

public class LazyAdapter extends BaseAdapter {

    private FragmentActivity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader; 
    private List<HashMap<String, String>> mOriginalNames;


    public LazyAdapter(FragmentActivity fragmentActivity, ArrayList<HashMap<String, String>> d) {
        super();
        this.activity = fragmentActivity;
        this.data = d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }


    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return data.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)

            vi = inflater.inflate(R.layout.list_row, null);

        TextView title = (TextView)vi.findViewById(R.id.title); // title
        TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
        TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
        ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

        HashMap<String, String> song = new HashMap<String, String>();
        song = data.get(position);

        // Setting all values in listview
        title.setText(song.get(CustomizedListView.KEY_TITLE));
        artist.setText(song.get(CustomizedListView.KEY_ARTIST));
        duration.setText(song.get(CustomizedListView.KEY_DURATION));
        imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
        return vi;
    }

    public void add(HashMap<String, String> map) {
        // TODO Auto-generated method stub
        data.add(map);
        notifyDataSetChanged();

    }



}

1 ответ

Решение

data является null в cacheInBackground(), Вы можете сказать это, прочитав трассировку стека (NullPointerException в cacheInBackground()) и видя, что единственное, что может вызвать это исключение прямо в cacheInBackground() является data.size(),

Поскольку я не вижу, где вы когда-либо назначаете значение dataтот факт, что это null это не удивительно.

Другие вопросы по тегам