开发者

Sending multiple http requests to Django from Android

I am developing a microblogging platform in which I need to populate the page with Post (user defined class with fields) obtained from the Django server using HttpGet.

In the client side(Android) I am using GSON to parse the responses from server to the type Post. So I require that server should send Post's one by one so as to add each of them to a list of Posts after parsing and then finally notifying the list adapter of changes in the data set after all Post's have been added.

But the problem coming when intially loading 开发者_如何学Gothe application, the page has to be populated with 10 latest Post's from the server. So I thought of a rather dirty way of sending 10 httpget requests to the server one after the other to the server. The code looks like this

public void populateTimeline(){
Thread populate = new Thread(){
    public void run(){
        Looper.prepare();
        InputStream data = getData(serviceURL);  //gets a post from server
        if(data!= null){
            String result = responsetoString(data); //turns response to String
            progressDialog.show();
            Posts post = toPostfromGson(result); //Parses string to Post Object             
        }
        Looper.loop();
    }

};
populate.start();       

}

I was thinking of executing it 10 times in a loop to get the 10 Post's I require. But in Django as far I know (correct me if I am wrong) there's no way to keep an index of the last sent Post to the client and so no way to send the 'next' Post on the next HttpGet request. So I am out of ideas.

I feel there's a better way to do this efficiently. Any help would be much appreciated.


As an elaboration on Dmitry's comment, consider adding a view in your Django app which returns multiple (serialized) Posts. Something like the following:

def get_posts(request, count=10):
    posts = Post.objects.all().order_by("-date")[:count]
    posts_in_gson = serialize_to_gson(posts)
    return HttpResponse(posts_in_gson)

Your client code will need to handle a list of posts as well as a single post. (Or just make subsequent calls with count=1.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜