listview向下滚动以加载更多视图

时间:2012-04-18 14:54:28

标签: android json web-services listview

我是Android的菜鸟,我已经阅读了很多xamples,但到目前为止没有成功,所以基本上我希望我的listview利用baseadapter在我向下滚动时添加更多行,以及添加更多行的机制将是再次查询动态URL,现在实现查询的on scroll函数,但适配器生成一个新列表n丢弃旧的,这里是代码

public class Second extends Activity {

static final String Li_nk = "LinkName:";
static final String Image_name = "ImageName:";
// ListView list;
public final static String AUTH = "authentication";
static final String KEY_THUMB_URL = "thumb_image";
// JSONObject j2;
String wrd;
int counter = 01;

// ArrayList<HashMap<String,String>> mylist;
@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Intent i2 = getIntent();
    wrd = i2.getStringExtra("entrd");
    Log.v("keyis", wrd);

    final Handler handler = new Handler();
    Runnable runable = new Runnable() {

        @Override
        public void run() {

            // call the function
            LoadData();
            // also call the same runnable
            handler.postDelayed(this, 40000);
        }
    };
    handler.postDelayed(runable, 10);

}

public void LoadData() {

    JSONObject j2 = JSONfunctions
            .getJSONfromURL("/webservice_search.php?keyword=" + wrd
                    + "&format=json&pagenum=" + counter);
    final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

    try {
        JSONArray jray = j2.getJSONArray("listings");
        for (int i = 0; i < jray.length(); i++) {
            Log.v("state", "json data being read");
            JSONObject j3 = jray.getJSONObject(i);
            String first = j3.getString("listing");
            Log.v("sublist", first);
            JSONObject j4 = j3.getJSONObject("listing");
            String sec = j4.getString("links");

            int maxLength = (sec.length() < 30) ? sec.length() : 27;
            sec.substring(0, maxLength);
            String cutsec = sec.substring(0, maxLength);
            Log.v("links are", cutsec);
            String img = j4.getString("image_name");
            Log.v("image name is ", img);
            // Uri
            // dimg=Uri.parse("http://zeesms.info/android_app_images/Koala.jpg");
            HashMap<String, String> map = new HashMap<String, String>();

            map.put("Id", String.valueOf(i));
            map.put(Li_nk, cutsec);
            map.put(Image_name, j4.getString("image_name"));

            map.put(KEY_THUMB_URL, "http://zeesms.info/android_app_images/"
                    + img);

            mylist.add(map);

        }

    } catch (JSONException e) {

        Log.e("loG_tag", "Error parsing" + e.toString());
    }
    final LazyAdapter adapter = new LazyAdapter(this, mylist);
    adapter.notifyDataSetChanged();

    View footerView = ((LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
            R.layout.footer, null, false);

    ListView list = (ListView) findViewById(R.id.lv1);
    list.setEmptyView(findViewById(R.id.empty));
    list.addFooterView(footerView);
    list.setAdapter(adapter);

    list.setItemsCanFocus(false);

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // Toast.makeText(getApplicationContext(),"Click ListItem Number "
            // + position, Toast.LENGTH_LONG).show();
            Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri
                    .parse("http://www.google.com/"));
            startActivity(myIntent);
        }

    });
    list.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub
            // what is the bottom iten that is visible

            int lastInScreen = firstVisibleItem + visibleItemCount;
            if (lastInScreen == totalItemCount) {

                counter++;

                LoadData();
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

    });
}

我的适配器类的代码是

public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader; 
//int count=5;


public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    Collections.reverse(d);
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return data.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}



@Override
public View getView(int position, View convertView, ViewGroup parent) {
    /*position=1;
    position=2;
    position=3;
    position=4;
    position=5;*/
    View vi=convertView;
    if(convertView==null)

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

    TextView title = (TextView)vi.findViewById(R.id.linkname); // merchnts name
    TextView artist = (TextView)vi.findViewById(R.id.imagename); // address
    //TextView duration = (TextView)vi.findViewById(R.id); // distance
   ImageView thumb_image=(ImageView)vi.findViewById(R.id.mClogo); // logo

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

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

现在新列表附加旧列表的最简单方法是什么,还是滚动后会添加更多视图的其他方式?

1 个答案:

答案 0 :(得分:1)

您可以为列表视图添加onscrollchange侦听器,当最后一个位置可见时,向其添加元素,并相应地增加列表视图的大小。

在lazyadapter中添加一个方法说

setData(HashMap<string,string> newdata){
this.data = newdata;
}

每次点击webservice并获得响应都会将数据附加到newConcretehashmap并调用上面的方法。通过这个,你将只获得hashmap中更新的newData。然后只需调用notifydatasetchanged();并且列表将更新。