Quantcast
Viewing all articles
Browse latest Browse all 10

Android how can add data into SQLite

Prerequisite

If you not understand this lecture .how can add data into SQLite Database in android.You should also read my previous lectures Option Menu in android studio and Contextual Action mode in android studio . After reading these lecture you will also able to create Database of your Application.

Overview

Most of Application have to need to store small amount of data.And use Database is essential aspect of most of application. In android they are several ways to store data.While working with android studio you can store data in shared preference, file, and database.Android provide its own database name like SQLite. Most of all android device provide its own database name like SqlLite.

What is SQLite

SQLite is a embedded (RDBMS) Stand for Relation DataBase Management system.Most relation database such as ORACAL and SQL are example that are working independently and store the information.SQLite is referred to as embedded because it is provided in the form of a library that is linked into applications.The code for SQLite is in the public domain and is thus free for use for any purpose, commercial or private.There is no sever that are running in the background.All the Database function are perform internally.

Introduction

In this lecture well we describe how can create Database in android studio.And also describe what is SQLite.why we can use it.After Reading this lecture you will understand how can create a Database in android And i hope you will create Database of your application.

Description of Insert data into Database

In this lecture will describe how can working with Database in android studio.So we create a simple application that will describe how to create a database and add information into database.First of all we create project in android studio.Every project contain two file first is java class file and second is layout XML file.And we open a layout.XML file and add a button when user click on a button open a new activity.In that activity we will create three Edit text and one button.when user click on button data saved into database.So this is a work that will done this section.please read this lecture carefully all the detail is provides step by step.

Layout XML BASIC

XML Layout 

First of you will open a XML file of layout and set Linear Layout  and add  Edit text

Different property that are used in layout.xml file  explain here

  • warp_content   warp_content means height and width similar to the text that are entered.
  • Match_parent   means height and width similar to parent.
  • Edit text              The Edit Text control allows a user to enter text into an application
  • Button                  When user click on a button store information into database and show message

 And Write the following code in Activity_main.XML file

<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:orientation="vertical"
tools:context=".LinearLayout"
android:background="#000000"
    >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="sendMessage"
    android:text="@string/button1"
    android:layout_gravity="center"
    />
</LinearLayout>

Now we create a new Layout.

  • <- create a new Layout< Nameadddata_layout->Right click> the ->layout folder-> select ->New option-> and click ->layout resource folder->
  • WriteName->Ok.

In this example we are going to create a simple UI that includes only (Edit text) and (Button)with Different attributes  And Write the following code in adddata_layout .XML file:

<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:orientation="vertical"
    tools:context=".LinearLayout"

    >

    <EditText
        android:id="@+id/edi4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:layout_marginTop="30dp"
        android:layout_gravity="center"
        android:text="@string/edit4" />

    <EditText
        android:id="@+id/edit1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:layout_margin="20dp"
        android:hint="Contant name"

         />

    <EditText
        android:id="@+id/edit2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:layout_margin="20dp"
        android:hint="Mobile number"
         />

    <EditText
        android:id="@+id/edit3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:layout_margin="20dp"
        android:hint="Email address"
         />

    <Button
        android:id="@+id/button_save"
        android:layout_gravity="center"
        android:background="#000000"
        android:textColor="#FFFFFF"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:onClick="addContant"
        android:text="@string/button_save"
        android:textSize="25dp" />

</LinearLayout>

Step1=Create new class <-NewContactActivity ->Right click-> the ->package name ->select ->New option-> and click-> java class that will show in below.  

Image may be NSFW.
Clik here to view.
Alt Tag Android make new class

Step2=Step1->WriteName->Ok

Image may be NSFW.
Clik here to view.
Alt Tag android sqlite new class

And Write the following code NewContactActivity. java class

package customspinner.alienslab.com.adddata;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class NewContactActivity extends Activity {
    EditText ContactName,MobileNumber,EmailAddress;
    Context context=this;
    UserDbHelper userDbHelper;
    SQLiteDatabase sqLiteDatabase;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.adddata_layout);
        ContactName=(EditText)findViewById(R.id.contant_name);
        MobileNumber=(EditText)findViewById(R.id.mobile_number);
        EmailAddress=(EditText)findViewById(R.id.email_address);
    }

    public void addContant(View view)
    {
        String name=ContactName.getText().toString();
        String mob= MobileNumber.getText().toString();
        String email=EmailAddress.getText().toString();
        userDbHelper=new UserDbHelper(context);
        sqLiteDatabase=userDbHelper.getWritableDatabase();
        userDbHelper.addinnformation(name,mob,email,sqLiteDatabase);
        Toast.makeText(getBaseContext(),"Data saved",Toast.LENGTH_LONG).show();
        userDbHelper.close();
    }
}

  • Step3=Create new class <-UserContract ->Right click-> the ->package name ->select ->New option-> and click-> java class that will show in above. 
  •  Step4=Step3->WriteName->Ok
  • if you not understand this please read first step
  • And Write the following code UserContract. java class
public class UserContract {

    public static abstract class NewUserInfo
    {
     public static final String USER_NAME="user_name";
        public static final String USER_MOB="user_mob";
        public static final String USER_EMAIL="user_email";
        public static final String TABLE_NAME="user_info";
    }
}

  • Step5=Create new class <-UserDbHandler ->Right click-> the ->package name ->select ->New option-> and click-> java class that will show in above. 
  •  Step6=Step5->WriteName->Ok.
  • if you not understand this  please read step 1.
  • And Write the following code UserDbHandler. java class
package customspinner.alienslab.com.adddata;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by MUhammad zubair on 6/22/2015.
 */
public class UserDbHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="USERINFO.DB";
    private static final int DATABASE_VERSION=5;
    private static final String CREATE_QUERY="CREATE TABLE "+ UserContract.NewUserInfo.TABLE_NAME+"(id INTEGER, "+
            UserContract.NewUserInfo.USER_NAME+" TEXT, "+ UserContract.NewUserInfo.USER_MOB+" TEXT, "
            + UserContract.NewUserInfo.USER_EMAIL+" TEXT );";


    public UserDbHelper(Context context){

      super(context,DATABASE_NAME,null,DATABASE_VERSION);
        Log.e("DATABASE OPERATION", "Database created / opened.....");

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(CREATE_QUERY);
        Log.e("DATABASE OPERATION", "Table create..."+CREATE_QUERY);
    }
    public void addinnformation(String name,String mob,String email,SQLiteDatabase db){

     ContentValues contentValue = new ContentValues();
        contentValue.put(UserContract.NewUserInfo.USER_NAME,name);
        contentValue.put(UserContract.NewUserInfo.USER_MOB,mob);
        contentValue.put(UserContract.NewUserInfo.USER_EMAIL,email);
        db.insert(UserContract.NewUserInfo.TABLE_NAME,null,contentValue);
        Log.e("DATABASE OPERATION", "One row is insert");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

And Write the following code MainACtivity. java class

public class MainActivity extends Activity {

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


    public void sendMessage(View view)
    {
        Intent intent = new Intent(MainActivity.this,NewContactActivity.class);
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Run the Application

This picture consists of three Edit text and a button .when user add information in edit text and click on save button then all the information will saved in database.

Image may be NSFW.
Clik here to view.
Alt Tag android sqlite out image

when you connected the database SQLite.This type of message will show

  • Database is create and open
  • Table is create
  • One row is insert in database

Image may be NSFW.
Clik here to view.
Alt Tag andrid datbase create

 Conclusion

In this lecture we learn about Android SqLite database.And also learn about use of database in application.we will leaen about connection of database and insert data into database and  also create table. I hope you will understand this lecture.Thank you for reading this lecture Hope you got the idea.

The post Android how can add data into SQLite appeared first on The Master World.


Viewing all articles
Browse latest Browse all 10

Trending Articles