Не добавление нового списка изображений с помощью EndlessAdapter

1

Я использую EndlessAdapter для отображения списка изображений, но новый список не добавляется после прокрутки.

Мой код выглядит так:

/***
    Copyright (c) 2008-2009 CommonsWare, LLC

    Licensed under the Apache License, Version 2.0 (the "License"); you may
    not use this file except in compliance with the License. You may obtain
    a copy of the License at
        http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

package com.sample.endlessdemo;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

public class EndlessAdapterDemo extends ListActivity {
    String name[];
    String urls[];
    int j,limit;
    //ListView listValues;  
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        RestClient post=new RestClient("http://iconnect.myappdemo.com/listusers.php");
        try {
            post.ExecutePost();
        } catch (Exception e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        String response=post.getResponse();
        Log.e("Respopnse :",response);
        JSONArray json = null;
        try {
            json = new JSONArray(response);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        name=new String[json.length()];
        for(int i=0;i<json.length();i++)
            try {
                name[i]=json.getJSONObject(i).getString("picture").toString();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        urls=new String[10];

        for (int i=0;i<10;i++) { urls[i]=name[i]; }

        setListAdapter(new DemoAdapter(urls));
    }

    class DemoAdapter extends EndlessAdapter {
        private RotateAnimation rotate=null;

        DemoAdapter(String list[]) {
            super(new StartingView(EndlessAdapterDemo.this,R.layout.row,list));

            rotate=new RotateAnimation(0f,360f,Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF,0.5f);
            rotate.setDuration(1000);
            rotate.setRepeatMode(Animation.RESTART);
            rotate.setRepeatCount(Animation.INFINITE);
        }

        @Override
        protected View getPendingView(ViewGroup parent) {
            Log.e("Demo Adapter","getPendingView");
            View row=getLayoutInflater().inflate(R.layout.listrow,null);
            View child=row.findViewById(android.R.id.list);
            //View child=row.findViewById(R.id.image);
            child.setVisibility(View.GONE);

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

            return(row);

        }

        @Override
        protected boolean cacheInBackground() {
            SystemClock.sleep(10000);               // pretend to do work
            Log.e("Demo Adapter","In cacheInBackground");
            return(getWrappedAdapter().getCount()<20);
        }


        @Override
        protected void appendCachedData() 
        {
//          if (getWrappedAdapter().getCount()<75) {
//              Log.e("Demo Adapter","In appendCachedData");
//              @SuppressWarnings("unchecked")
//              ArrayAdapter<String> a=(ArrayAdapter<String>)getWrappedAdapter();
//              for (int i=0;i<5;i++) { a.add(name[a.getCount()]); }
//          }
            @SuppressWarnings("unchecked")
            ArrayAdapter<String> a=(ArrayAdapter<String>)getWrappedAdapter();
            for(int i=0;i<5;i++){
            Log.e("a.getCount()+i value :",String.valueOf(a.getCount()+i));
            a.getView(a.getCount()+i,null,null);
            }
            }
    }
    class StartingView extends ArrayAdapter<String>{
        String startUrls[];
        public StartingView(Context context, int ResourceId,String[] objects) {
            super(context, ResourceId, objects);
            startUrls=new String[objects.length];
            startUrls=objects;
            // TODO Auto-generated constructor stub
        }

        public View getView(int pos,View counterview,ViewGroup parent){
             View row=getLayoutInflater().inflate(R.layout.row,null);
             ImageView image=(ImageView)row.findViewById(R.id.image);
             Log.e("position :",String.valueOf(pos));
             image.setImageBitmap(convertImage(name[pos]));
             return row;
         }
    }

    public Bitmap convertImage(String imgstr){
        URL aURL = null;
        try {
            final String imageUrl =imgstr.replaceAll(" ","%20");
            Log.e("Image Url",imageUrl);
            aURL = new URL(imageUrl);
            URLConnection conn = aURL.openConnection();
            InputStream is = conn.getInputStream(); 
            BufferedInputStream bis = new BufferedInputStream(is); 
            Bitmap bm = BitmapFactory.decodeStream(bis); 
            is.close();
            return bm;
        } 
         catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
}
  • 1
    Это твой код? Он пишет «Copyright (c) 2008-2009 CommonsWare, LLC». И хорошее форматирование - твой друг.
Теги:

2 ответа

0
Лучший ответ

Я надеюсь, что следующий код вам поможет.

PS: Исходный код и вопрос можно найти здесь.

Открытый класс Test extends ListActivity реализует OnScrollListener {

Aleph0 adapter = new Aleph0();

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setListAdapter(adapter); 
    getListView().setOnScrollListener(this);
}

public void onScroll(AbsListView view,
    int firstVisible, int visibleCount, int totalCount) {

    boolean loadMore = /* maybe add a padding */
        firstVisible + visibleCount >= totalCount;

    if(loadMore) {
        adapter.count += visibleCount; // or any other amount
        adapter.notifyDataSetChanged();
    }
}

public void onScrollStateChanged(AbsListView v,

int s) {}

class Aleph0 extends BaseAdapter {
    int count = 40; /* starting amount */

    public int getCount() { return count; }
    public Object getItem(int pos) { return pos; }
    public long getItemId(int pos) { return pos; }

    public View getView(int pos, View v, ViewGroup p) {
            TextView view = new TextView(Test.this);
            view.setText("entry " + pos);
            return view;
    }
} }
0

Добавьте это после завершения загрузки:

 StartingView.notifyDataSetChanged()

Ещё вопросы

Сообщество Overcoder
Наверх
Меню