Tuesday 25 February 2014

How to disable asp.net version and server information on HTTP Headers

Leave a Comment

Scenario:

We identified that the target web server is disclosing the ASP.NET version in its HTTP response. This information might help an attacker gain a greater understanding of the systems in use and potentially develop further attacks targeted at the specific version of ASP.NET.

Impact:

An attacker might use the disclosed information to harvest specific security vulnerabilities for the version identified.

Solution

Disable the asp.net version and server information on http headers.
Open the web.config file and add this code in the web.config file :

<system.webServer>

    <httpProtocol>

        <customHeaders>

            <remove name="Server" />

            <remove name="X-AspNet-Version" /> 

            <remove name="X-AspNetMvc-Version" />

            <remove name="X-Powered-By" />                        

        </customHeaders>        

    </httpProtocol>

  </system.webServer>


You also need to remove the X-Powered-By headers on the IIS configuration.
  1. Open your IIS
  2. Open Http Response Headers
  3. Remove the X-Powered-By value.

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...

How to disable httpOnlyCookies - asp.net

Leave a Comment

Scenario

HTTP only cookies cannot be read by client-side script therefore marking a cookie as HTTP only can provide an additional layer of protection against cross-site script attack.

Impact:

During Cross-Site scripting attack and attacker might easily access cookies and hijack the victim’s session.

Solution

You can disable the httpOnlyCookies on the web.config file. Open the web.config file and add the configuration on the httpCookies element like example below :

<system.web>

:

: 

<httpCookies httpOnlyCookies="false" requireSSL="false" domain="" />

:

:
 </system.web>




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 18 February 2014

Store and retrieve image from database MSSQL - asp.net

Leave a Comment
This is a example to upload image and store into database. The example also show how to retrieve image from database.

Note : Assume the web page have their own master page

SQL Create Table

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[imageTest](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Image] [image] NULL,
 CONSTRAINT [PK_imageTest] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO



ASPX page Code

    <asp:Label ID="Label1" runat="server" Text="Image Upload :"></asp:Label>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />
    <br />
    <br />
    <asp:Panel ID="Panel1" runat="server">
       
    </asp:Panel>



Code Behind


protected void Page_Load(object sender, EventArgs e)
        {
            CheckIfHaveImage();
        }

        private void CheckIfHaveImage()
        {
            try
            {
                //Initialize SQL Server connection.
                SqlConnection dbConn = new SqlConnection("Connection string");

                //Initialize SQL adapter.
                SqlDataAdapter ADAP = new SqlDataAdapter("Select * from ImageTest", dbConn);

                //Initialize Dataset.
                DataSet DS = new DataSet();

                //Fill dataset with ImagesStore table.
                ADAP.Fill(DS, "ImagesStore");
                dbConn.Close();

                string path = Server.MapPath("~");
                foreach (DataRow row in DS.Tables[0].Rows)
                {
                    string image1 =  Convert.ToString(DateTime.Now.ToFileTime());
                    path += "/" + image1 + ".jpg";
                    FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
                    byte[] bimage1 = (byte[])row["Image"];
                    fs.Write(bimage1, 0, bimage1.Length - 1);
                    fs.Flush();
                    Image I = new Image();
                    I.ImageUrl = "~/" + image1 + ".jpg";
                    Panel1.Controls.Add(I);
                }
            }
            catch (Exception ex)
            {                
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                //get root path
                string path = Server.MapPath("~");

                //save image upload
                path += "/" + FileUpload1.FileName;
                FileUpload1.SaveAs(path);

                //Initialize byte array with a null value initially.
                byte[] data = null;

                //Use FileInfo object to get file size.
                FileInfo fInfo = new FileInfo(path);
                long numBytes = fInfo.Length;

                //Open FileStream to read file
                FileStream fStream = new FileStream(path, FileMode.Open, FileAccess.Read);

                //Use BinaryReader to read file stream into byte array.
                BinaryReader br = new BinaryReader(fStream);

                //When you use BinaryReader, you need to supply number of bytes to read from file.
                //In this case we want to read entire file.
                //So supplying total number of bytes.

                data = br.ReadBytes((int)numBytes);

                //create db connection
                SqlConnection dbConn = new SqlConnection("Connection string");
                SqlCommand dbComm;

                string strsql = "insert into ImageTest (Image) values(@image)";
                dbComm = new SqlCommand(strsql, dbConn);
                SqlParameter param = new SqlParameter("@image", System.Data.SqlDbType.Image);
                param.Value = data;
                dbComm.Parameters.Add(param);

                dbConn.Open();
                dbComm.ExecuteNonQuery();
                dbConn.Close();
            }
        } 


Code Explanation

The example above have file upload controller.After user select on the image to upload and click save button, the code will save upload image into temporary file, and process it as a byre[]. After that store byte value into database. The retrieve process will load data from database and convert byte[] value from database into an image and then create Image controller dynamically and add the image controller into panel to show the image.


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...

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

Example Upload File - ASP.NET

Leave a Comment
This is example of upload file using asp.net.

Html 

 <fieldset style="width: 804px" align="center">
        <legend><em>Using the FileUpload Control</em>&nbsp;</legend>
        <div align="left" style="text-align: center">
            <form id="form1" runat="server">
                <div>
                    <table style="width: 90%">
                        <tr>
                            <td colspan="2">
                                <br />
                                <asp:Label ID="LSuccessMssg" runat="server"></asp:Label>
                                <asp:FileUpload ID="FileUpload1" runat="server" /><asp:Button ID="buttonUpload" runat="server"
                                    Text="Upload" OnClick="buttonUpload_Click1" /></td>
                        </tr>
                    </table>
                </div>
            </form>
        </div>
    </fieldset> 

Code Behind

 protected void UploadThisFile(FileUpload upload)
    {
        if (upload.HasFile)
        {
            string theFileName = Path.Combine(Server.MapPath("~/Uploads"), upload.FileName);
            if (File.Exists(theFileName))
            {
                File.Delete(theFileName);
            }
            upload.SaveAs(theFileName);
        }
    }   

    protected void buttonUpload_Click1(object sender, EventArgs e)
    {
        UploadThisFile(FileUpload1);
        LSuccessMssg.Text = "Successfully upload File";
    }


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 - 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...

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.