Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Install Android Development Tools (ADT) on Ubuntu

Android Development Tools or ADT is a plugin for eclipse IDE that makes our life easier when developing Android applications. I think this is the reason why we highly recommend using Eclipse IDE during Android development. See easy to understand and great ADT descriptionon this link. This post covers only how I was able to install ADT on Ubuntu 11.10. Click here if you want to view the complete links on how I completed installing  my Android Development Environment on Ubuntu.

I made it work by doing the following simple steps:

First Part:

1. Open Eclipse

2. Go to Help > Install New Software

3. On the pop up,  click Available Software Sites

4. Tick http://download.eclipse.org/releases/helios

5. Click OK

6. On the “Work With” drop down, choose http://download.eclipse.org/releases/helios

7. Please wait while it's Pending

Click to enlarge.

8. Then it will list the available tools

9. On the list, tick Mobile and Device Development

10. Click Next > Next > Read and Accept the Terms > Finish

11. Wait for the software to be installed
Click to enlarge.

12. Click OK if security warning appears 

13. Restart Eclicpse


Second Part: When Eclipse was restarted.

1. Go to help > install new software

2. On the pop up Click Add

3. On the prompt, enter:

Name: Android ADT
Location: http://dl-ssl.google.com/android/eclipse/

4. Please wait for the Developer Tools to load while it is Pending

5. Tick the Developer Tools then click the "Next" button

6. Please wait while it loads

7. Click Next > Read and Accept the terms > Finish

8. Please wait while it install the software

9. Click OK if security warning appears

10. Restart Eclicpse

Hope this helps! Sorry for lack of screen shots (I actually hate doing lots of screen shots), I want you to believe in yourself that you can follow word instructions here even withoutpictures or screen shots, but if you have any questions or suggestions, leave your comment on the comment section below. Thanks!
READMORE
 

Install Android Development Environment on Ubuntu


Recently, I wanted to use Ubuntu 11.10 instead of Windows 7 for my Android applicationdevelopment. So far, I'm liking Ubuntu a lot, it is super fast, free, has great interface and animation, easy to learn and has lots of free applications that suits my needs as a computer user and software developer. Now I'm thinking to be more of an Ubuntu Linux user than Windows user haha!

What is Ubuntu?
Ubuntu is a kind Linux Operating System that powers millions of net-books, desktops and servers all over the world. Using this amazing operating system is absolutely free of charge, and always will be. It is created and actively developed by the best open source experts from all over the world. I think this is the only open source operating system that looks great. I find it stylish, beautiful and fast.

Anyway, enough of describing Ubuntu, this post is about Installing Android development environment in Ubuntu 11.10. Here are the links on how I was able to successfully install my Android Development Environment on Ubuntu 11.10, these guides should be followed in order:

1. Install JDK 7 on ubuntu 11.10


As a proof, I was able to run a HelloAndroid Application with the device emulator, here's ascreen shot:

Click to enlarge.
Enjoy!
READMORE
 

Android SharedPreferences Example


Android SharedPreferences store private primitive data in key-value pairs. The data saved using SharedPreferences will still be available in the device even if your application is killed. Types of data that can be saved are booleans, floats, ints, longs, and strings. One use of Android SharedPreferences is to store data that can be used in different activity of yourapplication.

Here's the code:

package com.example.SharedPreferencesExample;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class SharedPreferencesExampleActivity extends Activity {
    /** Called when the activity is first created. */
   SharedPreferences settings;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        try {
         //our edit text/text box where the name will be entered
         final EditText name_edit_text = (EditText) this.findViewById(R.id.NameTxt);
       
         //getSharedPreferences() - Use this if you need multiple preferences files identified by name, 
         //which you specify with the first parameter.
         //our preference name will be codeofaninja_shared_pref
         settings = getSharedPreferences("codeofaninja_shared_pref", 0);
       
            View.OnClickListener handler = new View.OnClickListener(){
                public void onClick(View v) {
                    switch (v.getId()) {

                        case R.id.SaveBtn:
                           //get entered value and set to a variable
                           String name_input = name_edit_text.getText().toString();
                           
                            //empty edit text field
                           name_edit_text.setText("");
                         
                           //SAVE shared pref value
                            SharedPreferences.Editor editor = settings.edit();
                            editor.putString("name", name_input);
                            editor.commit();
                           
                            //show button after saving
                            Toast.makeText(SharedPreferencesExampleActivity.this,
                                       "You entered: " + name_input,
                                       Toast.LENGTH_SHORT)
                                       .show();
                           
                            break;
                           
                        case R.id.ShowSavedBtn:

                           //RETRIEVE/load the saved shared pref value
                           String name = settings.getString("name", null);
                           Toast.makeText(SharedPreferencesExampleActivity.this,
                                       "Saved Name is: " + name,
                                       Toast.LENGTH_LONG)
                                       .show();
                            break;
                    }
                }
            };
               
            //we will set the listeners
            findViewById(R.id.SaveBtn).setOnClickListener(handler);
            findViewById(R.id.ShowSavedBtn).setOnClickListener(handler);
               
        }catch(Exception e){
             Log.e("SharedPreferences Example", e.toString());
        }
           
    }
}

Our XML Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
   
   <EditText
   android:layout_width="198dp"
   android:layout_height="50sp"
   android:text=""
   android:id="@+id/NameTxt"
   android:singleLine="true">
   </EditText>
 

    <Button
       android:id="@+id/SaveBtn"
       android:layout_width="198dp"
       android:layout_height="wrap_content"
       android:text="Save Name" >

    </Button>
   
    <Button
       android:id="@+id/ShowSavedBtn"
       android:layout_width="198dp"
       android:layout_height="wrap_content"
       android:layout_alignRight="@+id/SaveBtn"
       android:text="Show Saved Name" >

    </Button>
   
</LinearLayout>

When you run this code:

Entered something on the edit text:

Tapping "Save Name" button will clear the edit text and save the value on the SharedPreferences

Tapping "Show Saved Name" button, it will retrieve the saved value:

Just in case you want to download the code:
READMORE
 

How To View a Webpage Inside Your Android App

Hi there! Today I'm gonna share how to view a website or webpage to your Android apllication. You'll be able to view webpages from the internet or from the storage of your Adroid device such as your sdcard. This is useful if you want your app not to open a webbrowser for web links. It is like, the browser is inside or embedded your Android application.

How To View a Webpage Inside Your Android App
Android WebView


The following code will enable you to view this blog on your Android Application. This code uses the Android WebView class which is also an extension of Android's View class.
package com.example.yourproject;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class YourProject extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);

// Let's display the progress in the activity title bar, like the
// browser app does.
getWindow().requestFeature(Window.FEATURE_PROGRESS);

WebView webview = new WebView(this);
setContentView(webview);

webview.getSettings().setJavaScriptEnabled(true);

final Activity activity = this;
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
}
});

webview.setWebViewClient(new WebViewClient() {

public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//Users will be notified in case there's an error (i.e. no internet connection)
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
//This will load the webpage that we want to see
webview.loadUrl("http://codeofaninja.blogspot.com/");

}
}

If you want to view an html page from your sdcard, you can change the url for example "file:///sdcard/YourProject/index.html". Well that's it. Thanks for reading. :)
READMORE
 

Android Download File With Progress Bar

Hi guys! Today we are going to do a script that will show an Android progress bar whiledownloading a file. A progress bar looks good for the user to be notified about the progress of the download.

We will easily use a UI thread with Android AsyncTask. In other terms, we will use a subclassto handle our downloader thread. 

Android Download File With Progress Bar
Our output is something like this

DownloadFile.java

package com.example.downloadfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

public class DownloadFile extends Activity {
   
    public static final String LOG_TAG = "Android Downloader by The Code Of A Ninja";
   
    //initialize our progress dialog/bar
    private ProgressDialog mProgressDialog;
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
   
    //initialize root directory
    File rootDir = Environment.getExternalStorageDirectory();
   
    //defining file name and url
    public String fileName = "codeofaninja.jpg";
    public String fileURL = "https://lh4.googleusercontent.com/-HiJOyupc-tQ/TgnDx1_HDzI/AAAAAAAAAWo/DEeOtnRimak/s800/DSC04158.JPG";
   
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //setting some display
        setContentView(R.layout.main);
        TextView tv = new TextView(this);
        tv.setText("Android Download File With Progress Bar");
   
        //making sure the download directory exists
        checkAndCreateDirectory("/my_downloads");
       
        //executing the asynctask
        new DownloadFileAsync().execute(fileURL);
    }
 
    //this is our download file asynctask
    class DownloadFileAsync extends AsyncTask<StringString, String> {
       
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

       
        @Override
        protected String doInBackground(String... aurl) {

            try {
                //connecting to url
                URL u = new URL(fileURL);
                HttpURLConnection c = (HttpURLConnection)u.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
               
                //lenghtOfFile is used for calculating download progress
                int lenghtOfFile = c.getContentLength();
               
                //this is where the file will be seen after the download
                FileOutputStream f = new FileOutputStream(newFile(rootDir + "/my_downloads/", fileName));
                //file input is from the url
                InputStream in = c.getInputStream();

                //here's the download code
                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;
               
                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; //total = total + len1
                    publishProgress("" +(int)((total*100)/lenghtOfFile));
                    f.write(buffer, 0, len1);
                }
                f.close();
               
            } catch (Exception e) {
                Log.d(LOG_TAG, e.getMessage());
            }
           
            return null;
        }
       
        protected void onProgressUpdate(String... progress) {
             Log.d(LOG_TAG,progress[0]);
             mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) {
            //dismiss the dialog after the file was downloaded
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
    }
   
    //function to verify if directory exists
    public void checkAndCreateDirectory(String dirName){
        File new_dir = new File( rootDir + dirName );
        if( !new_dir.exists() ){
            new_dir.mkdirs();
        }
    }
   
    //our progress bar settings
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading file...");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }
}

And for the AndroidManifest.xml, include the INTERNET and WRITE_EXTERNAL_STORAGE permissions.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.downloadfile"
     android:versionCode="1"
     android:versionName="1.0">
     
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     
    <uses-sdk android:minSdkVersion="4" />

    <application android:icon="@drawable/icon"android:label="@string/app_name">
        <activity android:name=".DownloadFile"
                 android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>
</manifest>

That's it! :)
READMORE
 

Getting Android Device Current Date and Time

Recently, my Android App needed to get the value of the device, or system, date and time. I found two ways of doing it. They are by using the Calendar class and SimpleDateFormat class. So let's see what method will be more simple for you.


Getting Android Device Current Date and Time
What time is it?

tv = (TextView) this.findViewById(R.id.thetext);

//using Calendar class
Calendar ci = Calendar.getInstance();

String CiDateTime = "" + ci.get(Calendar.YEAR) + "-" +
(ci.get(Calendar.MONTH) + 1) + "-" +
ci.get(Calendar.DAY_OF_MONTH) + " " +
ci.get(Calendar.HOUR) + ":" +
ci.get(Calendar.MINUTE) + ":" +
ci.get(Calendar.SECOND);

tv.append( CiDateTime + "\n" );

//using SimpleDateFormat class
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
String newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));

tv.append(newtime);

I have the output of the code above as:
2011-6-9 7:0:56
2011-06-09 19:00:56

As you can see, using the calendar class seemed like it require us to code more. Also, I think I found a bug. My device calendar settings are correct. It is month of June, so ci.get(Calendar.MONTH) must return "6" but it returns "5" so I had to add "1" to make the output correct.


In my case, I used the SimpleDateFormat class since I don't really have to synchronize it. It is easy to format - you can just use its time pattern strings (in our example "yyyy-MM-dd HH:mm:ss"). But please be aware that it was said in the docs that SimpleDateFormat is NOT thread safe when it comes to Synchronization.

For more info and resources:
http://developer.android.com/reference/java/util/Calendar.html
http://developer.android.com/reference/java/text/SimpleDateFormat.html
READMORE
 

Leave Me a Comment Below. Thanks :)