Thursday, September 27, 2012

Horizontal Scroll View in Android | Horizontalscrollview example in Android | ScrollView Demo in Android

Hello Friends,
It's a simple demo for Horizontal Scroll View in Android.

1-Print Screen:


2-HorizontalScrollView.java


package com.example.horizontalscrollview;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {

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

3-activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button1" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button2" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button3" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button4" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button5" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button6" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button7" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button8" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button9" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button10" />
        </LinearLayout>
    </HorizontalScrollView>

</LinearLayout>

Thank you so much!

Wednesday, September 26, 2012

Custom ListView in Android | List View Example in Android |ListView ArrayAdapter in Android

Hello Friends,
      It's a very simple demo for custom List-View in android. Important steps or given below, hope it will help you.

1-Print screen:

2-Create a new Project name e.g.- CustomListView.java

package com.example.customlistview;

import java.util.ArrayList;

import android.os.Bundle;
import android.widget.ListView;
import android.app.Activity;

public class CustomListView extends Activity {
ArrayList<Contact> imageArry = new ArrayList<Contact>();
ContactImageAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// add image and text in arraylist
imageArry.add(new Contact(R.drawable.facebook, "FaceBook"));
imageArry.add(new Contact(R.drawable.google, "Google"));
imageArry.add(new Contact(R.drawable.ical, "Ical"));
imageArry.add(new Contact(R.drawable.outlook, "Outlook"));
imageArry.add(new Contact(R.drawable.twitter, "Twitter"));
// add data in contact image adapter
adapter = new ContactImageAdapter(this, R.layout.list, imageArry);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);

}

}

2- Create class Contact.java for getters - setters.

package com.example.customlistview;

public class Contact {

int image;
String name;
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Contact(int image, String name) {
super();
this.image = image;
this.name = name;
}

}

3-Create ContactImageAdapter.java class for display custom list e.g. image and text in same List.

package com.example.customlistview;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ContactImageAdapter extends ArrayAdapter<Contact>{
Context context;
   int layoutResourceId;   
   ArrayList<Contact> data=new ArrayList<Contact>();
   public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) {
       super(context, layoutResourceId, data);
       this.layoutResourceId = layoutResourceId;
       this.context = context;
       this.data = data;
   }

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
       View row = convertView;
       ImageHolder holder = null;
      
       if(row == null)
       {
           LayoutInflater inflater = ((Activity)context).getLayoutInflater();
           row = inflater.inflate(layoutResourceId, parent, false);
          
           holder = new ImageHolder();
           holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
           holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
           row.setTag(holder);
       }
       else
       {
           holder = (ImageHolder)row.getTag();
       }
      
       Contact myImage = data.get(position);
       holder.txtTitle.setText(myImage.name);
          int outImage=myImage.image;
       holder.imgIcon.setImageResource(outImage);
      return row;
      
   }
  
   static class ImageHolder
   {
       ImageView imgIcon;
       TextView txtTitle;
   }
}


4-main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ListView
        android:id="@+id/list"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="0.55" >
    </ListView>
</LinearLayout>

5-list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/imgIcon"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.71"
        android:gravity="center_vertical"/>
    
    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="80dp"
        android:layout_height="fill_parent"
        android:gravity="center_vertical"
        android:textSize="14dp"
        android:layout_marginLeft="7dp" />
      
</LinearLayout>



Thanks...


Image in Sqlite Database and display in a List | SqLite demo in Android

Hello Friends,
      Today I am going to share very important example for how to save Image and text in Sq-lite database and how to display it in a List-view. Steps and code are given below please follow-

1- Create a new Project name e.g.- SQLiteImageDemo.
2- Create a DataBaseHandler class and create database.
3-Create a SQLiteDemoActivity and call DatabaseHandler class for insert and get data from database.
4- Create a Contact class.
4- Create a ContactImageAdapter class for create custom ListView.
5-Add ListView in main.xml file.
6-Create a xml file for add Image and Text.

a) Print Screen:


b)DataBaseHandler.java

package com.manish.sqlite;

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

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "imagedb";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_IMAGE = "image";

public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

// Create tables again
onCreate(db);
}

/**
* All CRUD(Create, Read, Update, Delete) Operations
*/

public// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact._name); // Contact Name
values.put(KEY_IMAGE, contact._image); // Contact Phone

// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}

// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_IMAGE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getBlob(1));

// return contact
return contact;

}

// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM contacts ORDER BY name";

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setImage(cursor.getBlob(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return contact list
return contactList;

}

// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGE, contact.getImage());

// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });

}

// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}

// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}
}

c)SQLiteDemoActivity.java

package com.manish.sqlite;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class SQLiteDemoActivity extends Activity {
ArrayList<Contact> imageArry = new ArrayList<Contact>();
ContactImageAdapter adapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

DataBaseHandler db = new DataBaseHandler(this);
// get image from drawable
Bitmap image = BitmapFactory.decodeResource(getResources(),
R.drawable.facebook);

// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte imageInByte[] = stream.toByteArray();
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("FaceBook", imageInByte));
// display main List view bcard and contact name

// Reading all contacts from database
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "ID:" + cn.getID() + " Name: " + cn.getName()
+ " ,Image: " + cn.getImage();

// Writing Contacts to log
Log.d("Result: ", log);
//add contacts data in arrayList
imageArry.add(cn);

}
adapter = new ContactImageAdapter(this, R.layout.screen_list,
imageArry);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
}
}

d)Contact.java

package com.manish.sqlite;

public class Contact {

// private variables
int _id;
String _name;
byte[] _image;

// Empty constructor
public Contact() {

}

// constructor
public Contact(int keyId, String name, byte[] image) {
this._id = keyId;
this._name = name;
this._image = image;

}

// constructor
public Contact(String name, byte[] image) {
this._name = name;
this._image = image;
}

// getting ID
public int getID() {
return this._id;
}

// setting id
public void setID(int keyId) {
this._id = keyId;
}

// getting name
public String getName() {
return this._name;
}

// setting name
public void setName(String name) {
this._name = name;
}

// getting phone number
public byte[] getImage() {
return this._image;
}

// setting phone number
public void setImage(byte[] image) {
this._image = image;
}
}


e)ContactImageAdapter.java

package com.manish.sqlite;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ContactImageAdapter extends ArrayAdapter<Contact>{
Context context;
int layoutResourceId;
ArrayList<Contact> data=new ArrayList<Contact>();
public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
Contact picture = data.get(position);
holder.txtTitle.setText(picture ._name);
//convert byte to bitmap take from contact class
byte[] outImage=picture._image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
holder.imgIcon.setImageBitmap(theImage);
return row;
}
static class ImageHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}



f)main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.55" >
</ListView>
</LinearLayout>

g)screen_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp" >
<ImageView
android:id="@+id/imgIcon"
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_weight="0.71"
android:gravity="center_vertical" />
<TextView
android:id="@+id/txtTitle"
android:layout_width="80dp"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:textSize="14dp"
android:layout_marginLeft="7dp" />
</LinearLayout>
For simple sqlite demo you can refer below link-
http://www.androidhub4you.com/2012/09/sqlite-database-in-android.html