Pages

Showing posts with label hello. Show all posts
Showing posts with label hello. Show all posts

Thursday, May 12, 2016

Hello Android

Now we’re going to explore our first Android application which will be the famous Hello World application. We are going to explain the structure of an Android application and some of the basic concepts wee must understand
  1. Open Eclipse and select from the menu File>New>Android Project, you’ll see a window like this.
  2. Now there are several fields that appear here they are:
    Project Name: The Eclipse project name, the name of the folder that will hold the project files.
    Application Name:The name of the application that will appear on the phone.
    Package Name: The package name space, it sould be in the form of [abc].[xyz].
    Create Activity: the name of the basic activity class of your application. it’s optional to create.
    Min SDK Version: the minimum API level required by the application. You see in the Build Target list there is a list of the available SDK versions to use for the application and in front of each one the corresponding API level. You must ensure that you application API level is supported b the device.
  3. Press Finish then press run and choose run as Android Application, the emulator will start, wait until the main screen appears, unlock by pressing the menu button then you should see something like this

    Notice: the emulator may take a long time to boot so please be patient.
  4. Now go to the package explorer on the left bar of eclipse to your project


    folder navigate to src/[PackageName]/HelloAndroid.java this is the main activity class of your application. It should be like this:
    package mina.android.helloandroid;

    import android.app.Activity;
    import android.os.Bundle;

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

  5. We will explain what each line in this code means later but now let’s understand what each folder in our project contains.
  6. The project contains the following folders



    Folder Name

    Description

    Required

    src

    Contains all the source code (class files) for the project

    Yes

    gen

    Contains the R.java class file

    Generated automatically

    Android 1.5

    Its name changes according to the sdk version you use (1.5 here). Contains the Android API class files packed in android.jar files

    Generated automatically

    assets

    You can place any external resources (text files,images,…) in this folder. It’s much like the res file except it’s more like the file system where you put files that you want to access them as raw bytes


    no

    res

    Contains resources for the application

    Yes

    drawable

    Contains the images required for you application. You can add your own image files to this folder

    No

    Layout

    Contains the main.xml file that defines the view that construct the User Interface of the application

    No

    Values

    Contains other resources that can be used for your application such as string resources, styles or colors

    No

  7. So that was a quick look on the android project structure, in this post we will take a deeper look on the hello Android application.

Read More..

Friday, February 12, 2016

Using Alerts in Android

In a previuos post we saw how to display a popup message using Toasts. Toasts are just notification messages involving no interaction from the user.

another way to show interactive messages is to use Alerts. alerts act as MessageBox or JOptionPane in J2SE. they have buttons that can be used to take decisions.

Creating Alerts

lets check this example to create an alert and show it:
//declared as final to be able to reference it in inner class declartations of the handlers 
final AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Alert Dialog");
builder.setMessage("This is the alerts body");
builder.setIcon(android.R.drawable.ic_dialog_alert);

builder.setPositiveButton("OK", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText("You clicked Ok");
}
});

builder.setNegativeButton("Cancel", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText("You clicked Cancel");
}
});

builder.setNeutralButton("Do something", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText("Neutral Button Clicked");
AlertDialog ad=builder.create();
ad.cancel();
}
});

builder.setOnCancelListener(new OnCancelListener() {

@Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(txt.getText()+" the cancel listner invoked");
}
});



builder.show();

the previous code displays the following Alert

the code may look bulky but its very simple.
first we create an instance of AlertDialog.Builder. we use the builder object to construct the AlertDialog object.
we specify the title and the icon of the alert. then the text to display in the body of the message.
the AlertDialog can display up to three buttons:
positive button: represents the OK button.
Negative button: represents the cancel button.
Neutral button: represents a button to perform another functionality other than ok or cancel.

note that there are no restrictions on the use of the three buttons, they can perform the same functionality the difference is just in logical meaning. but the three buttons cause the Alert dialog to dismiss.

we then specify the text and the click handler of each button.
in the neatral button click handler we added the lines AlertDialog ad=builder.create(); and ad.cancel();. the firt line gets a reference to the current dialog created by the builder to provide additional functionality such as invoking cancel() method.

the cancel method raises the onCancel callbcak method.

we could have replaced the previous code with the following:
AlertDialog ad=builder.create();
ad.setMessage(message);
ad.setIcon(icon);
ad.setMessage(message);
ad.setButton(text, listener);
.
.
.

Displaying Custom Views:

alerts can display complex views rather than simple text messages. create an xml layout file called alertview.xml like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android_orientation="vertical"
android_layout_width="fill_parent"
android_layout_height="fill_parent"
android_id="@+id/toastView"
android_background="#DAAA"
>
<TextView
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_text="Hello alerts"
android_textColor="#000"
/>

<TextView
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_id="@+id/txtDate"
android_textColor="#000"
/>
<Button
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_id="@+id/btnAlert"
android_text="Click"
/>
</LinearLayout>



to display this view as the alert view we do it like this:
View bodyView=getLayoutInflater().inflate(R.layout.alertview, (ViewGroup)findViewById(R.id.toastView));


TextView txtDate=(TextView)bodyView.findViewById(R.id.txtDate);
txtDate.setText(Calendar.getInstance().getTime().toLocaleString());
Button btnAlert=(Button)bodyView.findViewById(R.id.btnAlert);
btnAlert.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView txtDate=(TextView)bodyView.findViewById(R.id.txtDate);
txtDate.setText(Calendar.getInstance().getTime().toLocaleString());
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(Calendar.getInstance().getTime().toLocaleString());
}
});
builder.setView(bodyView);
.
.
.

what is interesting in this approach is that the alert is fully interactive, by clicking the button you can change the value of any view in the alert or in the activity.

you can also set the title of hte alert to be a custom view via builder.setCustomTitle(View v) method in the same way described above.

Displaying an alert of items:

alerts can display a list of items from which the user selects from like this:
final String [] items=new String []{"Item 1","Item 2","Item 3","Item 4"};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Items alert");

builder.setItems(items, new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(items[which]);
}
});

builder.show();
this will display an alert like this:

notice that we do not have to specify any buttons because when the user clicks on any item the alert will be dismissed.

if the list items are in an Adapter we can achieve the same result using builder.setAdapter(Adapter ad,OnClickListener listner) method:
final String [] items=new String []{"Item 1","Item 2","Item 3","Item 4"};
ArrayAdapter arr=new ArrayAdapter(this, android.R.layout.select_dialog_item,items);

AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Adapter alert");

builder.setAdapter(arr, new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(items[which]);
}
});

or if the items are returned from a database in a cursor we can use
builder.setCursor(Cursor cursor, OnClickListener listner, String labelColumn)

Displaying alerts with items with choices:

we can add items to the alert with choices whether they are single choice (Radio buttons) or multiple choices (Check boxes).

to display single choice items:
final String [] items=new String []{"Item 1","Item 2","Item 3","Item 4"};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("List alert");
builder.setSingleChoiceItems(items, 0, new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(items[which]);
}
});
builder.setPositiveButton("OK", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
});
builder.show();

the second parameter of setSingleChoiceItems is an integer specifying the index of the selected item

notice that we added a postive button that when clicked dismisses the alert cause unlike the regular items list the alert wont be dismissed when an item is selected.

the builder.setSingleChoiceItems method has other overloads that can accept an Adapter or a Cursor as parameters that hold the items to be displayed

to display multiple choice items:
final String [] items=new String []{"Item 1","Item 2","Item 3","Item 4"};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("List alert");
builder.setMultiChoiceItems(items, null, new OnMultiChoiceClickListener() {

@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(txt.getText()+" "+items[which]);
}
});
builder.setPositiveButton("OK", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
});
builder.show();

the second parameter of setMultiChoiceItems is an array of boolean values specifying which items are set selected. if you want no items to be selected then set it to null, otherwise specify an array with the same length of the items with boolean values indicating which item is selected and which is not like this:
new boolean[] {true,false,...}

works in the fashion as single items choice except that the selection here is multiple.

download a demo applications on alerts from here
Read More..