I am working on an app where I need to POST data(a JSON string) to a web server. I am doing this using the Apache HTTP Client(attached code below). When there is an internet connection everything works fine, but the project spec needs me to cache data locally if there is no internet connection and wait till I have a connection to the server.
Here are my questions: 1. What would be the best way to cache the JSON strings locally and send them on their way when I get an internet connection. The only way I can think of is to store them in a database till I find a connection to the server.
- How do I check if I have an Internet connection?
The code from the POST is here, If I have to catch the data I am assuming I will have to do it in place of the "no connection" error dialogue in the exception handle.
Thread t = new Thread()
{
public void run()
{
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
try {
HttpPost post = new HttpPost("http:xxxxx");
StringEntity se = new StringEntity( flat.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
// /*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
} catch(Exception e)
{
e.printStackTrace();
//createDialog("Error", "Cannot Estabilish Connection");
Toast.makeText(getApplicationContext(), "cannot establish concetion",Toast.LENGTH_SHORT).show();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();