Tuesday, February 10, 2015

Sample Ormlite for Android Database

Hi Guys, This post is all about Ormlite, so What is Ormlite?
Ormlite is an open source software framework that provides lightweight object relational mapping (ORM) between Java classes and SQL databases. It supports JDBC databases as well as Android mobile platform according. To see more documentations about Ormlite visit this (http://ormlite.com/)

Okay lets Start the Project!! :D

1st add this to your dependencies

Download Jar here

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile files('libs/ormlite-android-4.48.jar')
    compile files('libs/ormlite-core-4.48.jar')
}


1.MainActivity.java

package com.example.user.ormlite;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import java.util.List;

public class MainActivity extends ActionBarActivity {

    DataHelper dbHelper;
    Button save;
    Button viewAll;
    Button delete;
    EditText student_name;
    EditText student_lastname;
    EditText student_age;

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

        //Get All Widget
        save = (Button) findViewById(R.id.btn_save);
        viewAll = (Button) findViewById(R.id.btn_view);
        delete = (Button) findViewById(R.id.btn_delete);
        student_name = (EditText) findViewById(R.id.name);
        student_lastname = (EditText) findViewById(R.id.surname);
        student_age = (EditText) findViewById(R.id.age);
        innit();
    }

    public void innit(){

        //OpenHelper of DatabaseHelper
        dbHelper = (DataHelper) OpenHelperManager.getHelper(this,DataHelper.class);
        final RuntimeExceptionDao<student integer=""> studDao = dbHelper.getStudRuntimeExceptionDao();
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(student_name.getText().toString().length() &gt; 0 &amp;&amp; student_lastname.getText().toString().length() &gt; 0 &amp;&amp; student_age.getText().toString().length() &gt; 0) {
                    studDao.create(new Student(student_name.getText().toString(), student_lastname.getText().toString(), Integer.parseInt(student_age.getText().toString())));
                    student_name.setText("");
                    student_lastname.setText("");
                    student_age.setText("");
                    Toast.makeText(MainActivity.this, "Student Saved", Toast.LENGTH_SHORT).show();
                }
                else
                    Toast.makeText(MainActivity.this, "Please Complete all Inputs", Toast.LENGTH_SHORT).show();
            }
        });
        viewAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String display = "";
                List<student> students = studDao.queryForAll();
                for(Student holder : students){
                    display += holder.getFname() + " " +  holder.getLname() + " " +holder.getAge() + "\n";
                }
                Toast.makeText(MainActivity.this,"Students:" +  display, Toast.LENGTH_SHORT).show();
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<student> students = studDao.queryForAll();
                studDao.delete(students);
                Toast.makeText(MainActivity.this,"Deleted", Toast.LENGTH_SHORT).show();
            }
        });

    }
    public void onDestroy(){
        super.onDestroy();
        OpenHelperManager.releaseHelper();
    }

}


2.Student.java Declaring your Database Table
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

/**
 * Created by Eugene Alvizo on 1/4/2015.
 */

public class Student {

    //Database Field for Table Student
    @DatabaseField (generatedId = true)
    private int id;
    @DatabaseField
    private String fname;
    @DatabaseField
    private String lname;
    @DatabaseField
    private int age;

    //Constructors

    public Student() {
      //Adding a No-Argument-Constructor
    }

    public Student(String fname, String lname, int age) {
        this.fname = fname;
        this.lname = lname;
        this.age = age;
    }

    public Student(int id, String fname, String lname, int age) {
        this.id = id;
        this.fname = fname;
        this.lname = lname;
        this.age = age;
    }

    //Getters and Setters
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }


    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}
3.DataHelper.java Creating your Database
package com.example.user.ormlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

/**
 * Created by Eugene Alvizo on 1/4/2015.
 */
public class DataHelper extends OrmLiteSqliteOpenHelper {

    private Context context;
    private static final String DATABASE_NAME = "Student";
    private static final int DATABASE_VERSION = 1;

   
    private RuntimeExceptionDao<student integer=""> studRuntimeDAO = null;
    public DataHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, Student.class);
        } catch (SQLException e){
            e.printStackTrace();
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i2) {
        try {
            TableUtils.dropTable(connectionSource, Student.class, true);
            onCreate(sqLiteDatabase,connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public RuntimeExceptionDao<student integer=""> getStudRuntimeExceptionDao(){
        if(studRuntimeDAO == null){
            studRuntimeDAO = getRuntimeExceptionDao(Student.class);
        }
        return studRuntimeDAO;

    }

}
4.activity_main.xml Layout for the App
<LinearLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">
    <EditText
        android:layout_width="180dp"
        android:layout_height="45dp"
        android:hint="Name"
        android:id="@+id/name"/>
    <EditText
        android:layout_width="180dp"
        android:layout_height="45dp"
        android:hint="Lastname"
        android:id="@+id/surname"/>
    <EditText
        android:layout_width="180dp"
        android:layout_height="45dp"
        android:hint="Age"
        android:inputType="number"
        android:id="@+id/age"/>
    <Button
        android:layout_width="180dp"
        android:layout_height="45dp"
        android:text="Save"
        android:id="@+id/btn_save"/>
    <Button
        android:layout_width="180dp"
        android:layout_height="45dp"
        android:text="View All"
        android:id="@+id/btn_view"/>
        <Button
            android:layout_width="180dp"
            android:layout_height="45dp"
            android:text="Delete All"
            android:id="@+id/btn_delete"/>
    </LinearLayout>

</LinearLayout>

           
Download Source code (Android Studio Project) reference

Friday, December 26, 2014

Android Listview with Checkbox (Custom Adapter)

Hi Guys!

Today I'm going to share with you how to add Checkbox on your Listview  and getting all selected values in your list.

IDE - Android Studio 1.0
Reference: BaseAdapter

Process Flow of the App:

















Java codes that you needed:

1. Item.java
package com.example.user.listviewxcheckbox;

public class Item {

    String name;
    boolean checkbox;

    public Item() {
         /*Empty Constructor*/
    }
    public  Item(String country, boolean status){
        this.name = country;
        this.checkbox = status;
    }
    //Getter and Setter
    public String getName() {
        return name;
    }

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

    public boolean isCheckbox() {
        return checkbox;
    }

    public void setCheckbox(boolean checkbox) {
        this.checkbox = checkbox;
    }

}

2. ItemSelectedAdapter.java
package com.example.user.listviewxcheckbox;

import android.view.LayoutInflater;
import java.util.ArrayList;
import android.view.View;
import android.view.ViewGroup;
import android.content.Context;
import android.widget.BaseAdapter;
import android.widget.*;
/**
 * Created by Eugene Alvizo on 12/26/2014.
 */
public class ItemSelectedAdapter extends BaseAdapter{

    private Context activity;
    private ArrayList<item> data;
    private static LayoutInflater inflater = null;
    private View vi;
    private ViewHolder viewHolder;

    public ItemSelectedAdapter(Context context, ArrayList&lt;Item&gt;<item> items) {
        this.activity = context;
        this.data = items;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

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

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

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        vi = view;
      //Populate the Listview
        final int pos = position;
        Item items = data.get(pos);
        if(view == null) {
            vi = inflater.inflate(R.layout.listview_item, null);
            viewHolder = new ViewHolder();
            viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.checkbox);
            viewHolder.name = (TextView) vi.findViewById(R.id.name);
            vi.setTag(viewHolder);
        }else
            viewHolder = (ViewHolder) view.getTag();
        viewHolder.name.setText(items.getName());
        if(items.isCheckbox()){
            viewHolder.checkBox.setChecked(true);
        }
        else {
            viewHolder.checkBox.setChecked(false);
        }
        return vi;
    }
    public ArrayList<item> getAllData(){
        return data;
    }
    public void setCheckBox(int position){
       //Update status of checkbox
        Item items = data.get(position);
        items.setCheckbox(!items.isCheckbox());
        notifyDataSetChanged();
    }

    public class ViewHolder{
        TextView name;
        CheckBox checkBox;
    }
}


3. MainActivity.java

package com.example.user.listviewxcheckbox;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;


public class MainActivity extends ActionBarActivity {
    private  Item itemHandler;
    private ItemSelectedAdapter adapter;
    private ArrayList<item> itemList;
    private ListView listView;
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView =(ListView) findViewById(R.id.listview);
        button = (Button) findViewById(R.id.printbtn);
        setWidget();
    }
    public void setWidget(){
       //Adding data to ArrayList
        itemList = new ArrayList&lt;Item&gt;<item>();
        itemList.add(new Item("Philippines", false));
        itemList.add(new Item("America", false));
        itemList.add(new Item("Thailand", false));
        itemList.add(new Item("Korea", false));
        itemList.add(new Item("Japan", false));
        itemList.add(new Item("China", false));
        itemList.add(new Item("Australia", false));
        itemList.add(new Item("Canada", false));
        itemList.add(new Item("Italy", false));
        itemList.add(new Item("Iraq", false));
        //Setup Adapter for Listview
        adapter = new ItemSelectedAdapter(MainActivity.this,itemList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int position, long l) {
               //Item Selected from list
                adapter.setCheckBox(position);

            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               //Display All Item Selected
                String countries = "";
                for(Item hold: adapter.getAllData()){
                    if(hold.isCheckbox()){
                        countries += " "  + hold.getName();
                    }
                }
                Toast.makeText(MainActivity.this,"Names: " + countries,Toast.LENGTH_SHORT).show();
            }
        });

    }
}
XML(Layouts) codes that you needed:

1.activity_main.xml
<LinearLayout 
      android:layout_height="match_parent" 
      android:layout_width="match_parent" 
      android:orientation="vertical" 
      tools:context=".MainActivity" 
      xmlns:android="http://schemas.android.com/apk/res/android" 
      xmlns:tools="http://schemas.android.com/tools">

    <ListView 
      android:id="@+id/listview" 
      android:layout_height="514dp" 
      android:layout_width="fill_parent"/>
    <Button 
      android:id="@+id/printbtn"
      android:layout_height="fill_parent" 
      android:layout_width="fill_parent" 
      android:text="Print"/>
   
 </LinearLayout>
2.listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:descendantFocusability="blocksDescendants">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        android:gravity="center">
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:gravity="center_vertical"
            android:paddingLeft="30dp"
            android:layout_weight=".8">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Item"
                android:id="@+id/name"
                android:focusable="false"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight=".1">
            <CheckBox
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:checked="true"
                android:focusable="false"
                android:clickable="false"
                android:id="@+id/checkbox" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

OUTPUT:






Download Source Code