如何从Service类更新SimpleCursorAdapter列表视图?

时间:2012-02-29 03:32:23

标签: android sqlite service background

我使用SimpleCursorAdapter将数据显示在我的活动类的列表中。我正在获取data from Sqlite DB and applying to listview。我正在从服务类插入数据。在我的服务类中,我得到了来自WEB服务的数据和最新插入Sqlite移动数据库的这个服务类将每隔5秒运行一次以检查最新的Web服务,然后将其带入并插入Sqlite db。当新记录插入Sqlite db时,listview不是使用最新插入的记录进行更新。我已按如下方式实现了我的应用程序:

MyActivity.java

private MySqliteHelper msh;
ListView lst;
Cursor cursor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        msh = new MySqliteHelper(MyActivity.this);
        msh.openToWrite();
        lst = ((ListView)findViewById(R.id.listView1));
        cursor = msh.queueAll();

        String getFromDB[] = new String[]{MySqliteHelper.KEY_CONTENT1,MySqliteHelper.KEY_CONTENT2};
        int toView[] = new int[]{R.id.msgId,R.id.usrmsg};

        lst.setAdapter(new SimpleCursorAdapter(this, R.layout.list, cursor, getFromDB, toView));

       //calling service class
        bindService(new Intent(ShoutGetMessagesActivity.this, ShoutRepeatService.class), mConnection, Context.BIND_AUTO_CREATE);

        updateList();
    }

      private void updateList(){
              cursor.requery();
               }


        RepeatService bg;
        private ServiceConnection mConnection = new ServiceConnection() {

            public void onServiceConnected(ComponentName className, IBinder binder) {

                bg = ((RepeatService.MyBinder) binder).getService();

                Toast.makeText(MyActivity.this, "Connected",
                        Toast.LENGTH_SHORT).show();

            }

            public void onServiceDisconnected(ComponentName className) {
                bg = null;
            }
        };
    }

RepeatService.java

    ArrayList<NewMessages> result;
    private MySqliteHelper msh;

     private Timer timer = new Timer();
     private static final long UPDATE_INTERVAL = 500;



    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
          msh = new MySqliteHelper(this);
            msh.openToWrite();

       pollForUpdates();

     super.onCreate();
    }

        private void pollForUpdates() {
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Log.v("Last message ID", "====>"+MySqliteHelper.LastMsgID);

                if(MySqliteHelper.LastMsgID==null){

                    MySqliteHelper.LastMsgID="0";

                }

                result = new ParseXml().convertUsersDetails(new Generic().getLatestFromWebService(MySqliteHelper.LastMsgID));


                 for(int i=0;i<result.size();i++){
                    String msgs =result.get(i).getMessages();
                    String msgID = result.get(i).getMsgId();
                        Log.v("messages", "------------>>>>"+msgs);
                        Log.v("messageIDs", "--------->>>>>>"+msgID);
                        msh.insert(msgID, msgs);
                    }   

            }
        }, 0, UPDATE_INTERVAL);

        Log.v(getClass().getSimpleName(), "Timer started.");

    }



         private void updateList(){
      cursor.requery();
       }

    public class MyBinder extends Binder {
        RepeatService getService() 
        {
            return RepeatService.this;
        }
    }
}

从上面的服务类我得到最新的记录并插入到Sqlite db。 如何从此服务类更新为View类?

请任何人帮助我

2 个答案:

答案 0 :(得分:5)

您可以使用intent来创建广播,以从服务的run()方法调用活动中的函数

private void pollForUpdates() {
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        Log.v("Last message ID", "====>"+MySqliteHelper.LastMsgID);

        if(MySqliteHelper.LastMsgID==null){

            MySqliteHelper.LastMsgID="0";

        }

        result = new ParseXml().convertUsersDetails(new Generic().getLatestFromWebService(MySqliteHelper.LastMsgID));


         for(int i=0;i<result.size();i++){
            String msgs =result.get(i).getMessages();
            String msgID = result.get(i).getMsgId();
                Log.v("messages", "------------>>>>"+msgs);
                Log.v("messageIDs", "--------->>>>>>"+msgID);
                msh.insert(msgID, msgs);
            }   

    }
*************************************
Intent intent = new Intent();
intent.setAction("com.example.updatelist");
sendBroadcast(intent); // finally broadcast
*************************************

}, 0, UPDATE_INTERVAL);

Log.v(getClass().getSimpleName(), "Timer started.");

}

在您的活动中,您必须收到广播意图并更新列表

 // Register Broadcast Receiver to receive broadcast intent in oncreate method

public oncreate()
{       
IntentFilter filter = new IntentFilter("com.example.updatelist");
        registerReceiver(myReceiver, filter);
}

private BroadcastReceiver myReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

    msh = new MySqliteHelper(MyActivity.this);
    msh.openToWrite();
    lst = ((ListView)findViewById(R.id.listView1));
    cursor = msh.queueAll();

    String getFromDB[] = new String[] MySqliteHelper.KEY_CONTENT1,MySqliteHelper.KEY_CONTENT2};
    int toView[] = new int[]{R.id.msgId,R.id.usrmsg};

    lst.setAdapter(new SimpleCursorAdapter(this, R.layout.list, cursor, getFromDB, toView));

    }
};

答案 1 :(得分:1)

您可以在活动中使用广播接收器,并在数据更新时让服务发出广播。您必须定义自定义广播才能使其正常工作。

首先。 像这样定义自定义操作

public static final String DATA_INSERTED = "WHATEVER_YOU_WANT"

在服务中更改数据时,请执行

Intent intent = new Intent (DATA_INSERTED);
sendBroadcast(intent)

初始化自定义广播接收器以侦听此特定DATA_INSERTED操作。覆盖onReceive方法。在onReceive方法中。您必须在适配器上调用notifydatasetchanged,这也意味着您需要对simplecursoradapter的引用。我将把广播接收器实现留给你弄清楚。