Tag Archives: Java

Using preference API in Android applications

This week’s homework in the android class was to persist the task information in the sample TaskManager application across program runs, which was created during the class.

Preference API

Android provides a preference API, using which we can store task information. The preference API is very simple to use and all we have to do is to get the instance to the preference object from the Application object and then call the getString() and putString() method.

Serializing ArrayList to string

The only tricky part of the home work is that, since the preference API supports only storing and retrieving of strings, we have to serialize and de-serialize the ArrayList object which has the list of tasks into string.

Instead of writing my own code to do this conversion, I used the code from the Apache Pig project. You can check out the class from the pig’s github page.

Storing the task

In the addTask() method of the TaskManagerApplication class, we have to get the instance of the shared preference and then store the serialized ArrayList using the putString() method.

	public void addTask(Task t) {
		assert(null != t);
		if (null == currentTasks) {
			currentTasks = new ArrayList<task>();
		}
		currentTasks.add(t);

		//save the task list to preference
		SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
		Editor editor = prefs.edit();
		try {
			editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
		} catch (IOException e) {
			e.printStackTrace();
		}
		editor.commit();
	}

Retrieving the task

Similarly we have to retrieve the list of tasks from the preference in the onCreate() method

	public void onCreate() {
		super.onCreate();
		if (null == currentTasks) {
			currentTasks = new ArrayList<task>();
		}

		//		load tasks from preference
		SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);

		try {
			currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

Finishing up

So that’s it, you are done. 🙂 All you have to do now is to save the project and run it in the emulator. If everything is done properly, the tasks that you enter will be saved even after you restart the app.

Source code

I have uploaded the entire project source code into github and you download it from there and verify it with your code.

Try to complete the homework, before the next session and do come back to view the notes and the homework for the next session too. 🙂

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , | 7 Comments

Developing Android applications in Java – Session 1 – My Notes

Like last week, I attended the session on Developing Android applications in Java by Creative Techs and O’Reilly and here are my notes which I took during the session.

Demo Application

In this week’s session, he created a sample task manager app which can be used for maintaining list of things to track. This app was created using Android 1.6 with Google API support. You can download the source code of this demo app below.

The sample app will have two activities. One will have a simple data entry form which can be used to add tasks and the other to view tasks which were entered. Check the screenshots below to see how the sample app looks like.

android-taskmanager-1 android-taskmanager-2

Layouts

Tony (the instructor) briefly explained about the different types of layouts and for the sample apps he used Relative Layout. You can read more about the relative layout from the android documentation.

The major pain point in using Relative layout is that, the controls should be specified in the order in which they are referenced and not in the order in which they will be displayed.

EditText control

EditText control is an editable control which can be used to get user input. It is similar to the HTML textbox or the Java Swing JTextField.

You can read more about EditText control from android documentation.

Sharing data between views

An application can have multiple activities (views) and to share data between these multiple activities, the android framework provides a class called Application. This Application class can be accessed from all the activities of the app by calling the getApplication() of the Activity class. Tony explained this about this class and also used it in the demo app to store and retrieve tasks from multiple activities.

You can find this class in the TaskManagerApplication.java in the sample app. You can download the source code of this demo app below.

Safe cancelling

Tony also explained about how to listen to text changes and make sure the user is not moving away from the activity when there are unsaved work.android-taskmanager-3

You can check the cancel() method in AddTaskActivity class, where we will be showing an alert box (see screenshot) using the built in AlertDialog, whenever the user clicks the cancel button without saving the task that he has entered.

You can read about the AlertDialog class in the android documentation.

Source code

I have uploaded source code for yesterday’s session in github and you can download it from there. I am also working in this week’s homework and will be posting the explanation and source code once I am done.

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , | 16 Comments

Android application that triggers the phone dial screen

As you know, I am following the free course on Developing Android applications in Java by CreativeTech and O’Reilly (even you should, if you are interested in developing apps for android) and this week’s homework in the course is to create an app which will show the phone dial screen when a button is clicked.

I just finished it and I thought of posting the source code and explanation so that it will be useful for others too.

Creating the project

The first step is to create the android project. You should follow the instructions given in the android documentation. You would need Eclipse and the android SDK to be installed to do this.

You will have an empty project to start with and with the default project structure, which I explained in my previous post.

Adding the button to the view

If you have followed the first session then you know that adding a button to the view is quite easy. All you have to do is to open your view file (/res/layout/main.xml) and add the following code.

<Button
    android:id="@+id/dialer_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/dialer"
/>

You should also declare the value for the @string/dialer key in your values (/res/values/strings.xml) file by adding the following line

<string name="dialer">Phone Dialer</string>

Adding the button to the activity

After adding the button to the view, we have to declare the button in the activity. To do so, we have to add the following line in the Activity file.

Button dialerButton = (Button)findViewById(R.id.dialer_button);

Bind the Listener to the button

After creating the button instance in the activity, we have to bind a click listener to it. In the click listener we have to invoke the Phone dialer intent. Add the following code to the activity

dialerButton.setOnClickListener(new OnClickListener() {
	@Override
	public void onClick(View v) {
		//open the phone dialer on clicking the button
		Intent intent = new Intent(Intent.ACTION_DIAL);
		startActivity(intent);
	}
});

In the above snippet the following line does the trick

Intent intent = new Intent(Intent.ACTION_DIAL);

It creates the intent, which will open the phone dialer.

Finishing up

So that’s it, you are done 🙂 All you have to do now is to save the project and run it in the emulator. If everything is done properly, you will see the following screen in the emulator.

android-homework-1  android-homework-2

When you click the button, it should open the phone dialer.

Source code

I have uploaded the entire project source code into github and you download it from there and verify it with your code.

Try to complete the homework, before the next session and do come back to view the notes and the homework for the next session too. 🙂

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , | 7 Comments

The structure of an Android project

In my notes for the first session on the “Developing Android applications with Java” course, I forgot to mention about the project structure, which Tony (the instructor) explained. So this is a follow-up post to my previous post where I wrote about the notes, which I took during the session.

Android project structure

After you create a new project in eclipse, you will see the following top-level folders in your package explorer.

android-project-structure-1

Let me explain each of them in detail

/srcandroid-project-structure-2

This folder will contain the Java source files that you will be creating. In the screenshot you can see the ‘activity’ files that were created for the sample project. The files inside this  folder will be organized according to the package structure. This is similar to the /src folder which is present in any normal Java project.

/genandroid-project-structure-3

This is also a source folder, but will be contain Java source files that will be automatically generated by the android platform. Notable among the generated Java files is the R class, which you see in the screenshot. The framework will generate R class file and you can read more about it in the android documentation.

/Android {version Number}

This is the folder, which will contain the libraries (jars) that are need for the project. In the screenshot, you can see that it contains the framework jar file. This is similar to the /lib folder which is present in any normal Java project.

/resandroid-project-structure-4

This directory contains all the external resources (images, data files etc) that are used by the android application. These external resources (content) will be referenced in the android application.

This contains the following sub-folders

  • /res/drawable
  • /res/layout
  • /res/Values

/res/drawable

This folder contains all images, pictures etc. If you want to include an image or an icon in your android application, then you will be placing it in this folder.

/res/layout

This folder contains the UI layouts that will be used in the project. These UI layouts are stored as XML files. You can read more about the UI layouts in the android documentation.

/res/Values

This folder again contains XML files, which contain key values pairs that will be referenced in the application. These XML files declare Arrays, colors, dimensions, strings etc. The main idea of having these values in a separate XML file is that the values can be used based on the locale without actually changing the source code. For example the messages in the application can be in different languages based on the use locale.

/assets

This folder also contains external resources used in the application like the /res folder. But the main difference is that the resources are stored in raw format and can be read only programmatically.

AndroidManifest.xml

This is an XML file which contains meta information about the android application and is important file for every android application project. It contains information about various activities, views, services etc. It also contains the list of user permissions that are needed to run the android application.

That explains the project structure of the android application. You can read more about it in the android documentation.

BTW how is your homework coming along? Hope you all were able to finish it quickly. I will be posting the source code for the homework together with the explanation soon. So stay tuned. 🙂

Update: I have also completed the homework for this session and have posted my source code and explanation.

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , , | 12 Comments

Developing Android applications in Java – Overview – My Notes

As I told before, I attended the free webinar by CreativeTech on Developing Android Applications with Java yesterday.

My friend Jaskirat, asked me write about the session since he missed some parts of it as he slept during the session. 🙂 Okay it was not because the session was boring, but due to the fact that 11 AM PST is midnight of us guys in India. I happily obliged and here are my notes from the session.

Introduction

The training started off with a brief introduction about the format of the session, about CreativeTech trainings, partnership with O’Reilly, brief profile of the author etc. They also explained how to use the GoTo Webinar console, ask questions etc.

Then there was a brief introduction about the android platform, its stack and how various components fit it. He also explained the various verbs like activity, intent etc. You can read about them in the Application fundamentals section of the android documentation.

Choosing the SDK version

Next there was a brief explanation about the SDK and the difference between android SDK and Google API’s and also about the various versions of SDK. This led to a brief Q&A session where people asked which version to SDK to target. The instructor then recommended targeting for SDK version 1.5. He said that version 1.5 strikes a balance between market reach and available features.

You can checkout the different versions of SDK and their market share in the android developer page.

Installing necessary software

After the Q&A, the instructor showed how to install the necessary software to follow the code samples.

You need to install the following

  • Eclipse
  • Android SDK
  • ADT Eclipse Plugin

You can follow the instructions in the android documentation page to install the above softwares.

After installing the necessary software, you should also create an Android Virtual Device (AVD), which will allow you to run the application in the Android Emulator.

Demo Application

The goal of the session was to introduce the android platform and to write a demo flashlight app.

The app will have two views (red and green, see screenshot), which can be toggled by clicking a button. The following are the screenshots of the application.

red-view green-view

Implementing the demo application

This was the meat of the presentation (but was pretty short due to time constraints), where he explained how to start writing code, to implement the demo application.

You can follow the steps in the “Hello World” tutorial of the android documentation to setup the project.

Source code

I have uploaded source code for yesterday’s session in github and you can download it from there.

The first session was really very good and I will be attending the remaining 5 sessions too and if possible will write blog posts with the notes that I take. Meanwhile if you are interested in developing android applications, then you should really watch this tutorial.

Update: I have added additional information about the android project structure in a subsequent post.

Update 2: I have also completed the homework for this session and have posted my source code and explanation.

Update 3: You can also view my notes for the next session.

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Posted in Android/Java | Tagged , , | 21 Comments

Free online course on developing android applications using Java

O’Reilly Training is conducting a 6-week online course which will help you to get started developing Android Applications with Java. The following is the official description

This free 6-week online course will get you started developing Android Applications with Java. You’ll learn hands on how to build actual working apps with Eclipse and the Android SDK, as well as the ins and outs of Android’s features

This online course if free if you watch it live, otherwise you may have to purchase it. You can check out the schedule in the official course page.

I check out the agenda and it seems to cover most of the basic things that you need to learn to develop applications using the Android platform. If you are interested then you register for the course at the official course page.

Posted in Android/Java | Tagged , , | 22 Comments

Why I (still) like Java

From the day I started programming, I have been on different camps on the battle between strongly typed and weekly typed languages at different times.

For close to 2 years I was working on a java project and at that time I used to wonder why it was designed to be so strongly typed. I have to declare each and every variable, initialize them, cast them properly if I am converting their data type etc and at times I used to get frustrated at the type of errors the complier throws at me every time I try to compile them. I wished I could tell the complier to stop guessing what I was trying to do and that I am smarter than it.

But now I understand their importance. I have recently started working on an ASP project (yes it is not migrated to ASP.NET yet!) and in last week I spent around half a day trying to figure out what was wrong in my code. All I got was just a simple ‘type mismatch’ error. The same lines of code were working perfectly in another page but not on this particular page. It was just an assignment statement which was calling a method and was assigning the return value to a variable.

After hours of debugging (with lot of head banging’s and nail bytes) I found out that I have forgotten to include the file in which that method was declared. If it had been my Java dear then it wouldn’t have thrown the apt ‘Method not found’ error the very first time I complied it. And I would have saved some a couple of hours of my time (and also my head and nails) 😉

Ohh my dear Java, I miss you very much dear..

Posted in Random/Personal, Web Programming | Tagged , , | 15 Comments

Learn J2EE programming with passion

Found this from SitePoint

Ready to get serious about learning Java Web application and enterprise application development? I can’t say I blame you those skills will net a pretty penny in the current job market. That’s why J2EE Programming (with Passion!), a free online class offered by Sun Microsystems employee Sang Shin in his spare time, is such an amazing opportunity.

Offered by means of a Yahoo! Groups discussion list, the class runs for about the length of a university semester. Once you subscribe, you’re responsible for reviewing the weekly pre-class reading material, reading the classroom slides with accompanying notes, and completing the assigned coursework and final project by the assigned dates. It’s just like taking a university class only you don’t have to show up at lectures oh, and did I mention it’s free?

If you’ve been awaiting an opportunity to learn J2EE in a structured way without shelling out a bunch of money on books and classes, this might just be the ticket. Sang Shin also offers a few other online classes, an advanced J2EE class among them.

The next session is starting today (26-Sep-2005) and I have registered for it. How about you?

Posted in Web Programming | Tagged , , , | 4 Comments

SCJP Next

I have taken a really looong break after my last exam. So its time that I start studying again for exams and after much thought I have finally decided my next exam. It’s going to be SCJP (CX-310-035).

The reason for choosing SCJP is that, for the next year or two I have to work mostly in java and will not be able to use much of .NET (at least at work).

Currently Sun is giving a discount of 25% for the exam till 30th of June. But I don’t think I can take up the exam with 9 days. I have kept the third week of July as my target for this exam. Hope I meet it.

BTW I am planning to use the book Sun Certified Programmer and Developer for Java 2 Study Guide (Exams 310-035 and 310-027) by OSBORNE. Does any one have a better suggestion..?

PS: Probably my friend Ram could help me, as he has already completed SCJP 😉

Posted in Certifications | Tagged , , | 2 Comments