playing with sdcard in android
Howdy everyone, today i am going to share a little code snippet that i developed recently while i was playing with my usual android development journey.
I wanted to build an android file manager,where one can browse all the files from sdcard.To bring up the pace in me at first i wanted to see all the files in sdcard.And this post is about that code snippet.
Another thing i want to ask that did you familiarize yourself with ddms? If not, that’s bad bcz i am sure of that if something goes wrong in your application you probably thinking your brains out.I tell you, ddms is big big helper when the whole world is beyond your hand.
In this post i am going to use ddms too, to help me out what’s going wrong.
So, let’s not talk too much…
File file[] = Environment.getExternalStorageDirectory().listFiles(); FilesInDir(file);
Above line is the most mandatory one but not everythig even if it seems.
public void FilesInDir(File[] file1){
int i = 0;
String filePath="";
while(i!=file1.length){
filePath = file1[i].getAbsolutePath();
i++;
Log.d(i+"", filePath);
}
}
Running that code snippet will show us all the files and directory name in ddms right after /mnt/sdcard/
But that’s not what i want.I want to see all the files.And that’s when i got a brilliant idea of recursion, hah maybe that’s why they teach us recursion, DnC and all.To see the world
So, let’s use it …
File file[] = Environment.getExternalStorageDirectory().listFiles();
recursiveFileFind(file);
public void recursiveFileFind(File[] file1){
int i = 0;
String filePath="";
while(i!=file1.length){
filePath = file1[i].getAbsolutePath();
if(file1[i].isDirectory()){
File file[] = file1[i].listFiles();
recursiveFileFind(file);
}
i++;
Log.d(i+"", filePath);
}
}
After running this we will see a "Force Close" in our emulator.
Now, what to do?Swithing to ddms perspective view we will see lots of red light:
but never fear this is where our solution is reside.
Let’s examine what is the problem:
you can see it’s a NullPointerException which is causing the problem, that means we are assigning a null reference somewhere in our code.
Closely look at the recursion:
what happens when there is only a directory left at the end of a folder but no files in it.
So that means, at that time we are assigning what’s in this below line? Which has no length!!!
File file[] = file1[i].listFiles();
So, to fix it all we need to do is check to see if the reference is null?
if(file1!=null){
while(...){
....
}
}
that should do it.
See how ddms helped to us to make a way when we can’t figure out things all by ourself.
That’s it for today, next i will try to write about Sensor bcz i recently added the Samsung Sensor Simulator in my eclipse, which is awesome.
“TextSpeak” android app using text to speech api
Today i’ve just developed another app for android using android’s own text to speech api.
Unlike the previous post i am going to share the apk file of this app and
i will provide the source code on request.
It’s a pretty simple app with a neat interface.
here is a snap of this app
I am sure you can guess what this application does.
Of course this application only support those languages that android platform supports.
These languages are
-English
-French
-German
-Italian
-Spanish
You can see in the snapshot that there is two buttons for English, one of them
is for the guys who wants to go to America and other is for England. ![]()
And i also want to thank James of http://www.jameselsey.co.uk/blogs/techblog/
blog bcz this application is inspired from his androidsam app idea.
Download the app: TextSpeak
Download source code: please contact me.
mediaviewer android app
Hello everyone.Today i am going to share my first android app that i built recently.
I call it MediaViewer.
The app is very simple.All it does is seek to see if you have any audio,video or photo in your phone, and represent them nicely in three gallery.One for images,one audios and other is for videos.
Here are some of the screen shot that i have taken.
You can click on any item and it will pop up another float screen with that item.
Also you can go to next item by clicking on top of the float screen.But not for video of course. ![]()
Oh, there is small button at the end of the screen if you want to contact me.
This application will be under development even though I’ve shown to you.
There are tons of idea pouring into my head and i will try to implement them, so in a way you can say that this app is the 1.0 version of MediaViewer.I will not publish it’s source code now since it has lot of things to update.When the update is done i will provide the source code.Till then if you want to test the app for yourself please contact me.
If you have any query about anything please do comment.I’d be delighted to know.
Download app: contact me
starting with android gps
Hello everyone, it’s been a while since my last post.It’s bcz i’ve been too lazy last few weeks figuring out what to do or what not.Though it’s not bcz of me it’s bcz my last semester exam is nearby and i have so much to do and so much to learn,Do you know the feeling when you are too excited to do lot more than you are thinking and you can not do anything at all, well i am in that situation right now.Let’s hope nothing goes wrong.
So, today i am going talk about android gps.
I am not going to dig into the theory behind android gps,rather i will try to show how you can begin development with android gps.
At first download this simple project so that you can understand what am i mockering.
WhereAmI
Open the projects code, at first, let’s see what happening in onCreate method
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
There may be different types of location services available in your device, to access those service we need a manager LocationManager. In this portion of the code We are getting the handle of LOCATION_SERVICE to manager, that is LocationManager.
String provider = LocationManager.GPS_PROVIDER;
Location location =
locationManager.getLastKnownLocation(provider);
Now that, we have the handler, we try to see current location by GPS service of that device,(you can also access other services using other providers (only if that’s available on your device)). Since we have the GPS_PROVIDER, now all we have to do is calling some method to see what gps is providing for us.Here we are trying to get the last known location.
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
This portion of the project is most important for us since it is responsible for listening the changes made by the device’s gps.
As you can see LocationManager has a method called requestLocationUpdates(java.lang.String provider, long minTime, float
minDistance, android.location.LocationListener listener) which takes as you can guess, 4 parameter.which provider to use,minimum time before listening for changes, minimum change in distance , and the listener.
Let’s see how is that listener is implemented:
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
here we have 4 methods but what we need for this project is onLocationChanged(Location location) and onProviderDisabled(String provider).
Every-time device changes it’s location, listener will fire the onLocationChanged(Location location) method with providing the location.
now remain only is updateWithNewLocation(location) which tells our UI to update with the location.
myLocationText.setText("Your Current Position is:\n" +
latLongString);
Before you run this project you should do a simple modification in your manifest file.
add <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”/> in your manifest. Use android.permission.ACCESS_COARSE_LOCATION if you are going to use LocationManager.NETWORK_PROVIDER.
And that’s it,wait, don’t run it right-away, we have a little housework to do.Now the Q is how the heck emulator is going to fetch the location, well that’s when mock gps comes in. It will mock you with gps location
, well not you, i mean emulator.
Fire up your emulator, after loading the emulator open your eclipse ide and go to ddms perspective view, you can see lot’s of thing happening in here. Find the emulator control.
now, i have provided a kml file with this project which stores some places location with their latitude and longitude.from emulator control’s kml “load KML” and locate the kml file.
Now run the project, after being initiated it will not show you anything bcz gps is not reading anything till now.Run the kml file from emulator control and voila, you are up and running.Isn’t it cool, you are moving from one place another without
being moved for an inch from your computer.I think that’s awesome.:)
Thanks everybody, next i will try to post something about android ndk(takes whole lot of pain only for configuring!!!) or
maybe else till then “HAVE A GOOD PROGRAMMING”
android startActivity and startActivityForResult
In my previous tutorial I have talked a little bit about intent. So we have our intention to do something either explicitly or implicitly now it’s time to start those intent. And we do this via startActivity() or startActivityForResult() but why do we have two kind of method for this.
As name suggest startAcitvity will only take you there where you wanna go without worrying about getting any result from child activity to parent activity.
It’s real classic when you have a sequence activity to go through, like filling some information in every activity and that’s it.
What if you want an activity that uses information from other activity or may be other application. In that case you need more than just startActivity(). And that’s when comes startAcitvityForResult().
So it start another activity from your activity and it expect to get some data from child activity and return that to parent activity.
Let’s see some example:
final Bundle bundle = new Bundle();
al.add(1,un.getText().toString());
bundle.putStringArrayList("Q1", al);
Intent intent=new Intent(PageOne.this,PageTwo.class);
intent.putExtras(bundle);
startActivity(intent);
In this case I just wanna go from page one to page two and I don’t expect to get something from page two but I want page two to receive some data from page one and that I have sent using intent.putExtras().Full Code: ReportGenerator
Now we will try to understand startAcitvityForResult(). using previous ContactPicker example.
If you have not downloaded it yet you can download it from:
ContactPicker
At first we should be creating an intent in our main activity that is ContentPickerTester and also create a static integer variable
public static final int PICK_CONTACT=1;
now that need to be done bcz you don’t actually know which sub activity is going to give you the result(if you are using implicit intent) so we need to somehow differentiate between sub activities so that we can take different type of action for different type of result.
Intent intent=new Intent(Intent.ACTION_PICK,
Uri.parse("content://contacts/"));
startActivityForResult() accept two parameters as it’s arguments, one is going to be the explicit or implicit intent and another is called request code which is our static variable.
startActivityForResult(intent,PICK_CONTACT);
now whenever subactivity finishes, it will return the request code you have sent, along with the data and a result code to your main activity.
Let’s look at the subactivity (ContactPicker)
In the subactivity side subactivity will finish itself and return the data to the parent whenever it gets the chance to execute the below code.
Uri outUri=Uri.parse(data.toString()+rowId);
Intent outData=new Intent();
outData.setData(outUri);
setResult(Activity.RESULT_OK,outData);
finish();
Here Activity.RESULT_OK is the result code we were talking about. Now if something goes wrong with subactivity Activity.RESULT_CANCEL will return.
I don’t know if you have noticed or not that we are not calling ContactPicker anywhere in our main activity. Well we actually calling it implicitly. See at manifest file
That in our ContactPicker activity we have something like this:
<intent-filter>
<action android:name="android.intent.action.PICK"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="content" android:path="contacts"></data>
</intent-filter>
You should also remember that when we have created an intent in our main activity we defined our action as Intent.ACTION_PICK. And of course ContactPicker has an action named android.intent.action.PICK. And also the kind of data we are looking. Android will use something called Intent Resolution to find a best fit activity and that is in our case is ContactPicker activity.So voila, startActivityForResult() will open up ur subactivity.
After choosing a contact it will return to the main activity by setting the result setResult(Activity.RESULT_OK,outData) and finishing off the subactivity.
Now all you have to do is taking care of the returned data in the main activity and that is done by
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case(PICK_CONTACT):{
if(resultCode==Activity.RESULT_OK)
{
//blah blah…
}
break;
}
}
}
And that’s it. A real simple application. Awesome, isn’t it? And plz do comment or question , that will encourage me to write more. Also if there is any mistake let me know so that I can correct myself. And “HAVE A GOOD PROGRAMMING”
android intent tutorial
Today i am going to talk about something called intent. To get more in depth knowledge about android you should have basic understanding about intent.
Intent comes with your intention. It’s pretty interesting after you really understand what this is for.
Android uses two kinds of intent:
- Implicit Intent
- Explicit Intent
Let’s see a real world example, say you want some information about intent but you don’t know where to get it but you only know you want to see information about intent. So what do you do? You will be open up your browser -> go to google -> and enter something about intent and search
Now what google will do, it will search its entire database and try to match with those that best describe your entered keywords and return it to you.
What if you knew that in my blog there is a post about intent that badly describe about intent and still you wanna see that, then you will probably enter my blog address in your browser url instead of going to google. Though it’s not a bad idea to go to google for various type of information. At least I would do that.
In first case what did you do?
You did give some data to google and google fired something at you when it found something using that data.
This will be implicit since you didn’t know where in the world has a server which reside the appropriate data in terms your given data.
In the second case you did know explicitly where can you find your data, so you explicitly told your browser to take you there.
And that is also the case for android too.
Intent intent=new Intent(Intent.ACTION_PICK,
Uri.parse("content://contacts/"));
startActivityForResult(intent,PICK_CONTACT);
is used with implicit intent. As you can see here, in creating new intent we need an action and the data that action will be performed on. Now startActivityForResult will launch the activity that uses “content://contacts/” kind of data. As for the action though you don’t know if they don’t tell you what kind of action is permitted on that application’s activity but we know in the case we are using now because Intent.ACTION_PICK is supported by android’s own contact application so this intent will launch android’s native contact application where we can pick a contact that we choose and return with the result in your activity. As with previous example here you only knew what kind of data you needed what you wanna do with that data, now android will lookup for an appropriate application that uses this kind of data and also permit the kind of action you are requesting since some application’s data will not be available to others to use. If any appropriate application is found android will start that activity and show it to you to do your work.
As of explicit:
Intent intent=new Intent(PageOne.this,PageTwo.class);
startActivity(intent);
You can easily guess that in here I’m in page one and I want to go another activity that is page two.
Here I explicitly told which activity I want to start.
Notice that I used startActivityForResult for the first one and startActivity for the second one, this may confused you a little bit, I will explain it to you later.
I think that explain not much but little bit about intent.
It will be more clear if you see some example application.
Using Implicit Intent: ContactPicker
Using Explicit Intent: ReportGenerator
or you can check it from here:
svn checkout http://reportgenerator.googlecode.com/svn/trunk/
this entire application uses explicit intent to go from one page to another.
Thank you for checking by and if you have any question or suggestion please do comment. I appreciate that very much.
“HAVE A GOOD PROGRAMMING“
Difference between interface and abstract in OOP
Now what is interface really?Interface is kind of like template.In that you tell people what standard they should follow but not telling them how to.For example.. assume you create box when people order it to you.In that case every time they order a box with telling you ”i want some box like that you made for my neighbour” then you define properties and behaviour of box yourself.After some days your workload has been so overflowed that you have to open your own company and need to recruit some worker in that company.And later you’ve to open some branches for it.Now in that case again when order comes to you ,you are not going to go to the every branch to do the job.You need to give some kind of standard to the branch manager’s or ceo whatever you call about how they should make a box.Give them some template of box where you define what a box should behave when they create it.Tell them something like this:
public interface boxTemplate{
double setWidth(double w);
void getWidth();
double setHeight(double h);
void getHeight();
double setLength(double l);
void getLength();
double getArea();
}
And then one of the branch,design a box class something like this:
public class box1 implements boxTemplate{
public double width;
public double height;
public double length;
public box1(double wd,double hg,double ln){
this.setWidth(wd);
this.setHeight(hg);
this.setLength(ln);
}
public void setWidth(double w){
this.width=w;
}
public double getWidth(){
return width;
}
public void setHeight(double h){
this.height=h;
}
public double getHeight(){
return height;
}
public void setLength(double l){
this.length=l;
}
public double getLength(){
return length;
}
public double getArea(){
return (width*height*length);
}
}
No matter how all branches want to make a box, should always follow your template .Box class design of different branches can differ from one another but since they all are implementing your boxTemplate you know that what behavior a box can behave when it’s ready no matter what it’s origin is.
Abstract:
One day somehow you get a huge order of making box but with some condition.By imagining that you can be next millioniare you accepted those condition.Now the condition was that they want box with same width and length but with red,orange,yellow,green,black,white in color and different type of height.Since it’s a big order you call your three branch manager.And give all of them a new kind of template like this:
abstract class boxNewTemplate {
public double width=22.0;
public double length=22.0;
boxNewTemplate()
{
this.setWidth(this.width);
this.setLength(this.length);
}
public void setWidth(double w){
this.width=w;
}
public double getWidth(){
return width;
}
public void setLength(double l){
this.length=l;
}
public double getLength(){
return length;
}
abstract void setHeight(double h);
abstract double getHeight();
abstract void setColor(int colorCode);
abstract double getArea();
}
And then tell one of them to make boxes where half of them should be red and half orange and you also told the same to others for making other colors.After that one of them create a box class like this:
public class box2 extends boxNewTemplate{
static final int RED=1;
static final int ORANGE=2;
public double height;
public box2(double hg,int colorCode) {
super();
this.setHeight(hg);
this.setColor(colorCode);
}
public void setHeight(double h){
this.height=h;
}
public double getHeight(){
return height;
}
public double getArea(){
return (width*height*length);
}
public void setColor(int colorCode){
if(colorCode==RED){
//give the color
}else if(colorCode==ORANGE){
//give the color
}else{
//do nothing
}
}
}
So the meaning of abstract class is that you do some implementation of your own to a class but some of them you leave for others.So if someone wants to include your class in their system they just have to implement those things that you did not in that class and you do that by telling them it’s abstract.Now if a method is not implemented yet which is abstract but most of the method of that class are how they are going to know that some of this class’s mehod is not implemented yet if you do not put abstract before that class name.Think about it.
I think that explains a lot about interface and abstract.
Again what you are reading in here is the concept that i figure out myself.It can contain any or many conceptual error.If you find some,feel free to tell me about it.And also if you have any question feel free to ask.
“HAVE A GOOD PROGRAMMING“
Concept of Object in OOP
When we first try to learn java(Object Oriented Programming),we all must have a conflict with Object.To be a developer having the idea about,”what is object?” is must.You must have a basic understanding about Object.Cz ,by the time pass by you will see that all things ,if it gui or others it always end up with concept of Object.So it is really very very important to have clear concept of Object Oriented Programming.
Now when u try to understand oop the very first question comes in mind is that What is this Object means?
Object is something that has some properties.And has some behaviour that acts with those properties.I am going take an example of Box.Now a box is cube like thing.It has width,height,length.If you assume those are it’s properties then i will say finding it’s area can be considered as it’s behaviour .Again if you are still confused about behaviour now what is behaviour in plain text?Think about yourself.Can you feel your skin?… J of course you can.When it is cold what do u do?And when it is summer i don’t think you do same thing as you do at the time of winter.So i can say the behaviour of your ,change when the behaviour or properties of something other change.See deep inside this concept,the behaviour change of weather will change the body temperature property of your thus your behaviour will also change.Go back to the box.If you change any property of it,it will affect the area of it.Now you can think of as many as behaviour you can.It’s up to u.If someone told you that i want some box with different type of area and also with different type of color.Then you can add a property of color with also add one extra behaviour in it that is going to set it’s color.You can imagine anything as object.From electron to whole universe.Since you are probably not here to assume the whole world as object but to understand object in respect to programming language.What about a window or the browser you are seeing or a button?All can be imagined as object.A window has title bar, closing option,minimizing option e.t.c.When you click on minimize, it’s behaviour should be minimizing the window.What about the properties clicking on it?Clicking on it will fire a change in properties will fire to it’s corresponding behaviour.Take another example of human.The lowest distance of human eye that it can see is 25cm.Now if you are wearing a glass or your friend is,tell yourself or him what happened why are you wearing a glass?Probably the answer will be lowest distance of eye has been reduced or increased.So if i tell you lowest _distance is a property of another property (can also be considered as object itself)of human which is eye.Well sometimes creator create human’s with a defected eye or anything can happen to one’s eye.Every human has a property of eye and it can be true or false depends on ,if it can see or not.Now the behaviour of eye is to see something where it has a property of seeing something with minimum distance of 25cm.If this 25cm is changed by some another behaviour then it will fire a change in the lowest_distance thus the behaviour of eye change thus you or your friend or your neighbour wear a glass of plus or minus power.
I think that’s explain a lot what the object is.
One thing you should know that what you are reading in here is the concept that i figure out myself.It can contain any or many conceptual error.If you find some,feel free to tell me about it.And also if you have any question feel free to ask.
And “HAVE A GOOD PROGRAMMING“
beginning android with hello world
In my last post we have talked about how to configure everything to start your android development.
Now in this post i will show you how we can create a very basic “HelloWorld” application for android.
And after that we will be doing some modification on our apps.
so are you ready to go..”yeah!”.but i am not ready.just kidding
steps:
1:Do i have to tell you that “Open your eclipse”??????
i think not
then
you do what i did in my first android tutorial to create an new android project.
2:Ok, now that you’ve created a project run it as android application.
3:There you go…. you should see a virtual device saying “Hello World (probably your project name)”.
4:Now we want to change something in it.Say… “Hello saiful103a”
So how do we do that
i.go res->values and open strings.xml
ii.Now you should understand where does this “Hello World ..” was coming from
iii.Now you’d think how this sentence is accessed from main file well then open gen->R.java
you should see an inner class called string. In that method what you see compare it with the strings.xml file
then you will understand not everything but enough to start with.
iv.Oh did you change the sentence from hello world to hello saiful103a.
v.Now run it….. voila….
is it worked ????yes then we should take a coffee break …..:)
5:Now we want our text to be red
create a file named colors.xml into res->values folder
inside that paste the below code
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorOfText">#ff0000</color>
</resources>
6.Open main.xml you should see a TextView element this element decide how the text will appear
on the screen upon it’s given attribute.
since we want to change color of the text add an extra attribute
->android:textColor="@color/colorOfText"
after that textview should be seen like:
<TextView
android:textColor="@color/colorOfText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
save it….
run it……….
voila…………..
so isn’t that (i will not say awesome cz we do not yet explored it deep enough but we will be) goooooood..:)
but that’s it for today…
So .. “HAVE A GOOD PROGRAMMING”
beginning android development
Last few days i was exploring about android development.And you know what i found ,I found it is pretty interesting.You do not have to be a geek to start with android,though i first thought that but now i am starting to like it.All you have to know is basic understanding about java.Enough talking,
So let’s get started for android:
At first you need to download the android sdk.
you can have it downloaded from
http://developer.android.com/sdk/index.html
And one more thing ,i am using windows as my OS.
Download the sdk for windows.
After downloading the .zip file extract it and put your extracted folder into c:\ drive
Go into the folder and you will see a file named “SDK Manager.exe”
Double click on it.Then you should see a window for “Android SDK and AVD Manager”.
Click on available packages and expand the
https://dl-ssl.google.com/android/repository/repository.xml
link and you will see the most updated API packages available.
Select most updated packages as your API and also select samples as you can explore android more in depth and install it.It will download the API into platforms folder.And also will create folder for sample code.Now that you’ve downloaded the SDK, you have to choose which IDE you should use.Though you can code without any IDE but notepad but we don’t want any trouble ‘do we?’.Since everyone is comforting in using eclipse for android development and since it is open source so we also will use that.
If you don’t have eclipse then download it from the eclipse site.
Well i have downloaded eclipse for java.Also download the windows version.
Extract it and run your eclipse ide.
After that you need to download a plugin for android that is called Android Development Tools “ADT”.
Go to
“Help”->”Install New Software”->”Add”->Name:”ADT”,Location:”http://dl-ssl.google.com/android/eclipse/”
Under the developer tools check both DDMS and ADT.I will explain what is DDMS for later.And then install it.
Since everything is ready now we just need to integrete the sdk with eclpise so that eclipse can use the api provided by sdk and other resources.
Go to “Window”->”Preferences”->”Android”
under android locate the sdk location in your hard drive.
eclipse will do the rest for you.
Next thing you need to create a virtual device called emulator.
Go to window->Android Sdk and AVD Manger
Under virtual devices
Select ‘New‘ ,name your emulator whatever you like, select target as best available api,
give a size of the sd card if your application needs it and then ‘create avd‘.
Also you can have multiple AVD if you want.Then you can specify the emulator in which you want to run with.
And that’s it.
You are ready to go with android.
Now that you are ready
Go to your eclpise and start a new project
under Android select Android project
Do something like this:

click finish
And then will see something like this:

Right click on projeect and go to-> run as->Android application
then just wait for the magic.After appearing of your virtual mobile(emulator) click menu,app will
start automatically after awhile.
As i was saying you can use specific emulator if you want, so right click on project
got run as->run configurations, under that go target and check which AVD you want to launch.
And that’s it for today.I’ll keep update in my blog as my path of exploring android goes into deeper.
If you have any questions or any suggestions please inform me.
So “HAVE A GOOD PROGRAMMING“












last comment