Android:调用notifyDataSetChanged但未更新ListView

时间:2011-05-26 10:56:20

标签: android android-listview

我得到了这个ListView,它是从网络上的JSON数据填充的。但是当我更新JSON条目时,例如添加新条目时,ListView不会更新。虽然我已经调用了notifyDataSetChanged(),但它并没有在列表中显示新条目。

任何人都可以帮助我吗?感谢。

这是我的代码:

public class ProjectsList extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.projects_list);
        Intent serviceIntent = new Intent(this, LooserSync.class);
        startService(serviceIntent);
        ListView listView = (ListView) findViewById(R.id.lstText);
        MySimpleCursorAdapter projectAdapter = new MySimpleCursorAdapter(this, R.layout.listitems,
                managedQuery(Uri.withAppendedPath(LooserProvider.CONTENT_URI,
                        Database.Project.NAME), new String[] { BaseColumns._ID,
                        Database.Project.C_PROJECTTITLE, Database.Project.C_SMALLIMAGE }, null, null,
                        null), new String[] { Database.Project.C_PROJECTTITLE, Database.Project.C_SMALLIMAGE }, new int[] {
                        R.id.txt_title, R.id.image });
        listView.setAdapter(projectAdapter);
        projectAdapter.notifyDataSetChanged();


        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              

                Intent i = new Intent(ProjectsList.this, DetailsActivity.class);
                i.setData(Uri.withAppendedPath(Uri.withAppendedPath(
                        LooserProvider.CONTENT_URI, Database.Project.NAME), Long
                        .toString(id)));
                i.putExtra("spendino.de.ProjectDetail.position",position);
                startActivity(i);
            }
        });

    }

    class MySimpleCursorAdapter extends SimpleCursorAdapter {

        public MySimpleCursorAdapter(Context context, int layout, Cursor c,
                String[] from, int[] to) {
            super(context, layout, c, from, to);
            loader = new ImageLoaderCache(context);
            this.context = context;
        }
        Activity activity= ProjectsList.this;
        Context context=null;
        ImageLoaderCache loader = null;

        public void setViewImage(ImageView v, String value) {
            v.setTag(value);
            loader.displayImage(value, activity, v);
        }
    }


}

这里更新的是LooserSync.java

public class LooserSync extends IntentService {

    public LooserSync() {
        super("LooserSyncService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Database.OpenHelper dbhelper = new Database.OpenHelper(getBaseContext());
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        db.beginTransaction();
        HttpGet request = new HttpGet(
                "http://liebenwald.spendino.net/admanager/dev/android/projects.json");
        try {
            HttpResponse response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                InputStream instream = response.getEntity().getContent();
                BufferedReader r = new BufferedReader(new InputStreamReader(
                        instream), 8000);
                StringBuilder total = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    total.append(line);
                }
                instream.close();
                String bufstring = total.toString();
                JSONArray arr = new JSONArray(bufstring);
                Database.Tables tab = Database.Tables.AllTables.get(Database.Project.NAME);
                tab.DeleteAll(db);
                for (int i = 0; i < arr.length(); i++) {
                    tab.InsertJSON(db, (JSONObject) arr.get(i));
                }
                db.setTransactionSuccessful();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        db.endTransaction();
        db.close();

    }

}

2 个答案:

答案 0 :(得分:4)

当您使用光标填充列表时,您必须在模型上更改(添加,编辑或删除)某些内容后获取新的列表或重新查询旧列表。

获得新光标后,可以通过调用changeCursor()将其传递给适配器。

<强>更新

以下代码每次调用onResume()时都会获得一个新游标。所以你的清单应该是最新的。当然,在显示列表时对模型所做的更改不会更新到列表中。如果你想要实时更新列表,你必须实现某种观察者模式。因此,当模型更改时,您的活动会收到通知。

public class ProjectsList extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.projects_list);
        Intent serviceIntent = new Intent(this, LooserSync.class);
        startService(serviceIntent);
        ListView listView = (ListView) findViewById(R.id.lstText);

        final String[] from = new String[] { Database.Project.C_PROJECTTITLE, Database.Project.C_SMALLIMAGE };
        final int[] to = new int[] {R.id.txt_title, R.id.image};

        MySimpleCursorAdapter projectAdapter = new MySimpleCursorAdapter(this, R.layout.listitems, null, from, to);

        listView.setAdapter(projectAdapter);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              

                Intent i = new Intent(ProjectsList.this, DetailsActivity.class);
                i.setData(Uri.withAppendedPath(Uri.withAppendedPath(
                        LooserProvider.CONTENT_URI, Database.Project.NAME), Long
                        .toString(id)));
                i.putExtra("spendino.de.ProjectDetail.position",position);
                startActivity(i);
            }
        });

    }

    public void onResume(){
        Cursor cursor = managedQuery(Uri.withAppendedPath(LooserProvider.CONTENT_URI,
                        Database.Project.NAME), new String[] { BaseColumns._ID,
                        Database.Project.C_PROJECTTITLE, Database.Project.C_SMALLIMAGE }, null, null, null);

        ListView listView = (ListView) findViewById(R.id.lstText);                         
        ((CursorAdapter)listView.getAdapter()).changeCursor(cursor);
    }

答案 1 :(得分:0)

projectAdapter.notifyDataSetChanged();

用给定的吹线替换上面的线,然后你就可以解决你的问题了。

((MySimpleCursorAdapter)(ProjectsList.listView.getAdapter())).notifyDataSetChanged();

错误:在通知适配器列表后,您应该获得列表视图的适配器。