Friday, 9 February 2018

SQLiteDatabase connection using SQLiteOpenHelper class | Insert data into SQLiteDb | View Data from SQLIteDatabase into ListView in Android Studio Example

Here is the example that how to make Application to save user data into SQLite database,using  SQLiteOpenHelper class . And get all data and show into Listview in Android. Here we will use Model class withe setter and getter method to set and get the data.To start this example ,open your Android Studio and add new project like following:- Android Studio(open )-> File -> New-> New Project -> give project name and next and finish.

We will follow following code step :-
Step 1:- Firstly we will design strings.xml file (res -> values-> strings.xml) and we have to add fome string-array  code like following :-
<resources>
    <string name="app_name">SQLiteDatabaseExmp</string>
    <string-array name="date">
        <item>-Select-</item>
        <item>1</item>
        <item>2</item>
        <item>3</item>
        <item>4</item>
        <item>5</item>
        <item>6</item>
        <item>7</item>
        <item>8</item>
        <item>9</item>
        <item>10</item>
        <item>11</item>
        <item>12</item>
        <item>13</item>
        <item>14</item>
        <item>15</item>
        <item>16</item>
        <item>17</item>
        <item>18</item>
        <item>19</item>
        <item>20</item>
        <item>21</item>
        <item>22</item>
        <item>23</item>
        <item>24</item>
        <item>25</item>
        <item>26</item>
        <item>27</item>
        <item>28</item>
        <item>29</item>
        <item>30</item>
        <item>31</item>
    </string-array>

    <string-array name="month">
        <item>-Select-</item>
        <item>January</item>
        <item>February</item>
        <item>March</item>
        <item>April</item>
        <item>May</item>
        <item>June</item>
        <item>July</item>
        <item>August</item>
        <item>September</item>
        <item>October</item>
        <item>November</item>
        <item>December</item>
    </string-array>
    <string-array name="type">
        <item>-Select-</item>
        <item>Birthday</item>
        <item>Anniversary</item>
    </string-array>

</resources>

Step 2:- Now we will design our MainActivity Layout, that which types of input we wants from user. open activity_main.xml  and code like following :-
<?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:layout_gravity="center"    
android:layout_margin="20dp">

    <TextView        
android:id="@+id/tvmain"       
 android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:layout_marginBottom="20dp"        
android:layout_marginTop="20dp"        
android:gravity="center"        
android:text="Database Insert"        
android:textSize="20sp"        
android:textStyle="italic" />

    <EditText        
android:id="@+id/edtName"        
android:layout_width="match_parent"       
 android:layout_height="wrap_content"        
android:layout_below="@+id/tvmain"        
android:hint="Name"        
android:imeOptions="actionDone"        
android:singleLine="true" />

    <TextView        
android:id="@+id/tv"        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:layout_below="@+id/edtName"        
android:layout_marginTop="20dp"        
android:text="Date and Month" />

    <LinearLayout        
android:id="@+id/lay1"        
android:layout_width="match_parent"        
android:layout_height="wrap_content"      
  android:layout_below="@+id/tv"      
  android:layout_marginTop="10dp"       
 android:orientation="horizontal">
        <Spinner            
android:id="@+id/spnMonth"           
 android:layout_width="wrap_content"         
   android:layout_height="wrap_content"          
  android:layout_weight="1"           
 android:entries="@array/date"></Spinner>

        <Spinner            
android:id="@+id/spnDate"           
 android:layout_width="wrap_content"           
 android:layout_height="wrap_content"         
   android:layout_weight="1"           
 android:entries="@array/month"></Spinner>
    </LinearLayout>

    <View        android:layout_width="match_parent"        
android:layout_height="1dp"        
android:layout_below="@+id/lay1"        
android:layout_marginTop="5dp"        
android:background="@color/colorPrimaryDark"></View>

    <TextView        
android:id="@+id/tv1"        
android:layout_width="match_parent"        
android:layout_height="wrap_content"       
 android:layout_below="@+id/lay1"       
 android:layout_marginTop="20dp"       
 android:text="Select Type" />

    <Spinner       
 android:id="@+id/spnType"       
 android:layout_width="wrap_content"      
  android:layout_height="wrap_content"      
  android:layout_below="@+id/tv1"      
  android:layout_marginTop="20dp"      
  android:entries="@array/type"></Spinner>

    <View       
 android:layout_width="match_parent"       
 android:layout_height="1dp"        
android:layout_below="@+id/spnType"        
android:layout_marginTop="5dp"       
 android:background="@color/colorPrimaryDark"></View>

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

        <Button            
android:id="@+id/btnSave"            
android:layout_width="wrap_content"            
android:layout_height="wrap_content"           
 android:layout_weight="1"            
android:text="Save" />

        <Button            
android:id="@+id/btnView"           
 android:layout_width="wrap_content"            
android:layout_height="wrap_content"           
 android:layout_weight="1"            
android:text="View" />
    </LinearLayout>


</RelativeLayout>

Step 3:- Next create a Model class of all info which we wants to take from user or wants to insert into Database (java -> right click on package -> add new java class with name ModelClass) to setter and getter for all data:- Code will be like:-
public class ModelClass  {
    int id;
    String name;
    String date;
    String month;
    String typeOfCelebration;

    public ModelClass() {
    }

    public ModelClass(int id, String name, String date, String month, String typeOfCelebration) {
        this.id = id;
        this.name = name;
        this.date = date;
        this.month = month;
        this.typeOfCelebration = typeOfCelebration;
    }

    public ModelClass(String name, String date, String month, String typeOfCelebration) {
        this.name = name;
        this.date = date;
        this.month = month;
        this.typeOfCelebration = typeOfCelebration;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getMonth() {
        return month;
    }

    public void setMonth(String month) {
        this.month = month;
    }

    public String getTypeOfCelebration() {
        return typeOfCelebration;
    }

    public void setTypeOfCelebration(String typeOfCelebration) {
        this.typeOfCelebration = typeOfCelebration;
    }
}

Step 4:- Next we will make a new class (java -> right click on package -> add new java class with name Database ) to do database operation  and code like following :-
after adding new class > open Database class and extend class with SQLiteOpenHelper.
Error will shown because here we have to implement two method and constructor.
For macOS User click(control+enter key and click on constructor). for implements method click alt_enter in mac user and click on implements and add two method: onCreate and onUpgrade .
Final code will be like following:-

public class Database extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="MyDatabase";
    private static final int DATABASE_VERSION=1;

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

    @Override   
 public void onCreate(SQLiteDatabase db) {
 db.execSQL("create table if not exists MyTable(ID integer primary key autoincrement not null,NAME varchar,DATE varchar,MONTH varchar,TYPE varchar)");
    }

    @Override        
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS MyTable");
        onCreate(db);
    }

    //operation on database    
public void insert(ModelClass modelClass){
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put("NAME",modelClass.getName());
        cv.put("DATE",modelClass.getDate());
        cv.put("MONTH",modelClass.getMonth());
        cv.put("TYPE",modelClass.getTypeOfCelebration());
        db.insert("MyTable",null,cv);
        db.close();
    }

    //GET ALL DATA    
public List<ModelClass> getAllData(){
        SQLiteDatabase db=this.getReadableDatabase();
        List<ModelClass> listData=new ArrayList<ModelClass>();
        Cursor cursor=db.rawQuery("select * from MyTable",null);
        if(cursor.moveToFirst()){
            do{
             ModelClass modelClass=new ModelClass();
             modelClass.setName(cursor.getString(1));
             modelClass.setDate(cursor.getString(2));
             modelClass.setMonth(cursor.getString(3));
             modelClass.setTypeOfCelebration(cursor.getString(4));
             listData.add(modelClass);
            }while (cursor.moveToNext());
        }

        return listData;
    }
}

Step 5:- MainActivity.java class code will be like following:-
public class MainActivity extends AppCompatActivity {
    EditText etName;
    Spinner spnDate,spnMonth,spnType;
    Database database;
    Button btnSave,btnView;

    @Override    
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etName=(EditText)findViewById(R.id.edtName);
        spnDate=(Spinner)findViewById(R.id.spnDate);
        spnMonth=(Spinner)findViewById(R.id.spnMonth);
        spnType=(Spinner)findViewById(R.id.spnType);

        btnSave=(Button)findViewById(R.id.btnSave);
        btnView=(Button)findViewById(R.id.btnView);

        database=new Database(this);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override            
public void onClick(View v) {
                database.insert(new ModelClass(etName.getText().toString(),spnDate.getSelectedItem().toString(),spnMonth.getSelectedItem().toString(),spnType.getSelectedItem().toString()));
                etName.setText("");
                spnDate.setSelection(0);
                spnMonth.setSelection(0);
                spnType.setSelection(0);
            }
        });

        btnView.setOnClickListener(new View.OnClickListener() {
            @Override            
public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,UserData.class));
            }
        });


    }
}

Step 6:- Next create a new class name UserData.java here we will show all information which we saved into database code like following :-
public class UserData extends AppCompatActivity {
    ListView list;
    List<ModelClass> allList;
    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_data);
        list=(ListView)findViewById(R.id.list);
        Database db=new Database(this);
        allList=db.getAllData();
        if(allList.size()>0)
        list.setAdapter(new Adapter(this,allList));
    }
}
Step 7:- user_data.xml code will be like following:-
<?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="match_parent"    
android:orientation="vertical">
    <ListView        
android:layout_width="match_parent"        
android:layout_height="match_parent"        
android:id="@+id/list"></ListView>

</LinearLayout>
Step 8:- Next we will create a row item xml where we decorate all data in each row ListView :-
<?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="match_parent"    
android:layout_margin="10dp"    
android:orientation="horizontal">
    <TextView
android:layout_width="wrap_content"        
android:layout_height="wrap_content"        
android:id="@+id/name"        
android:layout_weight="1"/>
    <TextView
android:layout_width="wrap_content"        
android:layout_height="wrap_content"        
android:id="@+id/date"        
android:layout_weight="1"/>
    <TextView
android:layout_width="wrap_content"        
android:layout_height="wrap_content"        
android:id="@+id/month"        
android:layout_weight="1"/>
    <TextView
android:layout_width="wrap_content"        
android:layout_height="wrap_content"        
android:id="@+id/type"        
android:layout_weight="1"/>

</LinearLayout>
Step 9:- Next we will create a adapter class to fill  of each row of ListView :

public class Adapter extends BaseAdapter {
    UserData userData;
    LayoutInflater inflater;
    List<ModelClass> list;

    public Adapter(UserData userData, List<ModelClass> list) {
        this.userData = userData;
        this.list = list;
        inflater=LayoutInflater.from(userData);
    }

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

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

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

    @Override    
public View getView(int position, View convertView, ViewGroup parent) {
        convertView=inflater.inflate(R.layout.row_item,null);
        TextView tvName=(TextView)convertView.findViewById(R.id.name);
        TextView tvDate=(TextView)convertView.findViewById(R.id.date);
        TextView tvMonth=(TextView)convertView.findViewById(R.id.month);
        TextView tvType=(TextView)convertView.findViewById(R.id.type);

        tvName.setText(list.get(position).getName());
        tvDate.setText(list.get(position).getDate());
        tvMonth.setText(list.get(position).getMonth());
        tvType.setText(list.get(position).getTypeOfCelebration());
        return convertView;
    }
}
Step 6:- Screen Shorts:-










No comments:

Post a Comment