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

Wednesday, 4 November 2015

Dialog box confirmation before exit android app.

Leave a Comment
This is the code to trigger dialog box before you exit the application in android.


  private void ShowMessageExit(String Message){  
     new AlertDialog.Builder(this)  
         .setMessage(Message)  
         .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {  
           public void onClick(DialogInterface dialog, int which) {  
             android.os.Process.killProcess(android.os.Process.myPid());  
             System.exit(0);  
           }  
         })  
         .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {  
           public void onClick(DialogInterface dialog, int which) {  
             // do nothing  
           }  
         })  
         .setIcon(android.R.drawable.ic_dialog_alert)  
         .show();  
   }  



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Saturday, 3 October 2015

Android on click list item open in dialog

Leave a Comment
Today i want to show how to open list item in dialog.

For this tutorial you need to have :-

  1. Dialog design view_item.xml
  2. MyDialogFragment.java class
  3. OnClick Event to call dialog.
  4. Announcement.java Class
  5. AnnouncementHelper Class
  6. OnCreateView Method

view_item.xml


  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent" >  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="match_parent"  
   android:orientation="horizontal"  
   android:padding="5dip"  
   android:id="@+id/Announcement"  
   android:transitionGroup="false">  
   <ImageView android:id="@+id/icon" android:layout_width="wrap_content"  
     android:layout_height="wrap_content" android:layout_alignParentTop="true"  
     android:layout_alignParentBottom="true" android:layout_marginRight="4dip"  
     android:src="@drawable/icon" />  
   <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"  
     android:orientation="vertical">  
     <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content"  
       android:layout_weight="1" android:gravity="center_vertical" android:textStyle="bold"  
       android:singleLine="false" android:ellipsize="end" />  
     <TextView android:id="@+id/datepublish" android:layout_width="wrap_content"  
       android:layout_height="wrap_content" android:layout_weight="1"  
       android:gravity="center_vertical" android:singleLine="false" android:ellipsize="end" />  
     <TextView android:id="@+id/summarycontent" android:layout_width="wrap_content"  
       android:layout_height="wrap_content" android:layout_weight="1"  
       android:gravity="center_vertical" android:singleLine="false" android:ellipsize="end" />  
     <Button android:layout_width="fill_parent" android:layout_height="wrap_content"  
       android:text="Close Announcement"  
       android:id="@+id/button"  
       android:layout_gravity="fill_horizontal"  
       />  
   </LinearLayout>  
 </LinearLayout>  
 </RelativeLayout>  

Read More...

how to select date time using calendar android

Leave a Comment
This tutorial shows how to set date time in android app when you click on the textbox.

Note : This example using Andorid Studio to create project. Im using Sample Blank Activity with Fragment sample.

Step By Step 

  1. Add One EditText on the fragment
  2. Create DateTimeFragment.java class
  3. Copy Paste DateTimeFragment.java class below.
  4. Override onViewCreated event from fragment
  5. Done.

Full Source Code of MainActivity class + Fragment / placeholder class

  package com.test.selectdatetime;  
 import android.app.Dialog;  
 import android.content.Context;  
 import android.support.annotation.Nullable;  
 import android.support.v4.app.DialogFragment;  
 import android.support.v7.app.ActionBarActivity;  
 import android.support.v4.app.Fragment;  
 import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.Menu;  
 import android.view.MenuItem;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import android.view.inputmethod.InputMethodManager;  
 import android.widget.EditText;  
 public class MainActivity extends ActionBarActivity {  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     if (savedInstanceState == null) {  
       getSupportFragmentManager().beginTransaction()  
           .add(R.id.container, new PlaceholderFragment())  
           .commit();  
     }  
Read More...

How to create multiple tab with different fragment / view - Android app

Leave a Comment
Most beginner android developer wonder how to create different fragment for each tab in their android app. Please follow this tutorial to create basic android app with 3 tab before continue with this tutorial. ( http://swengineercode.blogspot.com/2015/05/how-to-create-multiple-tab-on-android.html )

This example using android studio. Kindly download the studio here ( https://developer.android.com/sdk/index.html )

Step By Step 

1. Open "Three tab example" android app. ( Refer this tutorial to create "Three tab example" project )
2. Create New Fragment
























Read More...

Friday, 2 October 2015

How to create multiple tab on android app

Leave a Comment
This tutorial to show how to create multiple tab on Android App.

This example using android studio. Kindly download the studio here ( https://developer.android.com/sdk/index.html )

Step By Step

1. Open Android Studio.
2. Choose Start New Android Studio Project




















Read More...

Friday, 14 February 2014

Android Splitting the Tab

Leave a Comment
In this tutorial, we will move our ListView onto one tab and our form onto a separate tab of a TabView. Along the way, we will also arrange to update our form based on a ListView selections or clicks, even though the Save button will still only add new restaurants to our list.

Note : Please follow the Android Tutorial Post Here Before You Step On This Post.

Rework the Layout

First, we need to change our layout around, to introduce the tabs and split our UI between a list tab and a details tab.

This involves:
  • Removing the RelativeLayout and the layout attributes leveraging it,as that was how we had the list and form on a single screen
  • Add in a TabHost, TabWidget, and FrameLayout, the latter of which is parent to the list and details
To accomplish this, replace your current LunchList/res/layout/main.xml with the following:

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
  <LinearLayout
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
    <TabWidget android:id="@android:id/tabs"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
    <FrameLayout android:id="@android:id/tabcontent"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
      <ListView android:id="@+id/restaurants"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>
      <TableLayout android:id="@+id/details"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:stretchColumns="1"
      android:paddingTop="4dip">
        <TableRow>
          <TextView android:text="Name:" />
          <EditText android:id="@+id/name" />
        </TableRow>
        <TableRow>
          <TextView android:text="Address:" />
          <EditText android:id="@+id/addr" />
        </TableRow>
        <TableRow>
          <TextView android:text="Type:" />
          <RadioGroup android:id="@+id/types">
            <RadioButton android:id="@+id/take_out"
            android:text="Take-Out"/>
            <RadioButton android:id="@+id/sit_down"
            android:text="Sit-Down"/>
            <RadioButton android:id="@+id/delivery"
            android:text="Delivery"/>
          </RadioGroup>
        </TableRow>
        <Button android:id="@+id/save"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Save"/>
      </TableLayout>
    </FrameLayout>
  </LinearLayout>
</TabHost>

Wire In the Tabs

Next, we need to modify the LunchList itself, so it is a TabActivity (rather than a plain Activity) and teaches the TabHost how to use our FrameLayout contents for the individual tab panes.To do this:
  1. Add imports to LunchList for android.app.TabActivity and android.widget.TabHost 
  2. Make LunchList extend TabActivity 
  3. Obtain 32px high icons from some source to use for the list and details tab icons, place them in LunchList/res/drawable as list.png and restaurant.png, respectively
  4. Add the following code to the end of your onCreate() method:
        TabHost.TabSpec spec = getTabHost().newTabSpec("tag1");
        
        spec.setContent(R.id.restaurants);
        spec.setIndicator("List", getResources().getDrawable(R.drawable.list));
        
        getTabHost().addTab(spec);
        
        spec = getTabHost().newTabSpec("tag2");
        
        spec.setContent(R.id.details);
        spec.setIndicator("Details",
                getResources().getDrawable(R.drawable.restaurant));
        getTabHost().addTab(spec);
        getTabHost().setCurrentTab(0);
        

At this point, you can recompile and reinstall the application and try it out.

You should see a two-tab UI like this:



Get Control On List Events

Next, we need to detect when the user clicks on one of our restaurants in the list, so we can update our detail form with that information.

First, add an import for android.widget.AdapterView to LunchList. Then, create an  AdapterView.OnItemClickListener named onListClick:

private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            Restaurant r = model.get(position);
            name.setText(r.getName());
            address.setText(r.getAddress());
            if (r.getType().equals("sit_down")) {
                types.check(R.id.sit_down);
            } else if (r.getType().equals("take_out")) {
                types.check(R.id.take_out);
            } else {
                types.check(R.id.delivery);
            }
            getTabHost().setCurrentTab(1);
        }
    };


Update Our Restaurant Form On Clicks

Next, now that we have control in a list item click, we need to actually find the associated restaurant and update our details form.

To do this, you need to do two things. First, move the name, address, and types variables into data members and populate them in the activity's onCreate(). Our current code has them as local variables in the onSave listener object's onClick() method.

So, you should have some data members like:

    EditText name = null;
    EditText address = null;
    RadioGroup types = null;


And some code after the call to setContentView() in onCreate() like:

        name = (EditText) findViewById(R.id.name);
        address = (EditText) findViewById(R.id.addr);
        types = (RadioGroup) findViewById(R.id.types);


Switch Tabs On Clicks

Finally, we want to switch to the detail form when the user clicks a restaurant in the list.
This is just one extra line of code, in the onItemClick() method of our onListClick listener object:

getTabHost().setCurrentTab(1);


Full Code

import java.util.ArrayList;
import java.util.List;

import android.app.TabActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;

public class Main extends TabActivity {

    List<Restaurant> model = new ArrayList<Restaurant>();
    RestaurantAdapter adapter = null;
    EditText name = null;
    EditText address = null;
    RadioGroup types = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (EditText) findViewById(R.id.name);
        address = (EditText) findViewById(R.id.addr);
        types = (RadioGroup) findViewById(R.id.types);
        Button save = (Button) findViewById(R.id.save);
        save.setOnClickListener(onSave);
        ListView list = (ListView) findViewById(R.id.restaurants);
        adapter = new RestaurantAdapter();
        list.setAdapter(adapter);
        TabHost.TabSpec spec = getTabHost().newTabSpec("tag1");
       
        spec.setContent(R.id.restaurants);
        spec.setIndicator("List", getResources().getDrawable(R.drawable.list));
       
        getTabHost().addTab(spec);
       
        spec = getTabHost().newTabSpec("tag2");
       
        spec.setContent(R.id.details);
        spec.setIndicator("Details",
                getResources().getDrawable(R.drawable.restaurant));
        getTabHost().addTab(spec);
        getTabHost().setCurrentTab(0);
       
        list.setOnItemClickListener(onListClick);
    }

    private View.OnClickListener onSave = new View.OnClickListener() {
        public void onClick(View v) {
            Restaurant r = new Restaurant();
            r.setName(name.getText().toString());
            r.setAddress(address.getText().toString());
            switch (types.getCheckedRadioButtonId()) {
            case R.id.sit_down:
                r.setType("sit_down");
                break;
            case R.id.take_out:
                r.setType("take_out");
                break;
            case R.id.delivery:
                r.setType("delivery");
                break;
            }
            adapter.add(r);
        }
    };

    private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            Restaurant r = model.get(position);
            name.setText(r.getName());
            address.setText(r.getAddress());
            if (r.getType().equals("sit_down")) {
                types.check(R.id.sit_down);
            } else if (r.getType().equals("take_out")) {
                types.check(R.id.take_out);
            } else {
                types.check(R.id.delivery);
            }
            getTabHost().setCurrentTab(1);
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public class RestaurantAdapter extends ArrayAdapter<Restaurant> {
        RestaurantAdapter() {
            super(Main.this, android.R.layout.simple_list_item_1, model);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            RestaurantHolder holder = null;
            if (row == null) {
                LayoutInflater inflater = getLayoutInflater();
                row = inflater.inflate(R.layout.row, parent, false);
                holder = new RestaurantHolder(row);
                row.setTag(holder);
            } else {
                holder = (RestaurantHolder) row.getTag();
            }
            holder.populateFrom(model.get(position));
            return (row);
        }

    }

    static class RestaurantHolder {
        private TextView name = null;
        private TextView address = null;
        private ImageView icon = null;

        RestaurantHolder(View row) {
            name = (TextView) row.findViewById(R.id.title);
            address = (TextView) row.findViewById(R.id.address);
            icon = (ImageView) row.findViewById(R.id.icon);
        }

        void populateFrom(Restaurant r) {
            name.setText(r.getName());
            address.setText(r.getAddress());
            if (r.getType().equals("sit_down")) {
                icon.setImageResource(R.drawable.ball_red);
            } else if (r.getType().equals("take_out")) {
                icon.setImageResource(R.drawable.ball_yellow);

            } else {
                icon.setImageResource(R.drawable.ball_green);
            }
        }
    }

}


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Wednesday, 12 February 2014

Android - Custom ListAdapter look more fancier

Leave a Comment
In this tutorial, we will update the layout of our ListView rows, so they show both the name and address of the restaurant, plus an icon indicating the type. Along the way, we will need to create our own custom ListAdapter to handle our row views and a RestaurantHolder to populate a row from a
restaurant.

Note : Please follow the Android Tutorial Post Here Before You Step On This Post.

Create a Stub Custom Adapter

Create a stub implementation of a RestaurantAdapter that will be where we put our logic for  creating our own custom rows. That can look like this, implemented as an inner class of LunchList:

class RestaurantAdapter extends ArrayAdapter<Restaurant> {
         RestaurantAdapter() {
                super(LunchList.this,
                android.R.layout.simple_list_item_1,model);
         }
}


The above code use hard-wire in the android.R.layout.simple_list_item_1 layout for now, and we get our Activity and model from LunchList itself.

Next we need to change our adapter data member to be a RestaurantAdapter, both where it is declared and where it is instantiated in onCreate(). Make these changes, then rebuild and reinstall the application and confirm it works as it did at the end of the previous tutorial.

Design The List Row

Design a row that incorporates all three of our model elements: name, address, and type.
For the type, we will use three icons, one for each specific type (sit down, take-out, delivery).
Note : You can use whatever icons you wish

The Icon will be located on : res/drawable/

NOTE: If your project has no res/drawable/ directory, but does have res/drawable-ldpi/ and others with similar suffixes, rename res/drawablemdpi/ to res/drawable/ directory for use in this project, and delete the other res/drawable-* directories.

Example Custom List


To achieve this look, we use a nested pair of LinearLayout containers. Use the following XML as the basis for LunchList/res/layout/row.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="4dip"
>
<ImageView android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="4dip"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView android:id="@+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:textStyle="bold"
android:singleLine="true"
android:ellipsize="end"
/>
<TextView android:id="@+id/address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:singleLine="true"
android:ellipsize="end"
/>
</LinearLayout>
</LinearLayout> 

Some of the unusual attributes applied in this layout include:
  • android:padding, which arranges for some whitespace to be put outside the actual widget contents but still be considered part of the widget (or container) itself when calculating its size
  • android:textStyle, where we can indicate that some text is in bold or italics
  • android:singleLine, which, if true, indicates that text should not word-wrap if it extends past one line
  • android:ellipsize, which indicates where text should be truncated and ellipsized if it is too long for the available space

Override getView()

Next, we need to use this layout ourselves in our RestaurantAdapter. To do this, we need to  override getView() and inflate the layout as needed for rows.

Modify RestaurantAdapter to look like the following:
class RestaurantAdapter extends ArrayAdapter<Restaurant> {
         RestaurantAdapter() {
                 super(LunchList.this,
                 android.R.layout.simple_list_item_1,model);
         }
         public View getView(int position, View convertView,
                 ViewGroup parent) {
                 View row=convertView;
                 if (row==null) {
                        LayoutInflater inflater=getLayoutInflater();
                        row=inflater.inflate(R.layout.row, null);
                 }
                Restaurant r=model.get(position);
               ((TextView)row.findViewById(R.id.title)).setText(r.getName());
               ((TextView)row.findViewById(R.id.address)).setText(r.getAddress());
               ImageView icon=(ImageView)row.findViewById(R.id.icon);

               if (r.getType().equals("sit_down")) {
                     icon.setImageResource(R.drawable.ball_red);
               }
               else if (r.getType().equals("take_out")) {
                     icon.setImageResource(R.drawable.ball_yellow);
               }
               else {
                     icon.setImageResource(R.drawable.ball_green);
               }
               return(row);
        }
}

Create a RestaurantHolder

To improve performance and encapsulation, we should move the logic that populates a row from a restaurant into a separate class, one that can cache the TextView and ImageView widgets.

To do this, add the following static inner class to LunchList:

static class RestaurantHolder {
         private TextView name=null;
         private TextView address=null;
         private ImageView icon=null;
         RestaurantHolder(View row) {
                 name=(TextView)row.findViewById(R.id.title);
                 address=(TextView)row.findViewById(R.id.address);
                 icon=(ImageView)row.findViewById(R.id.icon);
         }
         void populateFrom(Restaurant r) {
         name.setText(r.getName());
         address.setText(r.getAddress());
         if (r.getType().equals("sit_down")) {
               icon.setImageResource(R.drawable.ball_red);
         }
         else if (r.getType().equals("take_out")) {
               icon.setImageResource(R.drawable.ball_yellow);

         }
         else {
               icon.setImageResource(R.drawable.ball_green);
         }
     }
}

Recycle Rows via RestaurantHolder

To take advantage of the new RestaurantHolder, we need to modify getView() in RestaurantAdapter. Following the holder pattern, we need to create a RestaurantHolder when we inflate a new row, cache that wrapper in the row via setTag(), then get it back later via getTag().
Change getView() to look like the following:

public View getView(int position, View convertView,
           ViewGroup parent) { 
           View row=convertView;
           RestaurantHolder holder=null;
           if (row==null) {
                 LayoutInflater inflater=getLayoutInflater();
                 row=inflater.inflate(R.layout.row, parent, false);
                 holder=new RestaurantHolder(row);
                 row.setTag(holder);
          }
          else {
                holder=(RestaurantHolder)row.getTag();
          }
          holder.populateFrom(model.get(position));
          return(row);
 }


LunchList Class (Full Code)

package apt.tutorial;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.ArrayAdapter;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;



public class LunchList extends Activity {
           List<Restaurant> model=new ArrayList<Restaurant>();
           RestaurantAdapter adapter=null;
        

           @Override
           public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                    Button save=(Button)findViewById(R.id.save);
                    save.setOnClickListener(onSave);
                    ListView list=(ListView)findViewById(R.id.restaurants);
                    adapter=new RestaurantAdapter();
                    list.setAdapter(adapter);
            }
            private View.OnClickListener onSave=new View.OnClickListener() {
                    public void onClick(View v) {
                             Restaurant r=new Restaurant();
                             EditText name=(EditText)findViewById(R.id.name);
                             EditText address=(EditText)findViewById(R.id.addr);
                             r.setName(name.getText().toString());
                             r.setAddress(address.getText().toString());
                             RadioGroup types=(RadioGroup)findViewById(R.id.types);
                             switch (types.getCheckedRadioButtonId()) {
                                  case R.id.sit_down:
                                          r.setType("sit_down");break;
                                  case R.id.take_out:
                                          r.setType("take_out");break;
                                  case R.id.delivery:
                                          r.setType("delivery");break;
                            }
                            adapter.add(r);

                  }
           };



    class RestaurantAdapter extends ArrayAdapter<Restaurant> {
            RestaurantAdapter() {
                   super(LunchList.this, R.layout.row, model);
            }
            public View getView(int position, View convertView,
                    ViewGroup parent) {
                    View row=convertView;
                    RestaurantHolder holder=null;
                    if (row==null) {
                          LayoutInflater inflater=getLayoutInflater();
                          row=inflater.inflate(R.layout.row, parent, false);
                          holder=new RestaurantHolder(row);
                          row.setTag(holder);
                   }
                   else {
                          holder=(RestaurantHolder)row.getTag();
                   }
                   holder.populateFrom(model.get(position));
                   return(row);
            }
    }


    static class RestaurantHolder {
         private TextView name=null;
         private TextView address=null;
         private ImageView icon=null;
         RestaurantHolder(View row) {
                 name=(TextView)row.findViewById(R.id.title);
                 address=(TextView)row.findViewById(R.id.address);
                 icon=(ImageView)row.findViewById(R.id.icon);
         }
         void populateFrom(Restaurant r) {
                name.setText(r.getName());
                address.setText(r.getAddress());
                if (r.getType().equals("sit_down")) {
                       icon.setImageResource(R.drawable.ball_red);
                }
                else if (r.getType().equals("take_out")) {
                       icon.setImageResource(R.drawable.ball_yellow);
                }
                else {
                       icon.setImageResource(R.drawable.ball_green);
                }

        }
    }

}

Rebuild and reinstall the application, then try adding several restaurants and confirm that, when the list is scrolled, everything appears as it should,the name, address, and icon all change.

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Tuesday, 11 February 2014

Android - Store Class Object into ArrayList or List

Leave a Comment
In this tutorial, we will change our model to be a list of restaurants, rather than just one. Then, we will add a ListView to view the available restaurants.
This will be rather incomplete, in that we can only add a new restaurant, not edit or delete an existing one. We will cover those steps too in a later tutorial.

Note : Please refer previous post before step on this tutorial

Hold a List of Restaurants

First, if we are going to have a list of restaurants in the UI, we need a list of restaurants as our model. So, in LunchList, change:

Restaurant r=new Restaurant();

to

List<Restaurant> model=new ArrayList<Restaurant>();

Note that you will need to import java.util.List and java.util.ArrayList as well.

Save Restaurant Object to List

All we need to do is add a local restaurant r variable, populate it, and add it to the list:

private View.OnClickListener onSave=new View.OnClickListener() {
          public void onClick(View v) {
                     Restaurant r=new Restaurant();
                     EditText name=(EditText)findViewById(R.id.name);
                     EditText address=(EditText)findViewById(R.id.addr);
                     r.setName(name.getText().toString());
                     r.setAddress(address.getText().toString());
                     RadioGroup types=(RadioGroup)findViewById(R.id.types);
                     switch (types.getCheckedRadioButtonId()) {
                              case R.id.sit_down:
                                      r.setType("sit_down");break;
                              case R.id.take_out:
                                      r.setType("take_out");break;
                              case R.id.delivery:
                                      r.setType("delivery");break;
                      }
            }
};


Implement toString()

To simplify the creation of our ListView, we need to have our restaurant class respond intelligently to toString(). That will be called on each restaurant as it is displayed in our list.

For the purposes of this tutorial, we will simply use the name. So, add a toString() implementation on restaurant like this:

public String toString() {
       return(getName());
}


Add a ListView Widget

This is the challenging part ---> adding the ListView to the layout.

The challenge is in getting the layout right. Right now, while we have only the one screen to work with, we need to somehow squeeze in the list without eliminating space for anything else. In fact, ideally, the list takes up all the available space that is not being used by our current detail form.

One way to achieve that is to use a RelativeLayout as the over-arching layout for the screen. We anchor the detail form to the bottom of the screen, then have the list span the space from the top of the screen to the top of the detail form.

To make this change, replace your current LunchList/res/layout/main.xml with the following:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableLayout android:id="@+id/details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:stretchColumns="1"
>
<TableRow>
<TextView android:text="Name:" />
<EditText android:id="@+id/name" />
</TableRow>
<TableRow>
<TextView android:text="Address:" />
<EditText android:id="@+id/addr" />
</TableRow>
<TableRow>
<TextView android:text="Type:" />
<RadioGroup android:id="@+id/types">
<RadioButton android:id="@+id/take_out"
android:text="Take-Out"
/>
<RadioButton android:id="@+id/sit_down"
android:text="Sit-Down"
/>
<RadioButton android:id="@+id/delivery"
android:text="Delivery"
/>
</RadioGroup>
</TableRow>
<Button android:id="@+id/save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
/>
</TableLayout>
<ListView android:id="@+id/restaurants"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_above="@id/details"
/>
</RelativeLayout>


If you recompile and rebuild the application, then run it, you will see our form slid to the bottom, with empty space at the top:

Build and Attach the Adapter

The ListView will remain empty, of course, until we do something to populate it. What we want is for the list to show our running lineup of restaurant objects.

Since we have our ArrayList<Restaurant>, we can easily wrap it in an ArrayAdapter<Restaurant> . This also means, though, that when we add a restaurant, we need to add it to the ArrayAdapter via add(). The adapter  will, in turn, put it in the ArrayList. Otherwise, if we add it straight to the ArrayList, the adapter will not know about the added restaurant and
therefore will not display it.

Here is the new implementation of the LunchList class:

package apt.tutorial;


import android.app.Activity;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import java.util.ArrayList;
import java.util.List;


public class LunchList extends Activity {
            List<Restaurant> model=new ArrayList<Restaurant>();
            ArrayAdapter<Restaurant> adapter=null;


            @Override
            public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                    Button save=(Button)findViewById(R.id.save);
                    save.setOnClickListener(onSave);
                    ListView list=(ListView)findViewById(R.id.restaurants);
                    adapter=new ArrayAdapter<Restaurant>(this,
                    android.R.layout.simple_list_item_1,model);
                    list.setAdapter(adapter);
           }
           private View.OnClickListener onSave=new View.OnClickListener() {
                    public void onClick(View v) {
                             Restaurant r=new Restaurant();
                             EditText name=(EditText)findViewById(R.id.name);
                             EditText address=(EditText)findViewById(R.id.addr);
                             r.setName(name.getText().toString());
                             r.setAddress(address.getText().toString());
                             RadioGroup types=(RadioGroup)findViewById(R.id.types);
                             switch (types.getCheckedRadioButtonId()) {
                                    case R.id.sit_down:
                                            r.setType("sit_down");break;
                                    case R.id.take_out:
                                            r.setType("take_out");break;
                                    case R.id.delivery:
                                            r.setType("delivery");break;

                            }
                            adapter.add(r);
                   }
          };
}


The magic value android.R.layout.simple_list_item_1 is a stock layout for a list row, just displaying the text of the object in white on a black background with a reasonably large font. In later tutorials, we will change the look of our rows to suit our own designs.

If you then add a few restaurants via the form, it will look something like this:




By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Android - Fancier Form using TableLayout

Leave a Comment
This post will show how to rearrange the previous post layout to using TableLayout. So that the form will look more fancier.

Note : Please refer previous post before you get step on this tutorial.

Switch to a TableLayout

  1. Open LunchList/res/layout/main.xml and modify its contents to look like the following:
    <?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">
    <TableRow>
    <TextView android:text="Name:" />
    <EditText android:id="@+id/name" />
    </TableRow>
    <TableRow>
    <TextView android:text="Address:" />
    <EditText android:id="@+id/addr" />
    </TableRow>
    <Button android:id="@+id/save"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Save" />
    </TableLayout> 
Notice that we replaced the three LinearLayout containers with a TableLayout and two TableRow containers. We also set up the EditText column to be stretchable. Recompile and reinstall the application, then run it in the emulator. You should see something like this:
Notice how the two EditText fields line up, whereas before, they appeared immediately after each label.

NOTE: At this step, or any other, when you try to run your application, you may get the following screen:

If you encounter this, first try to do a full rebuild of the project. In Eclipse, this would involve doing Project > Force Clean. If the problem persists after this, then there is a bug in your code somewhere. See the Java stack trace associated with this crash, to help you perhaps diagnose what is going on.

Add a RadioGroup

Next, we should add some RadioButton widgets to indicate the type of restaurant this is: one that offers take-out, one where we can sit down, or one that is only a delivery service. To do this, modify LunchList/res/layout/main.xml once again, this time to look like:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
>
<TableRow>
<TextView android:text="Name:" />
<EditText android:id="@+id/name" />
</TableRow>
<TableRow>
<TextView android:text="Address:" />
<EditText android:id="@+id/addr" />
</TableRow>
<TableRow>
<TextView android:text="Type:" />
<RadioGroup android:id="@+id/types">
<RadioButton android:id="@+id/take_out"
android:text="Take-Out"
/>
<RadioButton android:id="@+id/sit_down"
android:text="Sit-Down"
/>
<RadioButton android:id="@+id/delivery"
android:text="Delivery"
/>
</RadioGroup>
</TableRow>
<Button android:id="@+id/save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
/>
</TableLayout>


The RadioGroup and RadioButton widgets go inside the TableLayout, so they will line up with the rest of table. You can see this once you recompile, reinstall, and run the application:

Update the Model

The model class has no place to hold the restaurant type. To change that, modify LunchList/src/apt/tutorial/Restaurant.java to add in a new private String type data member and a getter/setter pair.

Model Class

package apt.tutorial;


public class Restaurant {
      private String name="";
      private String address="";

      private String type=""; 
      public String getName() {
            return(name);
      }
      public void setName(String name) {
           this.name=name;
      }
      public String getAddress() {
           return(address);
      }
      public void setAddress(String address) {
          this.address=address;
      }
      public String getType() {
          return(type);
      }
      public void setType(String type) {
           this.type=type;
      }
} 

Save the Type to the Model

Finally, we need to wire our RadioButton widgets to the model, such that when the user clicks the Save button, the type is saved as well. To do this, modify the onSave listener object to look like this:

package apt.tutorial;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;


public class LunchList extends Activity {
           Restaurant r=new Restaurant();
         

          @Override
          public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                    Button save=(Button)findViewById(R.id.save);
                    save.setOnClickListener(onSave);
           }
           private View.OnClickListener onSave=new View.OnClickListener() {
                       public void onClick(View v) {
                               EditText name=(EditText)findViewById(R.id.name);
                               EditText address=(EditText)findViewById(R.id.addr);
                               r.setName(name.getText().toString());
                               r.setAddress(address.getText().toString());
                               RadioGroup types=(RadioGroup)findViewById(R.id.types);
                               switch (types.getCheckedRadioButtonId()) {
                                       case R.id.sit_down:
                                               r.setType("sit_down");break;
                                       case R.id.take_out:
                                               r.setType("take_out");break;

                                       case R.id.delivery:
                                               r.setType("delivery");break;
                                  }
                          }
          };
}


Recompile, reinstall, and run the application. Confirm that you can save the restaurant data without errors.

If you are wondering what will happen if there is no selected RadioButton, the RadioGroup call to getCheckedRadioButtonId() will return -1, which will not match anything in our switch statement, and so the model will not be modified.

Reference :

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Android - Creating a simple form (Eclipse)

Leave a Comment
This tutorial is the first of several that will build up a lunch list application, where you can track  various likely places to go to lunch. While this application may seem silly, it will give you a chance  to exercise many features of the Android platform. Besides, perhaps you may even find the application to be useful someday.

Generate the Application Skeleton

  1. Create New Project(Refer here)
    Use the new-project wizard to create an empty Android project named LunchList, as described in the Link above. This will create an application skeleton for you, complete with everything  you need to build your first Android application: Java source code, build instructions, etc.

    In particular:
    • Choose a build target that is API Level 9 or higher and has the Google APIs, so you can add a map to the application later.
    • Name the project LunchList, with an initial activity also named LunchList
    • Use apt.tutorial for the package name

Modify the Layout

  1. Using your text editor, open the LunchList/res/layout/main.xml file. Initially, that file will look like this:
    <?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"
    >
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Hello World, LunchList"
    />
    </LinearLayout> 
    
    
  2. Change that layout to look like this:
     <?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"
    >
    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Name:"
    />
    <EditText android:id="@+id/name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
    </LinearLayout>
    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Address:"
    />
    <EditText android:id="@+id/addr"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
    </LinearLayout>
    <Button android:id="@+id/save"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Save"
    />
    </LinearLayout>
  3. This gives us a three-row form: one row with a labeled field for the restaurant name, one with a labeled field for the restaurant address, and a big Save button.

Support All Screen Sizes

You may want to test this application on an emulator. You may want to test it on a phone.You may want to test it on a tablet. The layouts we use in these tutorials will work on a variety of screen sizes, but they will work better if we tell Android that we do indeed those screen sizes. To that end, we need to modify the manifest for our project, to add a <supports-screens> element, declaring what sizes we support and do not.

  1. Open the AndroidManifest.xml file in the root of your project tree, and add in a <supports-screens> element. The resulting file should resemble:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="apt.tutorial"
    android:versionCode="1"
    android:versionName="1.0">
    <supports-screens
    android:xlargeScreens="true"
    android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="false"
    />
    <application android:label="@string/app_name">
    <activity android:name=".LunchList"
    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>
  2. Here, we are declaring that we support normal, large, and extra-large screens, but NOT SMALL screens. Android will not automatically scale down our UI, so our application will not run on a small-screen device (typically under 3" diagonal screen size). However, it will run well on everything bigger than that.

Compile and Install the Application

Run the project :
In your emulator, in the application launcher, you will see an icon for your LunchList application. Click it to bring up your form:

Use the directional pad (D-pad) to navigate between the fields and button. Enter some text in the  fields and click the button, to see how those widgets behave. Then, click the BACK button to return to the application launcher.

Create a Model Class

Now, we want to add a class to the project that will hold onto individual restaurants that will appear in the LunchList. Right now, we can only really work with one restaurant, but that will change in a future tutorial.
  1. using your text editor, create a new file named LunchList/src/apt/tutorial/Restaurant.java with the following contents:
    package apt.tutorial;
    
    public class Restaurant {
      private String name="";
      private String address="";
      public String getName() {
        return(name);
      }
      public void setName(String name) {
        this.name=name;
      }
      public String getAddress() {
        return(address);
      }
      public void setAddress(String address) {
        this.address=address;
      }
    }

Save the Form to the Model

Finally, we want to hook up the Save button, such that when it is pressed, we update a restaurant  object based on the two EditText fields. To do this, open up the LunchList/src/apt/tutorial/LunchList.java file and replace the generated Activity implementation with the one shown below:

package apt.tutorial;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class LunchList extends Activity {
      Restaurant r=new Restaurant(); 

      @Override
      public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main); 
              Button save=(Button)findViewById(R.id.save);
              save.setOnClickListener(onSave);
       } 

       private View.OnClickListener onSave=new View.OnClickListener() {
              public void onClick(View v) {
                    EditText name=(EditText)findViewById(R.id.name); 
                    EditText address=(EditText)findViewById(R.id.addr);
                    r.setName(name.getText().toString());
                    r.setAddress(address.getText().toString());
             }
       };
}


Code Explaination
  • Create a single local restaurant instance when the activity is instantiated.
  • Get our Button from the Activity via findViewById(), then connect it to a listener to be notified when the button is clicked
  • In the listener, we get our two EditText widgets via findViewById(),then retrieve their contents and put them in the restaurant

Run the application to make sure it seems like it runs without errors, though at this point we are not really using the data saved in the restaurant object just yet.


Reference :

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Build, Install, and Run the Application in Your Emulator or Device

Leave a Comment
Having a project is nice and all, but it would be even better if we could build and run it, whether on the Android emulator or your Android device

Eclipse

With your project selected in the Package Explorer pane, click the green play button in the Eclipse toolbar to run your project. The first time you do this, you will have to go through a few steps to set up a run configuration, so Eclipse knows what you want to do.
  1. First, in the Run As list, choose Android Application:
  2. If you have more than one emulator A VD or device available, you will then get an option to choose which you wish to run the application on. Otherwise, if you do not have a device  plugged in, the emulator will start up with the A VD you created earlier. Then, Eclipse will  install the application on your device or emulator and start it up.

Notice there is an icon for your Now application. Click on it to open it and see your first activity in  action. To leave the application and return to the launcher, press the "BACK button", located to the right of the [MENU] button, and looks like an arrow pointing to the left.


Reference :

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Create New Android Project - Eclipse

Leave a Comment
This is a tutorial of creating new android project from Eclipse tools.

Note : If your eclipse dont have Android project, then you need to follow step by step here to install android plugin for eclipse . Install Android Plugin - Eclipse

Eclipse

  1. From the Eclipse main menu, choose File >> New >> Project.; and this will bring up a list of project types to choose from. Fold open the Android option and click on Android Project:
  2. Press Next to advance the wizard to the main Android project page:
  3. Fill in the following: 
    • The name of the project (e.g., Now)
    • The Android SDK you wish to compile against (e.g., Google APIs for Android 2.3)
    • The name of the Java package in which this project goes (e.g: com.commonsware.android.skeleton)
    • The name of the initial activity to create (e.g., Now)
  4. At this point, clicking Finish will create your Eclipse project.
Reference :

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.