Search This Blog

Friday, July 15, 2016

Example of Custom ListView in Android


Data Containers in Android:

Usually in android to represent data in list format , following UI components are normally used

1) ListView
2) Expandable ListView
3) GridView
4)RecyclerView  -  Now a days mostly used
4)Gallary

So lets see each in details with simple Examples


1) ListView:

 ListView is one of the UI component in android used as a container to represent data in in verticle scrollable format .
In this list items are added automatically using Adopter

We can implement ListView in normal way and using CustomAdapter.

In normal ListView we set list items using String array or list object ,and in custom ListView we can set list items using custom Adapter class which will extend BaseAdapter class.

Fig. ListView Example


Lets start with new project:

Fig. Directory Structure of example



activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.ygutte.example_of_listview.MainActivity">
 <ListView
   android:id="@+id/list"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
 </ListView>
</RelativeLayout>
Before going to create UI for indivisual list items of list view lets create an rectangle shape to draw border line around list items

assets-> right click ->new Android resource file





** Must see the yellow marked text

rect.xml


<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:color="@android:color/holo_orange_dark" 
     android:width="1dp"/>
        <solid android:color="@android:color/transparent"/>
    <padding
       android:left="5dp"
       android:right="5dp"
       android:top="5dp"
      android:bottom="5dp"        />
    <corners android:radius="5dp"/>
</shape>


Above code will create  orange coloured border around each individual item in the list.


list_item.xml
  <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="@drawable/rect" >
  <ImageView
       android:id="@+id/ImgPhoto" 
       android:layout_width="50dp"
       android:layout_height="50dp" 
       android:src="@drawable/frnd1"/>
  <TextView
        android:id="@+id/tvInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="name" 
        android:layout_gravity="center_horizontal"/>
  </RelativeLayout>                                                                          

 Now lets create Adapter class to set custom view


MyAdaptor.java


  package com.ygutte.example_of_listview;

  import android.content.Context;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.view.ViewGroup;
  import android.widget.BaseAdapter;
  import android.widget.ImageView;
  import android.widget.TextView;

  import java.util.List;

/** * Created by Yogeshwar on 7/15/2016. */  public class MyAdapter extends BaseAdapter
{
    Context context;
    String[] names;
    int[] photo;
    public MyAdapter( Context context,String[] names,int[] photo)
    {
        this.context = context;
        this.names = names;
        this.photo = photo;
    }


    @Override    public int getCount() {
        return names.length;
    }

    @Override    public Object getItem(int position) {
        return null;
    }

    @Override    public long getItemId(int position) {
        return 0;
    }

    @Override    public View getView(int position, View v, ViewGroup parent)
    {

        LayoutInflater inflater = LayoutInflater.from(context);
        v = inflater.inflate(R.layout.list_item,null);

        ImageView imgPhoto = (ImageView)v.findViewById(R.id.ImgPhoto);
        TextView txName = (TextView)v.findViewById(R.id.tvInfo);

        imgPhoto.setImageResource(photo[position]);
        txName.setText(names[position]);

        return v;
    }
}                                                                                            




Now lets move to main code...

MainActivity.java


  package com.ygutte.example_of_listview;

  import android.support.v7.app.AppCompatActivity;
  import android.os.Bundle;
  import android.widget.ListView;

  import java.util.List;

  public class MainActivity extends AppCompatActivity {

    public ListView friends;

    @Override    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        friends = (ListView)findViewById(R.id.list);

        String[] name = {"Abhijeet",
                         "Amol",
                        "Ganesh",
                        "Hanumat",
                        "Rohit",
                        "Sagar",
                        "Sanket",
                        "Vaibhav"};

        int[]  photo= {
                        R.drawable.frnd1,
                        R.drawable.frnd2,
                        R.drawable.frnd3,
                        R.drawable.frnd4,
                        R.drawable.frnd1,
                        R.drawable.frnd2,
                        R.drawable.frnd3,
                        R.drawable.frnd4
                };
        MyAdapter adapter =new MyAdapter(this,name,photo);

        friends.setAdapter(adapter);

    }
}                                                                                            


Click here to Download Code


Happy Coding.......................



Thursday, July 7, 2016

Example of Custom AutoCompleteTextView in Android


Custom AutocompleteTextView :

Hi friends as i have already discussed about AutoCompleteTextView in my previous post

Click here  for  previous example of AutoCompleteTextView.

And now in this example we will going  to see the example of how to implement the CustomAdapet for AutoCompleteTextView.

So lets start with new Project.
as follow

To show string with image as......




OR

To show Only string as .......


                                                         




So lets star as  .....




Project Directory will be as....




activity_main.xml
Its a layout file for  MainActivity class



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ygutte.customactv.MainActivity">

    <AutoCompleteTextView
        android:id="@+id/ACTV"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textAutoComplete|textAutoCorrect"
        android:background="@color/colorPrimaryDark"
        android:layout_marginTop="20dp"
        android:textColor="#fff"
        android:hint="State.."
        android:paddingLeft="10dp"
        android:textSize="30sp"
    />

</RelativeLayout>




indi_item.xml

This is layout for individual items i.e. strings  or string and image we going to display as suggestion

so go to res->drawable folder-> create new XML layout file as..
indi_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
 >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="sample"/>

    <!-- To have just string view remove the following code of image tag-->
    <ImageView
        android:id="@+id/location"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:src="@drawable/location"
        android:layout_alignBottom="@+id/tv"
        android:layout_toRightOf="@+id/tv"
        android:layout_toEndOf="@+id/tv"
        android:layout_marginLeft="15dp"
        android:layout_marginStart="15dp" />

</RelativeLayout>

Now lets create CustomAdapter which will inflate suggestion list to AutoCompleteTextView  as

Project -> new Class as.

name it as.
CustomAdapter.java

package com.ygutte.customactv;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;

import java.util.ArrayList;

/** * Created by Yogeshwar on 7/7/2016. */
public class CustomAdapter extends ArrayAdapter<String> implements Filterable
        {
            private ArrayList<String> allList;
            private ArrayList<String> mValues;
            private ArrayFilter mFilter;

            public CustomAdapter(Context context, int resource, int textViewResourceId, ArrayList<String> allList) {

                super(context, resource, textViewResourceId, allList);
                this.allList = allList;
                mValues = new ArrayList<String>(allList);

            }

            @Override            public int getCount() {
                return allList.size();
            }

            @Override            public String getItem(int position) {
                return allList.get(position);
            }

            @Override            public View getView(int position, View convertView, ViewGroup parent) {
                return super.getView(position, convertView, parent);
            }

            @Override            public Filter getFilter() {
                if (mFilter == null) {
                    mFilter = new ArrayFilter();
                }
                return mFilter;
            }

            private class ArrayFilter extends Filter {
                private Object lock;

                @Override                protected FilterResults performFiltering(CharSequence prefix) {
                    FilterResults results = new FilterResults();

                    if (mValues == null) {
                        synchronized (lock) {
                            mValues = new ArrayList<String>(allList);
                        }
                    }

                    if (prefix == null || prefix.length() == 0) {
                        synchronized (lock) {
                            ArrayList<String> list = new ArrayList<String>(
                                    mValues);
                            results.values = list;
                            results.count = list.size();
                        }
                    } else {
                        final String prefixString = prefix.toString().toLowerCase();

                        ArrayList<String> values = mValues;
                        int count = values.size();

                        ArrayList<String> newValues = new ArrayList<String>(count);

                        for (int i = 0; i < count; i++) {
                            String item = values.get(i);
                            if (item.toLowerCase().contains(prefixString)) {
                                newValues.add(item);
                            }

                        }

                        results.values = newValues;
                        results.count = newValues.size();
                    }

                    return results;
                }

                @SuppressWarnings("unchecked")
                @Override                protected void publishResults(CharSequence constraint,
                                              FilterResults results) {

                    if (results.values != null) {
                        allList = (ArrayList<String>) results.values;
                    } else {
                        allList = new ArrayList<String>();
                    }
                    if (results.count > 0) {
                        notifyDataSetChanged();
                    } else {
                        notifyDataSetInvalidated();
                    }
                }
            }
        }
Now the main code i.e. MainActivity class as

package com.ygutte.customactv;

    import android.app.Activity;
    import android.os.Bundle;
    import java.util.ArrayList;
    import android.widget.AutoCompleteTextView;

public class MainActivity extends Activity {

        @Override        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            ArrayList<String> findArrayList = new ArrayList<String>();

            findArrayList.add("Maharastra");
            findArrayList.add("Manipur");
            findArrayList.add("MadhyaPradesh");
            findArrayList.add("Karnatak");
            findArrayList.add("Andra Pradesh");
            findArrayList.add("Telangana");
            findArrayList.add("Udisa Pradesh");
            findArrayList.add("Meghalaya");
            findArrayList.add("Delhi");
            findArrayList.add("Kashmir");



            CustomAdapter adapter = new CustomAdapter(this,R.layout.indi_item, R.id.tv, findArrayList);

            AutoCompleteTextView ACTV = (AutoCompleteTextView) findViewById(R.id.ACTV);
            ACTV.setAdapter(adapter);

        }

    }

To Download the code click here...



Happy coading..............

Thursday, June 30, 2016

Android Code Execution Step by Step Explanation with simple Hello World Example


Hay friend lets dig step by step Android Code execution with simple  Hello World App code:



Before going to dig a code  first lets understand some UI parts in android as bellow:



User Interface (UI) Group:

UI group is used to specify how to arrange the UI components.

Following are the UI groups used in android:

1)      Linear Layout :-Component arranged in  One after another manner.
2)      Table Layout :-Components arranged in row and columns manner.
3)      Frame Layout
4)      Relative Layout- By using this layout it is possible to move,resize and place UI components wherever on the screen.
5)      Grid Layout



UI Components:
1)      Text View
2)      Edit Text
3)      Button [Custom, Image, Toggle, Radio, Switch, Checkbox etc.]
4)      Image View
5)      Autocomplete Text View
6)      Spinner
7)      List View
8)      Gallery
9)      Grid View
10)   Web view
11)   Fragment
12)   View Switcher or View Flipper.

At this point of time just remember these things detailed explanation about all UI groups and Components we will discuss in upcoming posts....


So lets begin with our Hello World code Execution.......








Fig 1: Create new Project give name "Hello_World"

Fig 2: This will be your Project Structure.



Steps to create an Activity file:

 (**These steps are applied to any new activity we create)

         1)    Create class with sub-type of ”android.app.Activity”    

         2)    Same like main method in c/c++ /Java  in android activity OnCreate()  will invoke first so                    provide the implementation for OnCreate( )

         3)    Design the UI in XML, by using the following method we can set XML file context (UI) to the          java file as shown bellow....
                                                     “SetContentView (R.layout.xml-file)”








Example of: “Hello World” app:

 res->layout->activity_main.xml



         <?xml version="1.0" encoding="utf-8"?>  '

           Here you can see UTF-8 as default it is nothing but a Unicode format use in it

        


           In Android Studio default you will get as Relative Layout change it to Linear Layout,  Here xmlns means "XML namespace "   specifies package

where as namespace is nothing but the collection of Classes ,Interfaces,and collections etc.
  
                < LinearLayout xmlns: android=http://schemas.android.com/apk/res/android
                           android:layout_width="match_parent"
                           android:layout_height="match_parent"
                          android:orientation="vertical"
                                                                 >

             <TextView
                     android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                   android:text="Hello World!" />

           </LinearLayout>


  Here we have specified the attributes of  layout i.e. width and height we using and here "Parent" is the screen in which its going to be displayed.

And we can have orientation of components we are placing in Layout as Horizontal or Vertical as required

 

   



Main_activity.java file

package com.example.ygutte.Hello_World;



import android.app.Activity;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle; 



public class MainActivity extends Activity {
 
//must extends the Activity class


    @Override

    protected void onCreate (Bundle savedInstanceState) {
 
//Bundle is a class used to get state of an activity


        super.onCreate (savedInstanceState);


        SetContentView (R.layout.activity_main);   
 
   // to maintain the status of activity of supper class e.g. Function Overloading
 
/* Here we set the layout of screen as we designed in above xml file so that we use
                                  SetContentView () –converts xml to java
                                                                    -As abstract between xml and java file */


    }

}



Hope you understood the code now you can start yours...... 
Happy Coding...........

Saturday, June 25, 2016

Auto Complete TextView

 Auto Complete TextView in Android

Auto complete text view is Editable TextView which gives suggestion when we type related character in textview.

Click here for Introduction to Android

Click here for Android Project Directory Structure






as shown bellow:


In android we can use Autocomplete TextView in two way
1) AutoComplete TextView :
   Which will show only strings which we assign to it using ArrayAdapter<String>.
2) Custom AutoComplete Text View :
In custom we can assign strings and also images with strings and so on..



1) AutoComplete TextView:

So lets first see the example of Autocomplete TextView.

So check out my project structure  bellow and create yours:




main.xml


 <?xml version="1.0" encoding="utf-8"?>  

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   tools:context="com.ygutte.autocomplete_textview.MainActivity">  

   <AutoCompleteTextView  
     android:id="@+id/actv"  
     android:layout_height="wrap_content"  
     android:layout_width="200dp"  
     android:textSize="12sp"  
     android:layout_centerHorizontal="true">  
     </AutoCompleteTextView>  
 </RelativeLayout>  




MainActivity

 package com.ygutte.autocomplete_textview;
 import android.app.Activity;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.widget.ArrayAdapter;
 import android.widget.AutoCompleteTextView;

 public class MainActivity extends Activity
 {

    AutoCompleteTextView textViewCity;
    @Override    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textViewCity = (AutoCompleteTextView)findViewById(R.id.actv);
        //String[] Cities = getResources().getStringArray(R.array.Array_city);
        String[] Cities = {"Mumbai", "Pune","Hyderabad","Kolkata","Chennai","Bengaluru"};

        ArrayAdapter<String> adapter =new ArrayAdapter<String>(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item,Cities);
        textViewCity.setAdapter(adapter);
        textViewCity.setThreshold(1);

    }
}




Try above example and Happy coding .......









Friday, June 24, 2016

Android Directory Structure

 Android Project Directory



Click here for Android Introduction
Before going to the first project it is must , we should know the Android Project Directory Structure.

So lets begin with it....

check out he following snapshot of android project directory structure

(This structure is  Eclipse IDE  )


Fig.1 Project Structure in Eclipse IDE

This bellow one Structure  is in Android Studio


Fig.2 Project Structure in Android Studio


So friends before going for any project development in any of the technology it is very important to know the structure of the project we going to develop.                                                                        

similar to any other technology in android project also have structure as shown above fig.1 in Eclipse IDE and fig.2 is in Android Studio , now  its  official IDE to develop android apps 
  

1) Src i.e. source (Eclipse) / Java (studio) :

 This folder contains all the packages and java files we create (*.java )

2) Assets : In this folder we put the files which we use in our app i.e. files like html pages,Database files etc.


3)Lib (Library): In this folder we can have the .jar files i.e.additional library files in app.

4)Res (Resources) :


The above resource structure is in Eclipse where we can store different size images related to screens and XML drawable files which contains design /style codes.

where


Following are the  densities supported in android app

  • ldpi (low) ~120dpi
  • mdpi (medium) ~160dpi
  • hdpi (high) ~240dpi
  • xhdpi (extra-high) ~320dpi
  • xxhdpi (extra-extra-high) ~480dpi
  • xxxhdpi (extra-extra-extra-high) ~640dpi
             Where dp stands for Density-independent pixel .

so in in these different folders we can place our different sized images so that app can support different resolution screens android  devices.



R.Java ?

-Here ‘R’ is termed as resource

Purpose: r.java is an abstraction between the java file and different resources available in resource folder
-A resource may be an UI component or file.
-For every resource in resource folder, it creates a static integer field in R.Java so that we can access the resource into our java code with the help of static integer field i.e. id of the resource.

 Eg: R.drawble.image-name (i.e. any resource name)
       R.id.id-name.

          -R.java class
          -R.java is nothing but an internal class
          -It contain/create static internal class for folder/file each you place in folder


Eg: Class R
       {
          Static class drawable {
                                                        public static int icon { }
                                                   }
       }

XML:
In this  data is  enclosed  with tags.
     
In XML we can create our own tags, which is not possible in html.

Normally follow Rules used
                -Every element must be properly nested.
                 -Should not contain space between the tag names.
                -Tagging should not start with numbers and special symbols.
                -Should contain only one root element.
To define own rules to the xml file –go with DTD[Document Type Definition] and /or XSD[XML scheme Definition –it is latest and used in android.].
Following data  formats are used in XML
-UTF-8 (default in adnroid)
-UTF-16

Advantages:
-Used to share data between two technologies.
-XML is used as textual database
-XML is used as deployment descriptor.
Eg: web.xml, web_config.xml,manifest.xml.




5) Layout folder in res : This folder contains XML files which have the view design in XML format. 

6) Values : this is another folder in res directory where we can put dimensions xml file  string resources file, styles.xml and color.xml file and so on which are usefull in app, 

7) Manifest . xml :

This file provides complete description about the app i.e . number of activities used in app,the permissions needed to install the app and so on.

The important thing is android platform before starting and installing the app reefers to the manifest file.


8) Gradle Script :
Is the new thing added to the android studio.
Gradle is a build system used 

Have you ever wondered why the res folder is in the same directory as your src folder?
This is where the build system enters the picture. The build system automatically takes all the source files (.java or .xml), then applies the appropriate tool (e.g. takes java class files and converts them to dex files), and groups all of them into one compressed file, our beloved APK.
This build system uses some conventions: an example of one is to specify the directory containing the source files (in Eclipse it is \src folder) or resources files (in Eclipse it is \res folder).
Now, in order to automate all these tasks, there has to be a script; you can write your own build system using shell scripting in linux or batch files syntax in windows. Got it?
Gradle is another build system that takes the best features from other build systems and combines them into one. It is improved based off of their shortcomings. It is a JVM based build system, what that means is that you can write your own script in Java, which Android Studio makes use of.



Thank you guys hope you understood the directory structure in detail. !