Pages

Showing posts with label gallery. Show all posts
Showing posts with label gallery. Show all posts

Thursday, April 28, 2016

Android Gallery Control

In Android the Gallery control is a selection control that displays items in a horizontal gallery. the items in the gallery appear beside each other. they can appear separated by a pre-defined space.

remember that there is a sample demo application for the gallery to download at the end of the post

we can use the gallery to display String items using a simple ArrayAdapter.
so lets see how to create a gallery that displays the word "Hello" in several languages:

the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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="Gallery Demo"
/>
<Gallery
android_id="@+id/gallery"
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_gravity="center_horizontal"
android_spacing="100px"

/>
</LinearLayout>

and in the OnCreate method
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gallery=(Gallery)findViewById(R.id.gallery);
//String array holding the values
String [] text=new String[]{"Hello","Hi","Alloha","Bonjour","Hallo","¡Hola"};
//Array adapter to display our values in the gallery control
ArrayAdapter arr=new ArrayAdapter(this, android.R.layout.simple_gallery_item, text);
gallery.setAdapter(arr);
}

the gallery will be like this

we can increse the spacing between the items by increasing the value of android:spacing property.

we can display a scroll bar to indicate the position of the current selected item in the gallery like this:
<Gallery
android_id="@+id/gallery"
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_gravity="center_horizontal"
android_spacing="100px"
android_scrollbars="horizontal"
android_scrollbarFadeDuration="0"
android_scrollX="100px"
/>




setting the android:scrollbarFadeDuration="0" makes the scroll bar always visible.

The android:scrollX property defines the initial scroll offset of the scroll bar which is the initial distance that the gallery is scrolled for.

Handling Gallery Events
since the gallery is a selction Control (a adapter view) so it can register a OnItemSelectedListener to handle the selection of items within the gallery.

final String [] text=new String[]{"Hello","Hi","Alloha","Bonjour","Hallo","¡Hola"};
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(text[position].toString());
}

@Override
public void onNothingSelected(AdapterView parent) {
// TODO Auto-generated method stub

}
});


now the final step is to add two navigation buttons: Next and Previous to navigate throught the items in the gallery.
the layout is gonna be like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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="Gallery Demo"
android_id="@+id/txt"
/>
<Gallery
android_id="@+id/gallery"
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_gravity="center_horizontal"
android_spacing="100px"
android_scrollbars="horizontal"
android_scrollbarFadeDuration="0"
android_scrollX="100px"
/>
<LinearLayout
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_orientation="horizontal"
android_layout_marginTop="5px"
>
<Button
android_text="Previous"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_id="@+id/btnPrev"
android_onClick="onClick"
/>
<Button
android_text="Next"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_id="@+id/btnNext"
android_onClick="onClick"
/>

</LinearLayout>

</LinearLayout>


now in order to keep track of the index of the currently selected item we need to define two variables
//Variable to store the number of items in the gallery
int ItemsInGallery=0;
int CurrentIndex=0;

and the navigation buttons click handlers:
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.btnNext:
//Increase the index
CurrentIndex++;
//if reached the end of the gallery, then start from the first item
if(CurrentIndex>ItemsInGallery-1)
CurrentIndex=0;
gallery.setSelection(CurrentIndex,true);
txt.setText(String.valueOf(CurrentIndex));
break;
case R.id.btnPrev:
//Decrease the index
CurrentIndex=CurrentIndex-1;
//If reached the first item, then return to the last item in the gallery
if(CurrentIndex<0)
CurrentIndex=ItemsInGallery-1;
gallery.setSelection(CurrentIndex,true);
txt.setText(String.valueOf(CurrentIndex));
break;
}
}
you can download a sample program from here
Read More..

Tuesday, April 19, 2016

Android Developer Days is reloading for 2013

Android Developer Days(ADD) is now reloading for 2013. ADD 2013 will take place on June 14/15, 2013 in METU Cultural and Convention Center, Ankara, Turkey. 
ADD 2013 is targeted to be the one of the biggest international tech related community organization in EMEA. The first ADD was on May 21/22, 2012. There were 700 participants and more than 30 speakers.  ADD 2013,  June 14/15, 2013,  will have more participants, more fun, more networking and more inspiration. 
Take a look at the About, Call for submissions and Participation Form.

ADD is a community conference organized by:  


  • GDG Ankara,
  • GDG ?stanbul,
  • ODTÜ IEEE, 
  • GDG Baku,
  • GTUG Brussels, 
  • GDG Cluj-Napoca, 
  • GDG Dnipropetrovsk, 
  • GDG Eski?ehir, 
  • GDG Konya, 
  • GDG Kyiv, 
  • GDG Lviv, 
  • GDG Samsun, 
  • GDG Tbilisi, 
  • GDG Timi?oara

Call For Submissions

You can join the conference with the followings:

  • Presentations that is 15-20 minutes or 40-45 minutes long.
  • Quickie: 10 minute presentation in small rooms.
  • Poster: You can show your applications in a place dedicated for posters.
  • Workshop: Presentations with hands on coding, 40 minutes long.
Indicate your contribution in OpenConf and please indicate how much your presentation is going to take when submitting it to OpenConf Deadline of Call for Submissions is 1st May 2013.
Subjects:

  • Future Technologies
  • Mobile World
    • Future of Mobile World
    • New Generation Mobile Devices (Project Glass)
  • Android OS
    • Future Versions
    • Android in Different Architectures
    • Android in Different Areas(Industry, Defense, Home Electronics etc.)
  • Android App Development
    • New Features and Capabilities
    • App Development Best Practises
    • Android SDK Tools
    • UI(User Interface) / UX (User Experience) Design
    • App Monetization
      • Ad Integration
      • In-app Billing
    • User Statistics
  • Android NDK
  • Cross Platform App Development Frameworks
  • HTML5
  • Javascript
  • Game Development
  • Google TV
  • Google Playstore
  • Communication Solutions (NFC, Bluetooth, Wi-fi)
  • 3G, 4G Wide Band Communication
  • Cloud
    • Google Cloud Messaging for Android
    • Google App Engine
  • Augmented Reality
  • Social Media
  • Location Based Services and Maps
  • Mobile Education (Fatih Project)
  • Mobile Payment
  • Security
  • Arduino
  • Software Development Methodologies
  • Success Stories
  • GWT




Read More..

Thursday, March 24, 2016

Android Simple Image Gallery

In this post we are going to use the gallery control t construct a simple image gallery.
the layout is like the previous post.

remeber that the Gallery control is populated by an adapter, so we will create a custom adapter that contains ImageViews to display the images.
our custom adapter must inherit from BaseAdapter class
package mina.android.GalleryDemo;

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

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

public class ImageAdapter extends BaseAdapter {
Context Con;
//array to hold the values of image resources
int [] Resources;
List views;

public ImageAdapter(Context con,int[] resources)
{
Con=con;
Resources=resources;
views=new ArrayList(resources.length);
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return Resources.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return views.get(position);
//return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
//return views.get(position).getId();
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView img=new ImageView(Con);
img.setImageResource(Resources[position]);
views.add(img);

return img;
}

}


then in our activity onCreate Method:
int []res=new int[]{R.drawable.wc,R.drawable.wc2,R.drawable.wc3,R.drawable.wc4,R.drawable.wc5};
ItemsInGallery=res.length;
ImageAdapter imgAdapter=new ImageAdapter(this, res);
gallery.setAdapter(imgAdapter);

and that was our simple Image gallery.
download the application from here
Read More..

Friday, March 11, 2016

Contacts API 2 0 and above Android Developer Tutorial


Starting from Android 2.0 (API Level 5), the Android platform provides an improved Contacts API for managing and integrating contacts from multiple accounts and from other data sources. To handle overlapping data from multiple sources, the contacts content provider aggregates similar contacts and presents them to users as a single entity. This article describes how to use the new API to manage (insert, update, delete, view) contacts.

The new Contacts API is defined in the android.provider.ContactsContract and related classes. The older API is still supported, although deprecated.

We need to understand the underlying structure of storage to better manipulate the contacts. We have three distinct types of tables – Contacts, Raw Contacts and Data.

All data related to a contact is stored in this generic data table with each row telling what is the data it stores through its MIME type. So we could have a Phone.CONTENT_ITEM_TYPE as the MIME type of the data row, it contains Phone data. Similarly, if we have Email.CONTENT_ITEM_TYPE as the row’s MIME type, then it stores email data. Like this lot of data rows are associated with a single Raw Contact.

Each Raw Contact refers to a specific contact’s data coming from one single source – say, you gmail account or your office Microsoft account.

The Contact is the topmost in the hierarchy which aggregates similar looking data from various sources into one single contact – a very handy feature when you have redundant data coming about the same contact from you various accounts – like a facebook account, orkut account, yahoo account and goggle account.  So the hierarchy looks like this:
So, when we want to insert a new contact, we always insert a Raw Contact. When we want to update an existing contact, we most often deal with the data tables which are accessible through a series of CommonDataKind classes. Because this would be to update particular types of data like phone or email.
Coming to the example:

I create an activity with four buttons to View, Add, Modify and Delete Contacts.

           Button view = (Button)findViewById(R.id.viewButton);
            Button add = (Button)findViewById(R.id.createButton);
            Button modify = (Button)findViewById(R.id.updateButton);
            Button delete = (Button)findViewById(R.id.deleteButton);
           
           
            view.setOnClickListener(new OnClickListener() {
                  public void onClick(View v){
                        displayContacts();
                        Log.i("NativeContentProvider", "Completed Displaying Contact list");
                  }
            });

On the click of each of the buttons I invoke their respective methods: like displayContacts(), createContact(), updatecContact() and deleteContact(). We will now see each of these methods.

displayContacts() is pretty straightforward. Access to each of the tables mentioned above is through a content URI. I use the topmost level ‘Contacts’ URI to iterate through all the existing contacts and display their names and phone numbers (Toast them).

We know Contacts is a ContentProvider and hence we need to query through a ContentResolver which returns all the data of the contacts.

   private voiddisplayContacts() {
     
      ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                  String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                  String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                  if (Integer.parseInt(cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                     Cursor pCur = cr.query(
                               ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                               null,
                               ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                               new String[]{id}, null);
                     while (pCur.moveToNext()) {
                         String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                         Toast.makeText(NativeContentProvider.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
                     }
                    pCur.close();
                }
            }
        }
    }

I will try to briefly explain the above method.  Line 1 gets a handle to the ContentResolver. Line 2 queries the Contacts URI (ContactsContract.Contacts.CONTENT_URI ) without any mention of the specific columns or “where” clause of an SQL query. Notice all the 4 parameters are null. This means that we are not making any conditional query into the contacts table and hence all data is returned into the cursor.

Next, I check that the cursor is not empty and iterate through the cursor data. I retrieve the _ID and DISPLAY_NAME from the Contacts and then, I check for the flag if the contact has a phone number. This information is available in contacts table itself. But the Phone number details are in the data tables. Hence after checking for the flag, I query the CommonDataKings.Phone.CONTENT_URI for the phone data of that specific ID. From this new cursor named pCur, I retrieve the Phone Number. If there are multiple phone number for one contact, all of them will be retrieved and toasted one after another.
Now, let us see how to create or insert a new contact.

In the createContact() method which is called when you click on the “Add Contact” button, I first query to see if the hardcoded name “Sample Name” already exists. If so, I toast a message stating the same. If not, then I get into actually inserting the name along with a phone number. The first part of the check you can view in the complete source code available for download. Only the second part of inserting a contact is explained here. For this, we need to use a ContentResolveralways.

A ContentResolverprovides an applyBatch(…) method which takes an array of ContentProviderOperation classes as a parameter. All the data built into the ContentProviderOperations are committed or inserted into the ContentProvider that we are working on. IN this case, the ContentProvider we are working on are Contacts and the authority associated with the same is ContactsContract.AUTHORITY

Here is the code for the same:

        ArrayList<ContentProviderOperation> ops = newArrayList<ContentProviderOperation>();
        ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "accountname@gmail.com")
                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "com.google") Read More..

Wednesday, March 2, 2016

Android Developers Blog Introducing Android 4 1 Jelly Bean preview platform and more

Android Developers Blog: Introducing Android 4.1 (Jelly Bean) preview platform, and more
Read More..

Monday, February 8, 2016

Gallery View Android Developer Tutorial

Continuing on the Views, I have taken up the Gallery View that helps in showing Images as in a gallery. As per the android documentation, this is the definition: “A Gallery is a View commonly used to display items in a horizontally scrolling list that locks the current selection at the center.”


For this the layout xml in this case, the main.xml will have a ‘Gallery’ element as shown below:

<Gallery
    android_id="@+id/Gallery01"
    android_layout_width="fill_parent"
    android_layout_height="wrap_content"></Gallery>
<ImageView android_id="@+id/ImageView01"
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"></ImageView>

It also has an ImageView element which is used to show the selected Image in a larger ImageView. Here is how it would look when executed.

Now, I create a GalleryView Activity. To view a set of images of Antartica, I have created small sized images of antartica and stored them in the res/drawable-ldpi folder starting form antartica1.png to antartica10.png.

I create an array of these resources/images in my activity with the following code:

Integer[] pics = {
R.drawable.antartica1,
R.drawable.antartica2,
R.drawable.antartica3,
R.drawable.antartica4,
R.drawable.antartica5,
R.drawable.antartica6,
R.drawable.antartica7,
R.drawable.antartica8,
R.drawable.antartica9,
R.drawable.antartica10
};

As we have seen with all the other views so far, we need to have an adapter that associates the view with the data. Here the view is Gallery and the data is the above mentioned 10 images. An Adapter plays the role of linking the two as shown below:

Gallery ga = (Gallery)findViewById(R.id.Gallery01);
ga.setAdapter(new ImageAdapter(this));

However, we do not have a readymade implementation of the ImageAdapter. We have to create our own implementation of the same by extending the BaseAdapter class. This is the core of the code in this example. The moment we extend the BaseAdapter, we have to override 4 methods. They are getCount(), getItem(), getItemId() and getView().

Before we go to each of them, let us see the constructor of the ImageAdpater:

public class ImageAdapter extends BaseAdapter {


private Context ctx;
int imageBackground;


public ImageAdapter(Context c) {
    ctx = c;
    TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
    imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
    ta.recycle();
}
…
}

It takes the context that is passed to the constructor. We need to examine this code a little. First, we can define our own resources or attributes in an XML file. Those attributes can be retrieved through the method obtainStyledAttributes. This is a method on the Context object. The returned value needs to be stored in a TypedArray object. A TypedArray is nothing but a container for an array of values that are returned by obtainStyledAttributes.

So, in my example, I have created an xml file by name attributes.xml in the res/values folder with the following content:

<resources>
     <declare-styleable name="Gallery1">
    <attr name="android:galleryItemBackground"/>
     </declare-styleable>
</resources>

Here Gallery1 is a custom name for a style defined by us. In this style, we are trying to say what should be the background of our images. For that we are using a pre-defined backgournd in R.attr class as galleryItemBackground.

So, this is accessed in the ImageAdapter contructor through the line

ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();

The number 1 is to say that it is the first element in the attributes.xml file under the styelable Gallery1.

The rest of the over ridden methods are simple:

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


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

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


@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
    ImageView iv = new ImageView(ctx);
    iv.setImageResource(pics[arg0]);
    iv.setScaleType(ImageView.ScaleType.FIT_XY);
    iv.setLayoutParams(new Gallery.LayoutParams(150,120));
    iv.setBackgroundResource(imageBackground);
    return iv;
}

The getView actually returns a View object when called. Here I have overridden it to return a ImageView object with the selected image inside it alosn with some scale, layout paramaters and the image background set.

Finally in the onCreate() method of the activity I have captured the onClick event on a Gallery item and within that I have toasted a message as well as displayed the image in a bigger manner below the gallery:

ga.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    Toast.makeText(getBaseContext(), "You have selected picture " + (arg2+1) + " of Antartica",
        Toast.LENGTH_SHORT).show();
    imageView.setImageResource(pics[arg2]);
}
});

That is it. You may download the complete code from here.

Read More..