Archive

Archive for the ‘android java’ Category

How to create a new Android activity

August 25th, 2009 2 comments

(Android phone – how-to/example)

The Android development paradigm introduces for the developer the “Activity”: <> During development you will find it easy to wrap-up parts of the functionality of your code into independent activities, with their own life cycle. More about activity life cycle on the Android developers website.

Easy (just start activity)
Assume you have the MainActivity, and a SecondaryActivity you want to start, this may be done in the easiest way:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName(this, SecondaryActivity.class.getName());
startActivity(intent);

Medium (pass some params as well)
Now imagine you want to pass some data to the new intent. You will achieve this using the Bundle class, to encapsulate your data. Example:

Intent intent = new Intent();
Bundle bun = new Bundle();

bun.putString(”param_string”, “the actual string”); // add two parameters: a string and a boolean
bun.putBoolean(”param_bool”, true);

intent.setClass(this, SecondaryActivity.class);
intent.putExtras(bun);
startActivity(intent);

In the SecondaryActivity, you will need to access these params. This is how:

Bundle bun = getIntent().getExtras();
String param1 = bun.getString(”param_string”);
boolean param2 = bun.getBoolean(”param_bool”);

Advanced (return some data)
So we passed some parameters to the SecondaryActivity, but let’s assume we want some results as well. From MainActivity one will pack parameters and all others like in the examples above, and than one will call SecondaryActivity as follows:

startActivityForResult(intent, R.id.secondaryactivity_finished);

where secondaryactivity_finished is just some id, that the MainActivity will be looking for in it’s onActivityResult, as follows:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
     switch(requestCode)
     {
         case R.id.secondaryactivity_finished:
         if (resultCode == RESULT_OK)
         {
         Bundle res = data.getExtras();
         String result = res.getString(”param_result”);
         }
         break;
     } // end switch
}

In onActivityResult, one simply follows the activities that returned and their error/success codes, and as in the example above may get data passed by the SecondaryActivity. In our case SecondaryActivity returned a string under the name “param_result”.

On the other side, in SecondaryActivity, one will need to pack “param_result” as follows.

private void ReturnToParent()
{
   Bundle conData = new Bundle();
   conData.putString(”param_return”, “text returned to MainActivity”);
   Intent intent = new Intent();
   intent.putExtras(conData);
   setResult(RESULT_OK, intent);
   finish();
}

Some useful default activities:
Part of the beauty of Android is that you can encapsulate other functionality/activities in your own code, just by writing a few lines of code. Below is a list of useful activities one may consider to use:

1. Writing an email

Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(”mailto:office@example.com”));
intent.putExtra(”subject”, “my subject”);
intent.putExtra(”body”, “my message”);
startActivity(intent);

2. Browse to a web-page

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(”http://www.google.com”));
startActivity(intent);

3. Write a SMS

Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(”sms://”));
intent.putExtra(”address”, “”);
intent.putExtra(”sms_body”, “my message”);
startActivity(intent);

4. Search something on Google

Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, “search this text”);
startActivity(intent);

5. Get the Wiktionary of some word

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(”http://en.wiktionary.org/wiki/” + “word”));
startActivity(intent);

6. Get the Wikipedia page of some words

String uri = “http://en.wikipedia.org/wiki/” + “my text”;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);

There are several others activities one can try, just a quick google-search will reveal useful examples and links:
- calendar, phone, map, getdirections, product/book search – here

Download Files over Internet

August 25th, 2009 No comments

(Android phone – how-to/example)

If you need to download a file on your Android from a remote site, here is one option. First it should be a good idea to compress whatever you store on the internet, thus it will transfer much faster. Given Java/Android have implemented the java.util.zip package, zip should be a very good option for your compression.
(for unzipping your files, it may be a good idea to consult the post on this topic)

You will need two packages:
import java.net.HttpURLConnection;
import java.net.URL;

URL u = new URL(url_filename);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod(”GET”);
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();

// use “in” to save the file locally

Note: for a nice status bar you may use c.getContentLength().

Note2: pay attention that not any type of file may be transferred this way; depending on the remote file type – the HTTP will parse your file, and sometimes issue parsing warnings and errors.

Categories: android java Tags:

Add Google Translate into your own code

August 24th, 2009 No comments

(Android phone – how-to/example)

As expected, Google already deployed a Google-translate wrapper for Android. You can find a sample application here.

Actually all you need to use to translate a phrase is held in Translate.java

Categories: android java Tags:

Installing assets

August 24th, 2009 No comments

(Android phone – how-to/example)

Android allows a nice feature of adding your own files in the final apk package. These files are called “assets”. For adding assets to your project you simply add your files to the “prj_name/assets” directory.

The files you add in the assets directory will be zipped in the final “apk” project, along with the executable-files and the other resources.

One has two methods to access the asset files:
a. use android.content.res.AssetManager
Note that this will limit your asset files to 1Mb, at least for Android 1.5 release.
b. use java.util.zip
This has no limitations to size, but will access all resources in the zip, so one has to filter the results.

The implementations at a glance:
a. android.content.res.AssetManager

AssetManager am = getResources().getAssets(); // get the local asset manager

InputStream is = am.open( asset ); // open the input stream for reading

while ( true ) // do the reading
{
     int count = is.read(buf, 0, MAX_BUF);
     // .. use the data as you wish
}

b. java.util.zip
Your apk file is installed in /data/app/com.name.of.package.apk
Given this location of your apk file, the unzip method is straight-forward:

ZipFile zipFile = new ZipFile(m_sZipFilename); // create the zip file

Enumeration entries = zipFile.entries(); // get the enumeration of the entries in the zip
while (entries.hasMoreElements()) // while the zip still has elements
{
     ZipEntry entry = (ZipEntry)entries.nextElement(); // get each entry at a time

     String filename = entry.getName(); // get entry name
     zipFile.getInputStream(entry); // get the input stream for the given entry – you can use this to unzip the asset
     // process the entry as you like (copy it in the
}

Some other useful methods of the ZipEntry class are:
- getSize(): Gets the uncompressed size of this ZipEntry.
- isDirectory(): Gets the uncompressed size of this ZipEntry.
- getCompressedSize(): Gets the compressed size of this ZipEntry

Categories: android java Tags: ,

Sliding drawer

July 16th, 2009 No comments

(Android phone – how-to/example)

You can integrate the cool sliding-drawer that you use all the time in Home application on Android (the small arrow on the right/bottom of the screen, that displays all the available applications).

One sliding-drawer has two components:
- the handle: most of the time a picture (the picture that you drag). Be careful not to use a big image, or text.
- the content: text, images etc

< SlidingDrawer
android:id="@+id/drawer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:handle="@+id/handle"
android:content="@+id/content"
android:orientation="horizontal">

< LinearLayout
android:id="@id/handle"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent">

< ImageView android:id="@+id/IconSlide"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="@drawable/left_48">
< /ImageView>
< /LinearLayout>

< LinearLayout
android:id="@id/content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent">

< !-- INSERT in here the content of the sliding-drawer -->

< /LinearLayout>

< /SlidingDrawer>

Code example: you may find useful to see an implementation of this in the Mezzofanti application – google code. The code is released under Apache License, ver 2.0, so you can freely use it free of charge in your own code. Consult the /layout directory.

Categories: android java Tags: