Recent Posts
- November 2014 (1)
- January 2014 (1)
- October 2013 (1)
- May 2013 (1)
- February 2013 (2)
- October 2012 (1)
- August 2012 (1)
- July 2012 (4)
- June 2012 (13)
Blog Stats
- 36,360 hits
Write your code smartly
Here in this post I will write about how AsyncTask can be created as a single class to make it re useable for other activities. There are some ways to handle the background operations well-known-ed for foreground apps (not services). AsyncTask allows you to execute a specific task such as downloading, loading content from web or communication to server without blocking the main thread (user interface). Writing the code for AsyncTask is quite simple, but what when you have more than one activity to process same piece of code/task in AsyncTask. Now here comes the greatest benefit of Object Oriented Programming concepts and mechanism to write a code which can be re-used. Thanks to an interview question which made me dive into this and get to know how can this be achieved. What we will do here is, create a single AsyncTask and put it in a separate class and make use of it in which ever activity we want. The main problem comes with handling the result of the AsyncTask operation. Lets have a look at how AsyncTask class can be extended to our custom class and we can perform operations required to be done in the background.
First you have to create ad simple class and extend it from AsyncTask
public class myCustomAsyncTask extends AsyncTask{
}
Now myCustomAsyncTask will have a compile time error, stating first suggestion to be : Add unimplemented methods. As you are performing inheritance here and extending the AsyncTask parent class, there is a method defined which must be implemented and that is doInBackground
@Override
protected Object doInBackground(Object... arg0){
return null;
}
doInBackground is the method where the background operation is performed. There are other methods provided by AsyncTask such as onPreExecute, onPostExecute, onCancelled, onProgressUpdate having their own benefits.
If you want to perform some tasks prior to your main background operation such as some parameters initialization, load resources etc, you can do that in onPreExecute method
@Override
protected void onPreExecute(){
// Your code
}
Once we execute AsyncTask, the first method called is onPreExecute and then doInBackground. Now what after the background operations are completed and you want to show some response or play with result. Here comes to use of onPostExecute
protected void onPostExecute(Object o){
// Your code to handle data
}
Note: Updating any UI controls is not allowed in doInBackground method but can be done inside onPostExecute, like update text of a textview or progress bar etc…
So lets create a AsyncTask first.
public class YourAsyncTask extends AsyncTask<Object,Object,Object>{
String s = "";
public YourAsyncTask(){
}
@Override
protected Object doInBackground(Object... arg0) {
return null;
}
protected void onPostExecute(Object o){
}
}
Here we have overridden two AsyncTask methods: doInBackground and onPostExecute. It also have a constructor to get the context of the activity invoking it.
Now there are several ways on handling the response, but without getting out of the Activity context (making activity class members dead (non-static fields)) is what meant here.
Making use of Interface is useful here. Interface helps you implement it when its required by simply using implement following your class name and Interface name.
But before that lets make an interface so we can handle the response of the AsyncTask by implementing its method.
public interface OnTaskCompleted {
void onTaskCompleted(String response);
}
As the above interface shows, there is a method onTaskCompleted which takes an argument of String type must be implemented by any class implementing the interface.
We implement the interface through our activity using
public class MainActivity extends Activity implements OnTaskCompleted {
}
It will ask you to implement unimplemented methods so go ahead with it and you will see the method inside interface onTaskCompleted will be added to the activity class.
public class MainActivity extends Activity implements OnTaskCompleted {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onTaskCompleted(String response) {
}
}
Now using AsyncTask from activity. We will do this inside onCreate method of the activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YourAsyncTask task = new YourAsyncTask(MainActivity.this);
task.execute();
}
Now lets add onTaskCompleted (interface) to the AsyncTask and return the response from onPostExecute. It is also the final code of AsyncTask implementation.
public class YourAsyncTask extends AsyncTask<Object,Object,Object>{
String s = "";
private onTaskCompleted taskCompleted;
public YourAsyncTask(OnTaskCompleted activityContext){
this.taskCompleted = activityContext;
}
@Override
protected Object doInBackground(Object... arg0) {
return null;
}
protected void onPostExecute(Object o){
taskCompleted.onTaskCompleted(s);
}
}
Add the response handling code in the implemented method onTaskCompleted inside activity.
@Override
public void onTaskCompleted(String response) {
// Just showing the response in a Toast message
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
Here is how your final Interface code looks
public interface OnTaskCompleted {
void onTaskCompleted(String response);
}
Activity Full code
public class MainActivity extends Activity implements OnTaskCompleted {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YourAsyncTask task = new YourAsyncTask(MainActivity.this);
task.execute();
}
@Override
public void onTaskCompleted(String response) {
// Just showing the response in a Toast message
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
You can contact me by visiting the about page and picking up the contact details.
Happy coding!
The following post is about simple TCP Client Server communication sample using Java code for Android. The steps are simple as defined below. TCP communication is done over inter-network or internal network (not necessary internet working). There must be an IP-Address for destination and a unique port (with unique I mean is not one which is used for standard protocols such as File Transfer Protocol (FTP) uses port number 21, TCP uses port 80) list can be found here for more reference. The port range is from 1 to 65535. Selecting a port from this range and an IP address, you can simply transmit data over network directly to the destination port.
TCP Client connection to TCP server to send data
try{
// Creating new socket connection to the IP (first parameter) and its opened port (second parameter)
Socket s = new Socket("192.168.1.1", 5555);
// Initialize output stream to write message to the socket stream
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String outMsg = "";
outMsg = "This is Client";
// Write message to stream
out.write(outMsg);
// Flush the data from the stream to indicate end of message
out.flush();
// Close the output stream
out.close();
// Close the socket connection
s.close();
}
catch(Exception ex){
//:TODO Handle exceptions
}
A simple TCP server to receive the TCP packet from client.
TCP Server receive the data using the port as IP address is just mentioned from the source and not required anywhere for TCP Server.
try{
ServerSocket ss = null;
// Initialize Server Socket to listen to its opened port
ss = new ServerSocket(5555);
// Accept any client connection
Socket s = ss.accept();
// Initialize Buffered reader to read the message from the client
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
// Get incoming message
String incomingMessage = in.readLine() + System.getProperty("line.separator");
// Use incomingMessage as required
System.out.print(incomingMessage);
// Close input stream
in.close();
// Close Socket
s.close();
// Close server socket
ss.close();
}
catch(Exception ex){
//:TODO Handle exceptions
}
You can utilize the received message accordingly.
To test the working example on Android devices you must add permissions to AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
Cheers !
I am going to explain and show how you can easily parse a normal xml response using DOM Parsing concept. There are other parsing methods such as Pull Parsing and SAX Parsing and its on the choice of the developer in which way they want to parse.
Here is a simple XML response which can be a local file or accessible from the web.
<?xml version="1.0" encoding="utf-8"?> <settings> <woeid> <countrywoeid>2211096</countrywoeid> <countryname>Asia/Karachi</countryname> </woeid> <woeid> <countrywoeid>2211177</countrywoeid> <countryname>Asia/Karachi</countryname> </woeid> <woeid> <countrywoeid>2459115</countrywoeid> <countryname>America/New_York</countryname> </woeid> <woeid> <countrywoeid>1940345</countrywoeid> <countryname>Asia/Dubai</countryname> </woeid> <woeid> <countrywoeid>1105779</countrywoeid> <countryname>Australia/Sydney</countryname> </woeid> <woeid> <countrywoeid>2251945</countrywoeid> <countryname>Asia/Tehran</countryname> </woeid> </settings>
This is a local file inside the sdcard of the Android device. Using the code below we can access the XML file on the root of the sdcard.
InputStream filename = null;
//parse the local XML file
filename=new FileInputStream("/sdcard/weatherFile.xml");
InputSource is = new InputSource(filename);
Using the InputStream class we can easily set the location of the xml file in the sdcard as shown in the code above. InputSource uses the instance of the InputStream to utilize it in further parsing. Here is how we can use DocumentBuilder class to create a document of the xml response to parse its all nodes.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc=db.parse(new InputSource(is.getByteStream())); doc.getDocumentElement().normalize();
Document builder helps to create a tree structure with nodes in normalized form. The list of the nodes can be collected in the NodeList instance for further traversing.
NodeList nodeList = doc.getElementsByTagName("woeid");
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
pointer++;
woeid=Integer.parseInt(fstElmnt.getElementsByTagName("countrywoeid").item(0).getTextContent());
timeZone=fstElmnt.getElementsByTagName("countryname").item(0).getTextContent();
}
You can collect the all the nodes text in an array or you can get in a string variable and upon your requirement, it is easily used further.
So here is how the final code looks
InputStream filename = null;
//parse the local XML file
filename=new FileInputStream("/sdcard/weatherFile.xml");
InputSource is = new InputSource(filename);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc=db.parse(new InputSource(is.getByteStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("woeid");
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
pointer++;
woeid=Integer.parseInt(fstElmnt.getElementsByTagName("countrywoeid").item(0).getTextContent());
timeZone=fstElmnt.getElementsByTagName("countryname").item(0).getTextContent();
}
Hello,
Today this post will give you an idea about , how you can get the current location of your Windows Phone device. This can be easily achieved by using `GeoCoordinateWatcher` class under the namespace using System.Device.Location;
Here is the code by which you can get the Longitude and Latitude values of the device location.
This code gets the current position of Windows Phone device in the form of Longitude and Latitude. Using these values, many different Location features can be implemented such as distance finding between two locations , mapping the location on Bing and Google maps and more.
For any further query you can contact on below addresses:
Email: jkhan@programmer.net
Skype: jibrankhan1990
Hi, today I am going to guide you about how can you configure your system for developing Blackberry applications.
First of all you need Java Development Kit to run Eclipse on your system and it can be downloaded from here.
Try to Install Java development Kit in the directory without spaces in between their names like C:\Java or something similar.
Once you installed the JDK you must configure you environment variables pointing to your Java folder like this.
Go to
System Properties ==>Advance System Properties==> Environment Variables==> In the bottom list select New==> Provide the variable name "JAVA_HOME" without quotation marks
Provide the value by putting the full path to the JAVA folder where you have installed the JDK version. I have mentioned above that if you installed it in drive C root then variable value will be C:\Java\jdk 1.7.0 (install at least 1.6.0 and replace the value I have written with your version).
Now you are done with it. You need to download the Blackberry Plugin for Eclipse from here.
Simply install the “exe” file on your system. Run the Plugin from the desktop if you have allowed the shortcut to be at desktop.
Select File ==> New==>Project==> Blackberry Project==>Next==>Give Project Name==>Next==>Next==>Select Hello Blackberry Template==>Finish.
Once you create your project , run the application from top green circle button. The simulator will be launched and you app icon will be displayed on the mobile desktop. Click on it and see your demo application running.
I hope this helped you and you soon will start blackberry apps development. Happy Coding!
Today I will step by step guide you how you can create a “msi” (Microsoft Installer) or “exe” file for your application, so your users can only download your setup file and install your created application.
Open Visual studio and select new project from file menu.In installed templates on the left you will see “other Project types” under that ==> Setup and deployment and ==> Visual studio installer. After that in project types select Setup project and name your setup project as your application name and press ok.
You will see a the new project created in like this:
Now on your left you will see three folders displaying, Application folder, User’s Desktop and User’s Program Menu.
Now setup or project. On application folder right click and Add==>File
Click on file and browse till your project’s folder ==> bin==>debug==> your “exe” file of the project. Remember it will be in (*.exe) format.
Also you have to add the required framework setup exe which is required to run your application. add similarly framework 4 setup if you have developed your application in .NET framework 4.0, add framework 3.5 setup if you have developed your application in .NET framework 3.5, and so on, in the application folder.
Select User’s Desktop folder and right click on the window showing on the right side of the project and ==> Create new Shortcut.
Click on Application Folder and press Ok. After pressing Ok you will see your added exe file , select it and again press ok. This will add the shortcut of your application in user’s Desktop folder. Similarly do it for User’s Program Menu.
One last thing is select your Application folder and in the property window set your Always Create Property to “True. Do this for User’s Desktop and User’s Program Menu also.
Now build your project by ctlrl+shift+b. You will find your msi file in the folder location of the this project where you created it or saved it.
Your feed back is more important for my future work 🙂
enjoy!
Here i will tell you how to invoke Camera in Windows phone application. Its as simple as you can use a camera in your cell phone.
So now add a button any where in your Windows Phone application from toolbox and double click it to get the click event handler or find the click event from its properties windows show in previous posts.
Please add the following namespace on top of your CS file or code file
using Microsoft.Phone.Tasks;
Add following code on the click event of the button.
private void button1_Click(object sender, RoutedEventArgs e)
{
CameraCaptureTask cmt = new CameraCaptureTask();
cmt.Completed += new EventHandler<PhotoResult>(cmt_Completed);
cmt.Show();
}
The Camera will be launched after clicking button with a dummy Black object moving around a white screen. by pressing the Capture button you can capture the image. You can Play with the image captured in your application like displaying it on image control.
Put the below code in Camera photo result event
void cmt_Completed(object sender, PhotoResult e)
{
//throw new NotImplementedException();
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
image1.Source = bi;
}
Enjoy Happy Coding !
In previous post I explained the simple process of getting started guide with Windows Phone development and how to configure it in your development PC. In this post I will show how to create a simple calculator with addition property ( you can alter by your self with its operator -, *, /). The new project with simple Windows phone page, drop 2 text boxes from toolbar on left and a button. Now click on a text box and on the right bottom you will see a property window, find the property “TEXT” and remove the word text box written in front of it. Do this for other as well. Now change the button “Content” property to “Add”.
If you want to create text boxes and button through code then use the following code sample and place it inside the second grid tag.
<TextBox Height=”72″ HorizontalAlignment=”Left” Margin=”10,43,0,0″ Name=”textBox1″ Text=”” VerticalAlignment=”Top” Width=”460″ Grid.Row=”1″ />
<TextBox Height=”72″ HorizontalAlignment=”Left” Margin=”10,125,0,0″ Name=”textBox2″ Text=”” VerticalAlignment=”Top” Width=”460″ Grid.Row=”1″ />
<Button Content=”Add” Grid.Row=”1″ Height=”72″ HorizontalAlignment=”Left” Margin=”152,209,0,0″ Name=”button1″ VerticalAlignment=”Top” Width=”160″ />
Here how now design view XAML code looks like
<Grid x:Name=”LayoutRoot” Background=”Transparent”>
<Grid.RowDefinitions>
<RowDefinition Height=”Auto”/>
<RowDefinition Height=”*”/>
</Grid.RowDefinitions>
<!–TitlePanel contains the name of the application and page title–>
<StackPanel x:Name=”TitlePanel” Grid.Row=”0″ Margin=”12,17,0,28″>
<TextBlock x:Name=”ApplicationTitle” Text=”MY APPLICATION” Style=”{StaticResource PhoneTextNormalStyle}”/>
<TextBlock x:Name=”PageTitle” Text=”page name” Margin=”9,-7,0,0″ Style=”{StaticResource PhoneTextTitle1Style}”/>
</StackPanel>
<!–ContentPanel – place additional content here–>
<Grid x:Name=”ContentPanel” Grid.Row=”1″ Margin=”12,0,12,0″></Grid>
<TextBox Height=”72″ HorizontalAlignment=”Left” Margin=”10,43,0,0″ Name=”textBox1″ Text=”” VerticalAlignment=”Top” Width=”460″ Grid.Row=”1″ />
<TextBox Height=”72″ HorizontalAlignment=”Left” Margin=”10,125,0,0″ Name=”textBox2″ Text=”” VerticalAlignment=”Top” Width=”460″ Grid.Row=”1″ />
<Button Content=”Add” Grid.Row=”1″ Height=”72″ HorizontalAlignment=”Left” Margin=”152,209,0,0″ Name=”button1″ VerticalAlignment=”Top” Width=”160″ />
</Grid>
Now select the Button and go back to the property window, here you will see two tabs on the top of this window i.e “Properties” and “Events“. Click on the events tab and find out the “Click”. Double click on the event this will take you to the code file named as MainPage.xaml.cs and into the click event of the button. Here now you code the following :
private void button1_Click(object sender, RoutedEventArgs e)
{
int a,b;
long c;
a = Convert.ToInt16(textBox1.Text);
b = Convert.ToInt16(textBox2.Text);
c = a + b;
MessageBox.Show(c.ToString());
}
Now on top you can see a Play button in green color press that, you will see a emulator booting OS, This is because Emulators are designed with the same configuration as the original phones thats why you must meet the requirements of it. Now your application will run and the layout you designed will be displayed. Provide the values in text boxes and press add, you will see the answer in the message box. if not please go through it again.
Understanding the Event Code
int a,b; long c;
We have declared to Integer variables a and b to collect text box values in them and a long integer variable to collect their Sum.
a = Convert.ToInt16(textBox1.Text); b = Convert.ToInt16(textBox2.Text);
We have to convert the textbox values to integer because the addition operator is performed on numbers and textbox values are of TEXT type or Strings.
c = a + b; MessageBox.Show(c.ToString());
add the values of a and b and place the answer in c. Now displaying the answer c in a message box we have to again convert the c (which has a numeric answer) to String as Message Box is a class which only displays Strings.
Hope you got simple way to work with this post if any queries then leave a comment below.
Windows Phone applications are created using C# language on .NET platform 4.0 or above. Simply you must have Visual Studio 2010 service pack 1 installed on your system, if not you can find it fromHere. This down loader will install Windows Phone SDK along with Visual Studio Express limited for Windows phone development. Along with the SDK the Emulator for testing your apps live will also be installed for which you required at-least 2 GB memory. Once you have configured all the setup you are ready to build your first Windows Phone application.
Open Visual Studio Express for Windows Phone and click > File from the menu. Then new Project > Silverlight for Windows Phone .
Now here you can select different type of controls offered by Windows Phone, it includes Panorama, Pivot and simple application. Here how it looks like.
Give the name and location and then press OK. You will see this design view of your first application.
here you can see 2 blocks divided, one is the phone showing the Windows phone and second on the right side is the Silver light code (XAML) generated when you make changes on the phone design by dragging controls from toolbar to the phone. Toolbar is on the left side having common controls . Using these controls you can develop a Windows Phone application. In further posts i will be telling you how you can create a working simple app using XAML and C# code so stay tune and queries you can post comments below.
Happy Coding !