Wednesday, January 02, 2013

Android: Checking if Internet is available

The following method is very useful in android when you have to check if the internet is available on the device.

public boolean isNetworkAvailable(Context c) {

ConnectivityManager cm = (ConnectivityManager)c.getSystemService(Context.CONNECTIVITY_SERVICE);

return cm.getActiveNetworkInfo() != null


&& cm.getActiveNetworkInfo().isConnectedOrConnecting();

}

Android: Downloading a file to an external directory

In most of our applications we encounter a scenario where we have to download a file and then open it from our app. The file may be a pdf or an image.

So lets see the code for the same. I will be using the same HttpResponseContainerVO described previously.

Since we are downloading a file, instead of encoding the response in the VO, I am storing the file in the path and returning the absolute path of the file in response.

Downloading file:

public static HttpResponseContainerVO downloadPDFFile(String url,

String name)

throws ClientProtocolException, IOException {



if (!isExternalStorageAvailable()) {

throw new IOException("External Storage is not Available");
//Use internal storage or Cache or Temp folder to store the files.
}
HttpResponseContainerVO responseVo = new HttpResponseContainerVO();

DefaultHttpClient client = new DefaultHttpClient();


String filePath = getFilePath(name);
HttpGet get = new HttpGet(url);

 
// Add the headers....

HttpResponse response = client.execute(get);

HttpEntity entity = response.getEntity();


responseVo.setResponseCode(response.getStatusLine().getStatusCode());

Header[] headers = response.getAllHeaders();
for (Header hdr : headers) {
//Set the headers
 }


InputStream inputStream = entity.getContent();
FileOutputStream content = new FileOutputStream(new File(filePath));

// Read response into a buffered stream

int readBytes = 0;

byte[] sBuffer = new byte[512];

while ((readBytes = inputStream.read(sBuffer)) != -1) {


content.write(sBuffer, 0, readBytes);

}

content.flush();

content.close();

responseVo.setResponse(filePath);
return responseVo;

}


Getting external file path:

private static String getFilePath(String name) {


String fileDir = Environment.getExternalStorageDirectory()
.getAbsolutePath() +"YOUR DIRECTORY HERE";

String fileName = name + "Extension";

File dir = new File(fileDir);

if (!dir.exists()) {


dir.mkdirs();

}
return fileDir + fileName;


}

Now you have successfully downloaded and stored the file in the external / internal storage. How do you open this file from your app? Simple, follow the code below.


Uri path = Uri.fromFile(new File(VO.getResponse()));

Intent intent = new Intent(Intent.ACTION_VIEW);


intent.setDataAndType(path,
        "MIME TYPE OF THE CONTENT");

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

try {

startActivity(intent);
} catch (ActivityNotFoundException e) {

Toast.makeText(CONTEXT, MESSAGE,

Toast.LENGTH_LONG).show();


}

 

Android: Posting data to server & reading response

In the last post we saw how to do a get request using HttpClient in android. Now lets see how to do a post request, wherein we send some data to the server and then read the response.
 
The below code uses the HttpResponseContainerVO object from the previous post to retrieve the data.
 
 
public static HttpResponseContainerVO getPostResponse(String url,
final byte[] data)
throws IOException {
 
 
HttpResponseContainerVO responseVo = new HttpResponseContainerVO();
 

HttpPost post = new HttpPost(url);
// Add the headers
post.addHeader(new BasicHeader("Accept","application/json"));
 
post.setEntity(new HttpEntity() {
 

@Override
public void writeTo(OutputStream outstream) throws IOException {
 
outstream.write(data);
}

@Override
public boolean isStreaming() {
return false;
 
}

@Override
public boolean isRepeatable() {
return false;
 
}

@Override
public boolean isChunked() {
return false;
 
}

@Override
public Header getContentType() {
return new BasicHeader("Content-Type","application/json");
 
}

@Override
public long getContentLength() {
return data.length;
 
}

@Override
public Header getContentEncoding() {
return null;
 
}

@Override
public InputStream getContent() throws IOException,
 
IllegalStateException {
InputStream is = new ByteArrayInputStream(data, 0, data.length);
return is;
 
}

@Override
public void consumeContent() throws IOException {
 

}
});

DefaultHttpClient client = new DefaultHttpClient();
 
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
 
responseVo.setResponseCode(response.getStatusLine().getStatusCode());
Header[] headers = response.getAllHeaders();
for (Header hdr : headers) {
//Store the required headers
 
}

// Read response into a buffered stream
int readBytes = 0;
byte[] sBuffer = new byte[512];
while ((readBytes = inputStream.read(sBuffer)) != -1) {
 
content.write(sBuffer, 0, readBytes);
}
responseVo.setResponse(new String(content.toByteArray()));
 

return responseVo;
 
}

That's all :)