I am currently developing an app for an project in my university. This project consists of me benig able to handle synchronous and assynchronous http request to a web-service that i've built. I have to create a class or some code that can send http requests (easy enought done throught AsyncTask) and callback the responsed back to an activity.
I don't know how to do this, since the onPostExecute() method is a void method, which doesn't return anything, and I can't save the contents of the response in a public variable because it's in another class.
What I want to do is the following:
From activity:
MessageCentre centre = new MessageCentre();
centre.getMessages(1);
The 1 is an Id attributed to this device that is logged into my app-server. The server then retrieves all the messages associated with this ID in a JSONArray format. I cast those JSONObjects into a Message class that i've built, and save all of those new objects as an static array inside the MessageCentre class instance.
From here on, I have to disply the messages to the user, but I can't do that because inside the getMessages(1) method i execute an AsyncTask, which generates a secondary thread in my application. So the code goes on as shown below, but the ArrayAdapter doesn't show the messages (because he renders the adapter, before the messages arrive from the app-server)
ArrayAdapter a = new ArrayAdapter(getApplicationContext(),R.id.item_layout, centre.getMessagesList());
listview.setAdapter(a);
I also don't want to set the adapter from the AsyncTask because I wish to make this in a "black-box" format, where the user can simply call the methods and "make it work" by recieving plain object arrays and then implement their own views on top of that.
I also can't simply tell the activity to wait a couple of seconds by doing Thread.sleep() because that crashes the app and shows the ANR error.
So there are some ways i can think of handling this:
1) a way to make the activity wait for sometime without the ANR
2)returning the data back to the activity someway that isnt the onPostExecute() method, in some kind of callback method
3)making it so that the adapter and listview can, in Runtime, update and create the itens (OnCreateView() method) to show the messages, after they have been set and rendered, when the messages actually arrive, a couple of seconds later, from the app-server.
I think number 3 is more probable, and also resembles more what a chat application does. I just don't know how to update the messages list in runtime.
Any help is appreciated guys, thanks a lot!