如何通过网络从我的sqlite数据库发送记录?

时间:2012-05-29 10:19:19

标签: android multithreading sqlite

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

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

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

要知道表格中没有行

final String SQL_STATEMENT =“SELECT COUNT(*)FROM sample;

你可以在10的倍数检查计数,然后你可以

如果您的日期与表格中的任何列一样,则可以使用此方法。

final String orderBy = Constants.TABLE_CONVERSATION_FIELD_DATE +“DESC LIMIT 10”

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

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

答案 2 :(得分: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语句
select * from TABLE where _ID in (YOUR ID LIST)

也应该相当有效。

如果你只想要一个线程来发布服务器,那么你可以修改上面的逻辑,这样你就可以有一个后台线程来监视id的大小,当它达到10时,它会做发布到服务器。