How do you rate this blog

Wednesday, November 30, 2011

Creation of Simple Tabs


                Well in some cases you wouldn’t want the forms to be segregated like Personal info, professional info. Well in such cases you can use tabs feature which makes the app appear more pleasant.
This post I have created a simple tab. Create a new project and open ‘main.xml’ file under layouts. Go to the graphical designer. On the Right hand side you see a pane called outline and you can see it has liner layout by default. So change this to tabhost, a tabhost is one which have various tab. You can see there are 3 tabs under tabhost, you can retain it as per your convenience but here I have retained only 2. The layout will look as shown below.



Now go to package under src folder and create 2 classes under it called activity1 and activity2 which will be called by the main file. Now open the main java file instead of extending Activity we will change it TabActivity. Then create a new tabhost and bind it to the default tabhost pre defined in android.
TabHost th=(TabHost) findViewById(android.R.id.tabhost);
Now we need to create 2 tabs and start activities in it. This is done as shown below
Creating new tabs
TabHost.TabSpec tab1=th.newTabSpec("tab1");
TabHost.TabSpec tab2=th.newTabSpec("tab2");
Creating new intents
tab1.setIndicator("My Activity1").setContent(new Intent(this,Activity1.class));
tab2.setIndicator("My Activity2").setContent(new Intent(this,Activity2.class));
Finally adding the tabs to tabhost on which it will be shown.       
th.addTab(tab1);
th.addTab(tab2);      
The main file will look like as shown below.


 
Now go to the Activity1 file and set the content to a textview. The file will look as shown below.



Similarly create Activity2 file.
Now that we are done defining layouts, actions and binding lets define activity in android manifest file by adding the code below inside application tag after the main activity tag.
<activity android:name=".Activity1"></activity>
<activity android:name=".Activity2"></activity>
 
Now run the application and you will see a screen as shown below.



Now click on other tab My Activity2 and you will see the output screen as shown below.



Well this was a simple one will try to showcase complex scenarios in future posts :).

Some Small pot holes in Android Autobhan:


Problem using tabs in Eclipse 3.6.2 :
Well I was working on Tabs in android using Eclipse 3.6.2 well guess what it gives you an error. Well tried to see if there was any error in my environment but it was not the case then I wrote xml code instead of using the graphical designer but it was in vain. I ended spending 3-4 hours on this problem finally read in forum that tit works perfectly in 3.7.1, so I downloaded eclipse 3.7.1 and it worked perfectly fine.

Problem with Android SDK and ADT :
Finally I was happy that I manage to complete the coding of Tabs and wanted to see how it works but again hit a speed breaker L this time it was giving some error called ‘Unknown Option  --Crunch’ and it didn’t start the emulator nor does it allow you to create an apk file. Finally found that sdk was not up to date. Then I finally downloaded it and everything worked fine J.

I know these problems are small, but these can be time consuming and irritating because of which you can easily spend a day on some small problem which is not your fault. Hope it helps you people ;)

Friday, November 25, 2011

Spinner


A spinner is just like a drop down list with combo box which displays multiple items out of which a user can select one item.

In this post I have created an app which demonstrates the spinner. In order to do this, I have an array which has the list of values which need to be present in the list. On clicking one of the items I will display an alert dialog which will confirm the selection of the item.
So, first we will modify the layout. Open the ‘main.xml’ file in Layouts and remove the existing text box and add a new Large Text and add the app name to it. Then drag and drop the spinner item from the list into the layout and make its width the same as the parent’s width. The layout will finally look like the one shown below.



After this open the main java file in src folder within the package. As you can see it will just extend Activity by default but since we are using adapter we also need onItemSelectedListner.  Then it you need to implement methods like ‘ontemSelected’ and ‘onNothingSelected’ .Then we need to declare an array of string with the items of your choice or requirement.  Then create a spinner and arrayadapter which will hold the items as shown below.
Spinner spinner=(Spinner) findViewById(R.id.spinner1);
 spinner.setOnItemSelectedListener(this);
ArrayAdapter spinadapter=new ArrayAdapter(this,android.R.layout.simple_spinner_item,spinneritems);
spinadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinadapter);

Now you need to define action if the item is selected. So go to the function onItemSelected and get the item name into a string and then create an alert dialog with Done button which will display the item which has been selected by you.  The code for the same is provided below.
String items=(String) adapter.getAdapter().getItem(pos);
AlertDialog.Builder spinalert=new AlertDialog.Builder(SpinnerDemoActivity.this);
spinalert.setTitle("Spinner Demo - Alert");
spinalert.setMessage("You clicked on :"+items);
spinalert.setPositiveButton("Done", null);
spinalert.show();

Do the same for onNothingSelected where you just create an alert dialog with some default message.
The java file will look like in the image shown below.
 


Now right click on the project and say run as android application, the first output screen that you get is as shown below.



No click on the dropdown and you get a list of combo boxes as shown below.



Click on anyone of them and you get an alert dialog which will display the item which you have selected.


Saturday, November 19, 2011

ListViews with Alert Dialog


In this post I have used both List views as well as Alert Dialog components of android. So what does a list view mean? A list view in simple words is a collection of scrollable items displayed as a list. An alert dialog is a small window which opens up based on some selection usually to alert the user on some activity.
                
      In order to use both of them the flow is as follows, I have created an array which has names of cars which will be displayed in the list view. When the user clicks on the list item an alert dialog will come up which will display “You have selected <car_name>”.
So lets get on with the coding part, first open the main.xml file. Delete the existing textbox and add a new large text box and give the name of the app in it. Then add the list view component into the layout. The Main.xml file will look as follows.



Now that we are done with the layout, we have to add functionality for the same. So go to the mainclass java file, as you see that the class already extends Activity so lets change this to ListActivity. We will then remove the setContentView function which is already present since we will using the one of the default layouts for the listview called android.R.layout.simple_list_item_1 in the array adapter. Then create an array of string which will have the contents of the list. Then create a new ArrayAdapter called mylist which will be for the current context , layout and the array defined previously. So the code will look like below
super.onCreate(savedInstanceState);
String[] actionList=new String[]{"Ferrari","BMW","Porche"};       
ArrayAdapter<String> mylist=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,actionList);
setListAdapter(mylist);

Now  that we have defined the listview we will make alert dialog box to apper when the user clicks on the listview items.
So override the function onListItemClick function and obtain the item which has been selected to a string as shown below.
protected void onListItemClick(ListView l, View v, int position, long id) {
String pos=(String) getListAdapter().getItem(position);
Then create an action dialog as shown below.
AlertDialog.Builder alerter=new AlertDialog.Builder(ListViewDemoActivity.this);
Then set the title and message as shown below.
alerter.setTitle("AlertDilog Demo");
alerter.setMessage("You have selected :" +pos );
Now we have to declare a button which can be associated to any task which you would like to perform, here I have set only one called OK and no action has been set for this, so when the user clicks on OK it will take him back to the list view and no action will be performed.
alerter.setPositiveButton("OK", null);
alerter.show();}
The code will be like in the screen shot shown below



Now that we are done right click on the project and say RunAs android application, once it runs, you will get a screen shot as shown in the image below.



Click on any of the list view items, here I have clicked on Ferrari and you will get a dialog box as shown below.



Once you click OK button it will again take you back to the main screen. Hope you were able to get what has been explained.

Monday, November 7, 2011

Menus in Android – Part2: Context Menu


In the previous post we learnt what an Option Menu was, in this post we will get to know how to create Context Menu. This menu appears only when a user holds the screen for a considerable period of time.
                To create a Context menu, I have created a button which has been registered for context menu. When you click on this button a context menu opens up which will have 2 options called ‘Go to Action1’ and ‘Go to Action2’.  Based on the user selection one of the options, the action1 or action 2 will start.

So Create a layout Main.xml and add a Textview on top which will show the application name. Then Create a button which we will use for invoking the context menu. The main.xml file will look like as shown below.



Create 2 xml files in the layouts which will be for Action1 and Action2. These will have a textview which will have Action1/Action2. Then there will be a button which will take it back to the main screen. Given below is how Action1 will look like, Action2 can be created on similar lines.



Then open the main java file under src folder. First Create a button and bind it to the id. Then register this button for context menu in the view as shown below.
Button B1=(Button) findViewById(R.id.button1);
this.registerForContextMenu(B1);
Once you do this you need to populate all the items in the context menu. This can be achieved by the one below

public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
                                super.onCreateContextMenu(menu, v, menuInfo);
                                menu.setHeaderTitle("Context Menu Options");
                                menu.add(0,1,0,"Go To Action1");
                                menu.add(0,2,0,"Go To Action2");
                }
After you have added all the menu items, you need to associate activity with each of the items, this can be achieved by the code below –
public boolean onContextItemSelected(MenuItem item) {
                                switch(item.getItemId()){
                                                                case 0:  Intent Action1=new Intent(this,Action1.class);
                                                                                                this.startActivity(Action1);
                                                                                                break;
                                                                case 1:  Intent Action2=new Intent(this,Action2.class);
                                                                                                this.startActivity(Action2);
                                                                                                break;                  
                                                                default:break;
                                }
                                return true;
                }
At the end the file will look as shown below –



As you can see we have associated Activity with each of the menu item. So we need to create 2 class called Activity1 and Activity2 which will have code which returns back to the main screen as shown below.



Now Right click on the project and say Run As – Android Application. When you touch and hold on the button, the context menu should appear as shown in the image below.



Click on Action1 and it should take you to the screen as shown below and when you click on the ‘Go back to Main Screen’ then it should take you back to the original screen.


Android Blog - Simple Radio Button


A Radio button is similar to check boxes where in it has two states checked or unchecked.  So what is the difference between a radio button and a checkbox, well it’s simple in case of checkbox user can uncheck it which is not possible in case of radio buttons. Hence when you use radio buttons use it in Radio Groups where in at any time only one option can be selected.

                In this post I have created 2 radio buttons called ‘India’ and ‘New Zealand’, a Button called ‘Done’. Once a user clicks on the ’Done’ button it should show ‘You Selected -<Country Name>’.
Create a project and add the following –
Main.xml - Open the main.xml file in layout folder. Remove the default textview. Add a Large Text and add the app name to this. Then drag a medium text and have a label ‘Select Country’. Then add 2 radio buttons and call them India and New Zealand. Add a button and label it ‘Done’. On clicking the button you need to display the country which has been selected, so include a text view in it which you will set using java code.
The layout should like the one below –



RadioButton_Activity.Java – Open the class file RadioButton_Activity.Java in src folder. Here you need to declare and bind the Radio Button which you have created in the Main.xml file. Hence you need to add code
R1=(RadioButton) findViewById(R.id.radioButton1);       
R2=(RadioButton) findViewById(R.id.radioButton2);
Then you need to add a button called ‘Done’ and a listener which will set the text to ‘You Selected -<Country Name>’ as shown in the  code below

Done=(Button) findViewById(R.id.button1);
        tv=(TextView) findViewById(R.id.textView3);
        Done.setOnClickListener(new View.OnClickListener() {
                                               
                                                @Override
                                                public void onClick(View V) {
                                                                if(R1.isChecked()){
                                                                                tv.setText("You Selected - "+R1.getText());
                                                                }
                                                                if(R2.isChecked()){
                                                                                tv.setText("You Selected - "+R2.getText());
                                                                }
                                                }
                                });
The code will finally look like the one below 



And, we are done with coding, simple wasn’t it. Now lets see if it works, right click on the project and click on run as android application. The initial screen which you get will be as shown in the below



Now click on a country and click on the Done button, in this case I have clicked on India and the result is as shown below.



Well that was easy, I will tell how to use radio groups in my next post.