Android allows us to store data in various ways. Refer this Android Data Storage. If you want to store small amount of data then Shared Preferences can be used. SQLite Database is used to store related or unrelated data, takes small amount of disk space.
SQLite Database implementation-
Let's take an example where we store student name and roll no in student table and show all the students name on a list.
1. Create a new project in android studio.
2. We need to have a Student class with a constructor and getter/setter methods for all the data members. So, add a new java class Student.java .
7. Now, open NameActivity.java and type the following code-


SQLite Database implementation-
Let's take an example where we store student name and roll no in student table and show all the students name on a list.
1. Create a new project in android studio.
2. We need to have a Student class with a constructor and getter/setter methods for all the data members. So, add a new java class Student.java .
public class Student { String name; int rollNo; public Student(String name, int rollNo) { this.name = name; this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } }3. Open activity_main.xml , add two edit text and one add button, one show all button like this-
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp"> <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Student Name" android:layout_marginBottom="30dp"/> <EditText android:id="@+id/et_roll" android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="number" android:hint="Roll No." android:layout_marginBottom="30dp"/> <Button android:id="@+id/bt_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add" android:layout_gravity="center" android:layout_marginBottom="30dp"/> <Button android:id="@+id/bt_showAll" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show all" android:layout_gravity="center"/> </LinearLayout>4. Add new activity NameActivity and open its xml file (activity_name.xml) and add a listView-
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_name" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.gunjan.andriodcodesnippets.NameActivity"> <ListView android:id="@+id/lv_names" android:layout_width="match_parent" android:layout_height="wrap_content"></ListView> </RelativeLayout>5.Create a new java class DBHelper.java. This class will have all the database operations.
- Implement SQLiteOpenHelper and override onCreate() and onUpgrade() methods. onCreate() method is called when database is created. Here, we execute sql command to create tables. onUpgrade() method is called when databse is upgraded.
public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME="SQLiteDemo.db"; //Student table variables public static final String TABLE_NAME="student"; public static final String COLUMN_STUDENT_ID="studentID"; public static final String COLUMN_NAME="name"; public static final String COLUMN_ROLL_NO="roll"; public DBHelper(Context context) { super(context, DATABASE_NAME, null, 1); } //Create Table **STUDENT**. @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE student"+ "(studentID INTEGER PRIMARY KEY,name text,roll INTEGER)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS student"); onCreate(db); } }
- Implement insert,read, delete, update operations.
public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME="SQLiteDemo.db"; //Student table variables public static final String TABLE_NAME="student"; public static final String COLUMN_STUDENT_ID="studentID"; public static final String COLUMN_NAME="name"; public static final String COLUMN_ROLL_NO="roll"; public DBHelper(Context context) { super(context, DATABASE_NAME, null, 1); } //Create Table **STUDENT**. @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE student"+ "(studentID INTEGER PRIMARY KEY,name text,roll INTEGER)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS student"); onCreate(db); } //Insert new student in database. public boolean insertStudent(String name,int rollNo){ try{ SQLiteDatabase db=this.getWritableDatabase(); ContentValues contentValues=new ContentValues(); contentValues.put(COLUMN_NAME,name); contentValues.put(COLUMN_ROLL_NO,rollNo); db.insert(TABLE_NAME,null,contentValues); db.close(); return true; }catch (Exception e){ e.printStackTrace(); return false; } } //Update name of a particular student in database. public boolean updateName(String name,int studentID){ try{ SQLiteDatabase db=this.getWritableDatabase(); ContentValues contentValues=new ContentValues(); contentValues.put(COLUMN_NAME,name); db.update(TABLE_NAME,contentValues,"studentID="+studentID,null); db.close(); return true; }catch (Exception e){ e.printStackTrace(); return false; } } //Delete a student. public boolean deleteStudent(int studentID){ try{ SQLiteDatabase db=this.getWritableDatabase(); db.delete(TABLE_NAME,COLUMN_STUDENT_ID+"="+studentID,null); db.close(); return true; }catch (Exception e){ e.printStackTrace(); return false; } } //Get all the details from database. public ArrayList<Student> getAllDetails(){ ArrayList<Student> studentArrayList=new ArrayList<>(); try{ SQLiteDatabase db=this.getReadableDatabase(); Cursor result=db.rawQuery("SELECT name,roll FROM student",null); if(result.getCount()>0){ result.moveToFirst(); do{ String name=result.getString(result.getColumnIndex(COLUMN_NAME)); int roll=result.getInt(result.getColumnIndex(COLUMN_ROLL_NO)); studentArrayList.add(new Student(name,roll)); }while (result.moveToNext()); } db.close(); }catch (Exception e){ e.printStackTrace(); } return studentArrayList; } //Get all the students name from database. public ArrayList<String> getNames(){ ArrayList<String> names=new ArrayList<>(); try{ SQLiteDatabase db=this.getReadableDatabase(); Cursor result=db.rawQuery("SELECT name,roll FROM student",null); if(result.getCount()>0){ result.moveToFirst(); do{ String name=result.getString(result.getColumnIndex(COLUMN_NAME)); names.add(name); }while (result.moveToNext()); } db.close(); }catch (Exception e){ e.printStackTrace(); } return names; } }6. Now , open MainActivity.java and type the following code-
public class Main2Activity extends AppCompatActivity { EditText et_name; EditText et_roll; Button bt_add,bt_showAll; String name; int rollNo; DBHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); dbHelper=new DBHelper(this); et_name=(EditText)findViewById(R.id.et_name); et_roll=(EditText)findViewById(R.id.et_roll); bt_add=(Button)findViewById(R.id.bt_add); bt_showAll=(Button)findViewById(R.id.bt_showAll); bt_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { name=et_name.getText().toString(); rollNo=Integer.valueOf(et_roll.getText().toString()); //Insert values into database dbHelper.insertStudent(name,rollNo); Toast.makeText(getApplicationContext(),"Student Added",Toast.LENGTH_LONG).show(); } }); bt_showAll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Open NameActivity to show all names. Intent intent=new Intent(Main2Activity.this, NameActivity.class); startActivity(intent); } }); }}
7. Now, open NameActivity.java and type the following code-
public class NameActivity extends AppCompatActivity { ListView lv_names; ArrayList<String> arrayListNames; ArrayAdapter<String> arrayAdapterNames; DBHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_name); dbHelper=new DBHelper(this); lv_names=(ListView)findViewById(R.id.lv_names); arrayListNames=new ArrayList<>(); getAllNames(); arrayAdapterNames=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayListNames); lv_names.setAdapter(arrayAdapterNames); } private void getAllNames() { arrayListNames=dbHelper.getNames(); } }8. Run the project.


Comments
Post a Comment