Avoid Memory leaks in Android Program.
* Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
At the onset of learning customizing lists its tempting to do this mistake. We just pass reference of the present context to the adapater.
Now the problem arises when we use our programming skills to release the activity and its resources on OnDestroy callback, while activity gets destroyed but remember reference to the this activity context is still referenced by our list. And this leaks the Context means it can't be reclaimed by Garbage collector.
* Try using the context-application instead of a context-activity
Context.getApplicationContext() and use it in the application.
* Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance
* A garbage collector is not an insurance against memory leaks
Android OS Beginning
Sunday, May 22, 2011
Sunday, April 10, 2011
Android c2dm : Demystified
Motivation
My Project manager told me that he doesn't want to poll the server frequently to get the updated data. Probably he wants to come up with a solution that doesn't drains user pocket (due to Network Connection on Mobile operator's GPRS) and device battery.
Googled net a lot and found that Google Android Team has already come up with a solution Android Cloud to Device Messaging framework for Android 2.2 to resolve the above issues by using server push mechanism to send updates to devices.
Thanks Google.
So what's this Cloud to Device Messaging Framework.
Android Cloud to Device Messaging Framework
Android Cloud to Device Messaging (C2DM) is a service that helps developers send data from servers to their applications on Android devices. The service provides a simple, lightweight mechanism that servers can use to tell mobile applications to contact the server directly, to fetch updated application or user data. The C2DM service handles all aspects of queueing of messages and delivery to the target application running on the target device.
Architectural Overview : Working
This table summarizes the key terms and concepts involved in C2DM. It is divided into these categories:
* Components — The physical entities that play a role in C2DM.
* Credentials — The IDs and tokens that are used in different stages of C2DM to ensure that all parties have been authenticated, and that the message is going to the correct place.
Components
Mobile Device
The device that is running an Android application that uses C2DM. This must be a 2.2 Android device that has Market installed, and it must have at least one logged in Google account.
Third-Party Application Server
An application server that developers set up as part of implementing C2DM in their applications. The third-party application server sends data to an Android application on the device via the C2DM server.
C2DM Servers
The Google servers involved in taking messages from the third-party application server and sending them to the device.
Credentials
Sender ID
An email account associated with the application's developer. The sender ID is used in the registration process to identify a Android application that is permitted to send messages to the device. This ID is typically role-based rather than being a personal account—- for example, my-app@gmail.com.
Generally while registering the account at c2dm servers only test quota is given . To get production quota a discussion with c2dm server maintainers is needed. Production quota is not free.
Application ID
The application that is registering to receive messages. The application is identified by the package name from the manifest. This ensures that the messages are targeted to the correct application. Important to keep the package name same.
Registration ID
An ID issued by the C2DM servers to the Android application that allows it to receive messages. Once the application has the registration ID, it sends it to the third-party application server, which uses it to identify each device that has registered to receive messages for a given application. In other words, a registration ID is tied to a particular application running on a particular device.
Google User Account
For C2DM to work, the mobile device must include at least one logged in Google account.
Sender Auth Token
Auth token that the sender has already got from Google servers using ClientLogin.
Below it the php code to get AuthToken using Client Login
$userName=$_REQUEST['userName'];
$passWord=$_REQUEST['passWord'];
$userName="email add";
$passWord="password";
$auth = exec("curl https://www.google.com/accounts/ClientLogin \
--data-urlencode Email=".$userName." --data-urlencode Passwd=".$passWord." \
-d accountType=GOOGLE \
-d source=Google-cURL-Example \
-d service=ac2dm");
echo $auth;
$realAuth = substr($auth,5);
echo "
".$realAuth;
echo "
".strlen($realAuth);
mysql_connect("localhost","root","success") or die ('error connecting to mysql');
mysql_select_db("ctodm") or die('error connecting to database');
// put here logic where first id is determined if found values will be updated
// else new row would be inserted
$authorizeAccount=$userName;
$query = "TRUNCATE TABLE `tokendet`";
$query = "INSERT INTO tokendet (tokenid,senderemail) VALUES ('$realAuth','$authorizeAccount')";
mysql_query($query) or die ("Error updating database");
echo 'database updated';
After getting the authtoken store it in a database table.
Now get the client code modify it and use it
Client Code : https://sites.google.com/site/androidosbeginning/C2DM.zip?attredirects=0&d=1
If issues in using it ... wait for the next post I will be back.
Thanks
My Project manager told me that he doesn't want to poll the server frequently to get the updated data. Probably he wants to come up with a solution that doesn't drains user pocket (due to Network Connection on Mobile operator's GPRS) and device battery.
Googled net a lot and found that Google Android Team has already come up with a solution Android Cloud to Device Messaging framework for Android 2.2 to resolve the above issues by using server push mechanism to send updates to devices.
Thanks Google.
So what's this Cloud to Device Messaging Framework.
Android Cloud to Device Messaging Framework
Android Cloud to Device Messaging (C2DM) is a service that helps developers send data from servers to their applications on Android devices. The service provides a simple, lightweight mechanism that servers can use to tell mobile applications to contact the server directly, to fetch updated application or user data. The C2DM service handles all aspects of queueing of messages and delivery to the target application running on the target device.
Architectural Overview : Working
This table summarizes the key terms and concepts involved in C2DM. It is divided into these categories:
* Components — The physical entities that play a role in C2DM.
* Credentials — The IDs and tokens that are used in different stages of C2DM to ensure that all parties have been authenticated, and that the message is going to the correct place.
Components
Mobile Device
The device that is running an Android application that uses C2DM. This must be a 2.2 Android device that has Market installed, and it must have at least one logged in Google account.
Third-Party Application Server
An application server that developers set up as part of implementing C2DM in their applications. The third-party application server sends data to an Android application on the device via the C2DM server.
C2DM Servers
The Google servers involved in taking messages from the third-party application server and sending them to the device.
Credentials
Sender ID
An email account associated with the application's developer. The sender ID is used in the registration process to identify a Android application that is permitted to send messages to the device. This ID is typically role-based rather than being a personal account—- for example, my-app@gmail.com.
Generally while registering the account at c2dm servers only test quota is given . To get production quota a discussion with c2dm server maintainers is needed. Production quota is not free.
Application ID
The application that is registering to receive messages. The application is identified by the package name from the manifest. This ensures that the messages are targeted to the correct application. Important to keep the package name same.
Registration ID
An ID issued by the C2DM servers to the Android application that allows it to receive messages. Once the application has the registration ID, it sends it to the third-party application server, which uses it to identify each device that has registered to receive messages for a given application. In other words, a registration ID is tied to a particular application running on a particular device.
Google User Account
For C2DM to work, the mobile device must include at least one logged in Google account.
Sender Auth Token
Auth token that the sender has already got from Google servers using ClientLogin.
Below it the php code to get AuthToken using Client Login
$userName=$_REQUEST['userName'];
$passWord=$_REQUEST['passWord'];
$userName="email add";
$passWord="password";
$auth = exec("curl https://www.google.com/accounts/ClientLogin \
--data-urlencode Email=".$userName." --data-urlencode Passwd=".$passWord." \
-d accountType=GOOGLE \
-d source=Google-cURL-Example \
-d service=ac2dm");
echo $auth;
$realAuth = substr($auth,5);
echo "
".$realAuth;
echo "
".strlen($realAuth);
mysql_connect("localhost","root","success") or die ('error connecting to mysql');
mysql_select_db("ctodm") or die('error connecting to database');
// put here logic where first id is determined if found values will be updated
// else new row would be inserted
$authorizeAccount=$userName;
$query = "TRUNCATE TABLE `tokendet`";
$query = "INSERT INTO tokendet (tokenid,senderemail) VALUES ('$realAuth','$authorizeAccount')";
mysql_query($query) or die ("Error updating database");
echo 'database updated';
After getting the authtoken store it in a database table.
Now get the client code modify it and use it
Client Code : https://sites.google.com/site/androidosbeginning/C2DM.zip?attredirects=0&d=1
If issues in using it ... wait for the next post I will be back.
Thanks
Tuesday, November 30, 2010
JSON Parsing Example
1. Create an Android application with one activity, name it as you wish, if you are doing it in eclipse all the basic stuff will be generated for you which is exactly what we need.
2. Find an example url which responds in JSON, I have used Twitter Trends found here: http://search.twitter.com/trends.json
The example response looks like this:
{"as_of":"Thu, 25 Feb 2010 11:30:17 +0000","trends":[{"name":"#nowplaying","url":"http://search.twitter.com/search?q=%23nowplaying"},{"name":"#nothingworsethan","url":"http://search.twitter.com/search?q=%23nothingworsethan"},{"name":"Dubai Mall","url":"http://search.twitter.com/search?q=%22Dubai+Mall%22"},{"name":"iPad Gets","url":"http://search.twitter.com/search?q=%22iPad+Gets%22"},{"name":"#SuperJuniorTrot","url":"http://search.twitter.com/search?q=%23SuperJuniorTrot"},{"name":"Justin Bieber","url":"http://search.twitter.com/search?q=%22Justin+Bieber%22"},{"name":"Click","url":"http://search.twitter.com/search?q=Click"},{"name":"Jaebum","url":"http://search.twitter.com/search?q=Jaebum"},{"name":"#tosavemoney","url":"http://search.twitter.com/search?q=%23tosavemoney"},{"name":"Protection","url":"http://search.twitter.com/search?q=Protection"}]}
As you can see this json data contains date attribute called ‘as_of’ as well as array of items, each consisting of name and url attributes.
We will create two simple java classes wich will hold that information.
First one is TwitterTrends.java
package com.softwarepassion.jsonexample;
import java.util.Date;
import java.util.List;
public class TwitterTrends {
private String as_of;
private List trends;
public String getAs_of() {
return as_of;
}
public void setAs_of(String asOf) {
as_of = asOf;
}
public List getTrends() {
return trends;
}
public void setTrends(List trends) {
this.trends = trends;
}
}
And the second one is a simple TwitterTrend.java
package com.softwarepassion.jsonexample;
public class TwitterTrend {
private String name;
private String url;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
TwitterTrends contains a list of TwitterTrend objects, both of them are simple beans and are very similar to the json response if you look closely
Now the fun part begins.
Download the Gson library from http://code.google.com/p/google-gson/ and add it to your java build path in eclipse.
Once you do that, you can now transform your json response to Java object on Android Platform:
Get the response as InputStream:
public InputStream getJSONData(String url){
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri;
InputStream data = null;
try {
uri = new URI(url);
HttpGet method = new HttpGet(uri);
HttpResponse response = httpClient.execute(method);
data = response.getEntity().getContent();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
Then use that input stream to create your java objects:
public void runJSONParser(){
try{javascript:void(0)
Log.i("MY INFO", "Json Parser started..");
Gson gson = new Gson();
Reader r = new InputStreamReader(getJSONData("http://search.twitter.com/trends.json"));
Log.i("MY INFO", r.toString());
TwitterTrends objs = gson.fromJson(r, TwitterTrends.class);
Log.i("MY INFO", ""+objs.getTrends().size());
for(TwitterTrend tr : objs.getTrends()){
Log.i("TRENDS", tr.getName() + " - " + tr.getUrl());
}
}catch(Exception ex){
ex.printStackTrace();
}
}
2. Find an example url which responds in JSON, I have used Twitter Trends found here: http://search.twitter.com/trends.json
The example response looks like this:
{"as_of":"Thu, 25 Feb 2010 11:30:17 +0000","trends":[{"name":"#nowplaying","url":"http://search.twitter.com/search?q=%23nowplaying"},{"name":"#nothingworsethan","url":"http://search.twitter.com/search?q=%23nothingworsethan"},{"name":"Dubai Mall","url":"http://search.twitter.com/search?q=%22Dubai+Mall%22"},{"name":"iPad Gets","url":"http://search.twitter.com/search?q=%22iPad+Gets%22"},{"name":"#SuperJuniorTrot","url":"http://search.twitter.com/search?q=%23SuperJuniorTrot"},{"name":"Justin Bieber","url":"http://search.twitter.com/search?q=%22Justin+Bieber%22"},{"name":"Click","url":"http://search.twitter.com/search?q=Click"},{"name":"Jaebum","url":"http://search.twitter.com/search?q=Jaebum"},{"name":"#tosavemoney","url":"http://search.twitter.com/search?q=%23tosavemoney"},{"name":"Protection","url":"http://search.twitter.com/search?q=Protection"}]}
As you can see this json data contains date attribute called ‘as_of’ as well as array of items, each consisting of name and url attributes.
We will create two simple java classes wich will hold that information.
First one is TwitterTrends.java
package com.softwarepassion.jsonexample;
import java.util.Date;
import java.util.List;
public class TwitterTrends {
private String as_of;
private List
public String getAs_of() {
return as_of;
}
public void setAs_of(String asOf) {
as_of = asOf;
}
public List
return trends;
}
public void setTrends(List
this.trends = trends;
}
}
And the second one is a simple TwitterTrend.java
package com.softwarepassion.jsonexample;
public class TwitterTrend {
private String name;
private String url;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
TwitterTrends contains a list of TwitterTrend objects, both of them are simple beans and are very similar to the json response if you look closely
Now the fun part begins.
Download the Gson library from http://code.google.com/p/google-gson/ and add it to your java build path in eclipse.
Once you do that, you can now transform your json response to Java object on Android Platform:
Get the response as InputStream:
public InputStream getJSONData(String url){
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri;
InputStream data = null;
try {
uri = new URI(url);
HttpGet method = new HttpGet(uri);
HttpResponse response = httpClient.execute(method);
data = response.getEntity().getContent();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
Then use that input stream to create your java objects:
public void runJSONParser(){
try{javascript:void(0)
Log.i("MY INFO", "Json Parser started..");
Gson gson = new Gson();
Reader r = new InputStreamReader(getJSONData("http://search.twitter.com/trends.json"));
Log.i("MY INFO", r.toString());
TwitterTrends objs = gson.fromJson(r, TwitterTrends.class);
Log.i("MY INFO", ""+objs.getTrends().size());
for(TwitterTrend tr : objs.getTrends()){
Log.i("TRENDS", tr.getName() + " - " + tr.getUrl());
}
}catch(Exception ex){
ex.printStackTrace();
}
}
Sunday, October 17, 2010
Playing Media in Android
Today I 'm gonna tell you how much easy it is to play media in Android from a URL and your function is here.
public void playMedia(){
MediaPlayer mp = new MediaPlayer();
// here could be the video url too
mp.setDataSource(this,Uri.parse("http://blab..balal.mp3"));
mp.prepare();
mp.start();
}
MediaPlayer object contains start, pause , and stop and still requires a bit of research by you.. So enjoy the research !!!!!
public void playMedia(){
MediaPlayer mp = new MediaPlayer();
// here could be the video url too
mp.setDataSource(this,Uri.parse("http://blab..balal.mp3"));
mp.prepare();
mp.start();
}
MediaPlayer object contains start, pause , and stop and still requires a bit of research by you.. So enjoy the research !!!!!
Monday, September 27, 2010
HttpConnection Time out
Here's the code
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(envelope,HTTP.UTF_8);
httppost.setEntity(se);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httppost);
HttpEntity entity = httpResponse.getEntity();
return entity;
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(envelope,HTTP.UTF_8);
httppost.setEntity(se);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httppost);
HttpEntity entity = httpResponse.getEntity();
return entity;
Thursday, September 23, 2010
Generic Xml Parsing in Android
Here's the code
public void genericXmlParsing(String raw) throws Exception{
DocumentBuilder builder = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(raw)));
NodeList elementNames = doc.getElementsByTagName("ElementName");
NodeList elementValues = doc.getElementsByTagName("ElementValue");
for(int i=0;i Element elementName = (Element)elementNames.item(i);
ParsedXmlData parsedXmlData = new ParsedXmlData();
parsedXmlData.setElementName(elementName.getFirstChild().getNodeValue());
parsedXmlDataList.add(parsedXmlData);
}
for(int i=0;i Element elementValue = (Element)elementValues.item(i);
ParsedXmlData parsedXmlData = parsedXmlDataList.get(i);
parsedXmlData.setElementValue(elementValue.getFirstChild().getNodeValue());
}
}
public void genericXmlParsing(String raw) throws Exception{
DocumentBuilder builder = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(raw)));
NodeList elementNames = doc.getElementsByTagName("ElementName");
NodeList elementValues = doc.getElementsByTagName("ElementValue");
for(int i=0;i
ParsedXmlData parsedXmlData = new ParsedXmlData();
parsedXmlData.setElementName(elementName.getFirstChild().getNodeValue());
parsedXmlDataList.add(parsedXmlData);
}
for(int i=0;i
ParsedXmlData parsedXmlData = parsedXmlDataList.get(i);
parsedXmlData.setElementValue(elementValue.getFirstChild().getNodeValue());
}
}
Wednesday, September 22, 2010
XML Layout for Android
Ques:
Is there a way to display a View, such as a TextView sideways using the XML layout file? I know you can rotate the view using code in an activity, but is there a way just to do it with layout?
here's the answer
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:layout_weight="5"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:text="sideways dummy text sideways dummy text sideways dummy text sideways dummy text sideways dummy text sideways dummy text sideways dummy text"
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:text="Text Here"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
Is there a way to display a View, such as a TextView sideways using the XML layout file? I know you can rotate the view using code in an activity, but is there a way just to do it with layout?
here's the answer
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_height="fill_parent">
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
Subscribe to:
Posts (Atom)