2012-05-29 58 views
0

我在sqlite数据库中写了一堆记录。每次存储的记录数达到10的倍数时,我想将这10条记录存储到对象中并发送到远程服务器。如何通过网络从我的sqlite数据库发送记录?

我该如何在单独的线程中完成任务?

+0

我建议你创建一个绑定到单独线程的'Handler'并将'Runnable'或者邮件发布到你的记录中。 –

回答

1

如果你想使用http,你可以使用这个示例代码。

Thread background = new Thread(new Runnable(){ 
    @Override 
public void run() { 
        HttpClient httpclient = new DefaultHttpClient(); 
         HttpPost httppost = new HttpPost("http://your-url.com"); 

try { 
    // Add your data 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("paramName", paramValue)); 
      nameValuePairs.add(new BasicNameValuePair("paramName2", paramValue2)); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    // Execute HTTP Post Request 
    httpclient.execute(httppost); 

} catch (Exception e) { 
    Log.w("error", e.toString()); 
} 
}); 
background.start(); 
0

了解没有行的表从样品

最后弦乐SQL_STATEMENT =“SELECT COUNT(*);

可以检查计数时,它的多个10,那么你可以

,如果你有类似日期表中的任何列,你可以使用这种方法。

最后弦乐ORDERBY = Constants.TABLE_CONVERSATION_FIELD_DATE +“DESC LIMIT 10”

return db.query(table,columns,selection,null,null,null,orderBy);

现在您需要从数据库获取值并将该值传递给服务器。

0

如果所有的插入操作都是从单一方法发生的,那么您可以保留发送到服务器的项目ID的内部缓存,当集合达到10时,将这10个记录发送到服务器后台线程。

这个伪代码可能是这样的......

Set<Long> ids = new TreeSet<Long>; 

public void insert(Data data) { 
    long id = sqlite.insert(data); 
    ids.add(id); 
    if (ids.size()>=10) { 
     postToServer(); 
    } 
} 

public void postToServer() { 
    // build select statement using the 10 ids in the set. 
    // clear the set 
    ids.clear(); 
    // create a new thread and then post your results to the server 
    // optionally update those 10 ids in the database to indicate that they have been sent to the server 
} 

上面的代码只在内存中保存10个长值的缓存,因此追踪在内存中是不是巨大的交易。并且由于您插入了插入的记录的ID,因此使用类似于

select * from TABLE where _ID in (YOUR ID LIST) 

的方式创建单个选择语句也应该相当有效。

如果你只想要一个线程来发布服务器,那么你可以修改上面的逻辑,以便你有一个后台线程来监控ID设置的大小,当它达到10时,它会把帖子发到服务器上。