android – BaseAdapter.notifyDatasetChanged()不更新ListView

android – BaseAdapter.notifyDatasetChanged()不更新ListView,第1张

概述当我调用notifyDatasetChanged()时,为什么我的listview不会更新? 我可以使它显示数据的唯一方法是,再次在ListView上调用setAdatper()…我也尝试通过runOnUIThread()调用它,它没有更改任何内容 适配器 /** * Adapter to provide the data for the online scores * * @author 当我调用notifyDatasetChanged()时,为什么我的ListvIEw不会更新?
我可以使它显示数据的唯一方法是,再次在ListVIEw上调用setAdatper()…我也尝试通过runOnUIThread()调用它,它没有更改任何内容

适配器

/** * Adapter to provIDe the data for the online scores *  * @author soh#zolex * */public class OnlinescoresAdapter extends BaseAdapter {    private Context context;    private List<scoreItem> scores = new ArrayList<scoreItem>();    /**     * Constructor     *      * @param Context context     */    public OnlinescoresAdapter(Context context) {        this.context = context;    }    /**     * Add an item to the adapter     *      * @param item     */    public voID addItem(scoreItem item) {        this.scores.add(item);    }    /**     * Get the number of scores     *      * @return int     */    public int getCount() {        return this.scores.size();    }    /**     * Get a score item     *      * @param int pos     * @return Object     */    public Object getItem(int pos) {        return this.scores.get(pos);    }    /**     * Get the ID of a score     *      * @param in pos     * @retrn long     */    public long getItemID(int pos) {        return 0;    }    /**     * Get the type of an item vIEw     *      * @param int pos     * @return int     */    public int getItemVIEwType(int arg0) {        return arg0;    }    /**     * Create the vIEw for a single List item.     * Load it from an xml layout.     *      * @param int pos     * @param VIEw vIEw     * @param VIEwGroup vIEwGroup     * @return VIEw     */    public VIEw getVIEw(int pos,VIEw vIEw,VIEwGroup group) {        linearLayout layout;        if (vIEw == null) {            layout = (linearLayout)VIEw.inflate(this.context,R.layout.scoreitem,null);        } else {            layout = (linearLayout)vIEw;        }        TextVIEw position = (TextVIEw)layout.findVIEwByID(R.ID.pos);        TextVIEw time = (TextVIEw)layout.findVIEwByID(R.ID.time);        TextVIEw player = (TextVIEw)layout.findVIEwByID(R.ID.player);        TextVIEw createdAt = (TextVIEw)layout.findVIEwByID(R.ID.created_at);        scoreItem item = (scoreItem)getItem(pos);        player.setText(item.player);        position.setText(String.valueOf(new Integer(item.position)) + ".");        time.setText(String.format("%.4f",item.time));        createdAt.setText(item.created_at);        return layout;    }    /**     * Get the number of different vIEws     *      * @return int     */    public int getVIEwTypeCount() {        return 1;    }    /**     * Return wheather the items have stable IDs or not     *      * @return boolean     */    public boolean hasStableIDs() {        return false;    }    /**     * Return wheather the List is empty or not     *      * @return boolean     */    public boolean isEmpty() {        return this.scores.size() == 0;    }    /**     * No need of a data observer     *      * @param DataSetobserver arg0     * @return voID     */    public voID registerDataSetobserver(DataSetobserver arg0) {    }    /**     * No need of a data observer     *      * @param DataSetobserver arg0     * @return voID     */    public voID unregisterDataSetobserver(DataSetobserver arg0) {    }    /**     * No item should be selectable     *      * @return boolean     */    public boolean areAllitemsEnabled() {        return false;    }    /**     * No item should be selectable     *      * @param int pos     * @return boolean     */    public boolean isEnabled(int arg0) {        return false;    }}

活动

XMLLoaderThread工作正常,只是notifyDatasetChanged似乎什么也不做…

/** * Obtain and display the online scores *  * @author soh#zolex * */public class OnlinescoresDetails extends ListActivity {    WakeLock wakeLock;    OnlinescoresAdapter adapter;    boolean isLoading = false;    int chunklimit = 50;    int chunkOffset = 0;    @OverrIDe    /**     * Load the scores and initialize the pager and adapter     *      * @param Bundle savedInstanceState     */    public voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);        this.wakeLock = powerManager.newWakeLock(PowerManager.FulL_WAKE_LOCK,"racesow");        adapter = new OnlinescoresAdapter(this);        setlistadapter(adapter);        this.loadData();        setContentVIEw(R.layout.ListvIEw);        getListVIEw().setonScrollListener(new OnScrollListener() {            public voID onScrollStateChanged(AbsListVIEw vIEw,int scrollState) {            }            public voID onScroll(AbsListVIEw vIEw,int firstVisibleItem,int visibleItemCount,int totalitemCount) {                if (totalitemCount > 0 && visibleItemCount > 0 && firstVisibleItem + visibleItemCount >= totalitemCount) {                    if (!isLoading) {                        loadData();                    }                }            }        });    }    public voID loadData() {        final ProgressDialog pd = new ProgressDialog(OnlinescoresDetails.this);        pd.setProgressstyle(ProgressDialog.STYLE_SPINNER);        pd.setMessage("Obtaining scores...");        pd.setCancelable(false);        pd.show();        isLoading = true;        String mapname = getIntent().getStringExtra("map");        XMLLoaderThread t = new XMLLoaderThread("http://racesow2d.warsow-race.net/map_positions.PHP?name=" + mapname + "&offset=" + this.chunkOffset + "&limit=" + this.chunklimit,new Handler() {            @OverrIDe            public voID handleMessage(Message msg) {                switch (msg.what) {                    // network error                    case 0:                        new AlertDialog.Builder(OnlinescoresDetails.this)                            .setMessage("Could not obtain the mapList.\nCheck your network connection and try again.")                            .setNeutralbutton("OK",new OnClickListener() {                                public voID onClick(DialogInterface arg0,int arg1) {                                    finish();                                    overrIDePendingTransition(0,0);                                }                            })                            .show();                        break;                    // mapList received                    case 1:                        pd.dismiss();                        inputStream xmlStream;                        try {                            xmlStream = new ByteArrayinputStream(msg.getData().getString("xml").getBytes("UTF-8"));                            XMLParser parser = new XMLParser();                            parser.read(xmlStream);                            NodeList positions = parser.doc.getElementsByTagname("position");                            int numpositions = positions.getLength();                            for (int i = 0; i < numpositions; i++) {                                Element position = (Element)positions.item(i);                                scoreItem score = new scoreItem();                                score.position = Integer.parseInt(parser.getValue(position,"no"));                                score.player = parser.getValue(position,"player");                                score.time = float.parsefloat(parser.getValue(position,"time"));                                score.created_at = parser.getValue(position,"created_at");                                adapter.addItem(score);                            }                            adapter.notifyDataSetChanged();                            chunkOffset += chunklimit;                            isLoading = false;                        } catch (UnsupportedEnCodingException e) {                            new AlertDialog.Builder(OnlinescoresDetails.this)                                .setMessage("Internal error: " + e.getMessage())                                .setNeutralbutton("OK",null)                                .show();                        }                        break;                }                pd.dismiss();            }        });        t.start();    }    /**     * Acquire the wakelock on resume     */    public voID onResume() {        super.onResume();        this.wakeLock.acquire();    }    /**     * Release the wakelock when leaving the activity     */    public voID onDestroy() {        super.onDestroy();        this.wakeLock.release();    }    /**     * disable animations when leaving the activity     */    public voID onBackpressed() {        this.finish();        this.overrIDePendingTransition(0,0);    }}
解决方法 有点迟了,但答案是你不应该执行
public voID registerDataSetobserver(DataSetobserver arg0) {}public voID unregisterDataSetobserver(DataSetobserver arg0) {}

我刚刚有一个简单的BaseAdapter工作正常,谁添加这两个方法后停止工作.我觉得“有人”需要观察数据的变化,这样:)

总结

以上是内存溢出为你收集整理的android – BaseAdapter.notifyDatasetChanged()不更新ListView全部内容,希望文章能够帮你解决android – BaseAdapter.notifyDatasetChanged()不更新ListView所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1132686.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存