Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Saving information in database in Android

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 152
    Comment on it

    Storing record in database using Sqlite Helper class.
    We have taken Name, Age and City as input from user and saving them on click of Save button in database.

    MainActivity.java

    public class MainActivity extends Activity {
        CreateDatabase db;
        private EditText nameEditText;
        private EditText ageEditText;
        private EditText cityEditText;
        private TextView nameTextView;
        private TextView ageTextView;
        private TextView cityTextView;
        private String name = "";
        private String age = "";
        private String city = "";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            db = new CreateDatabase(MainActivity.this);
            initControls();
    
        }
    
        /**
         * Defining widgets controls
         */
        private void initControls(){
            nameEditText = (EditText) findViewById(R.id.NameEditText);
            ageEditText = (EditText) findViewById(R.id.AgeEditText);
            cityEditText = (EditText) findViewById(R.id.CityEditText);
            nameTextView = (TextView) findViewById(R.id.NameTextView);
            ageTextView = (TextView) findViewById(R.id.AgeTextView);
            cityTextView = (TextView) findViewById(R.id.CityTextView);
    
            findViewById(R.id.SaveButton).setOnClickListener(buttonClick);
    
            errorDismiss();
        }
    
        /**
         * Button click listeners
         */
        View.OnClickListener buttonClick = new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
                hideKeyboard();
                int id = v.getId();
                if(id == R.id.SaveButton){
                    saveButtonClick();
                }
    
            }
        };
    
        /**
         * Getting values from edittext and saving them in database.
         */
        private void saveButtonClick(){
            String nameVal = nameEditText.getText().toString();
            String ageVal = ageEditText.getText().toString();
            String cityVal = cityEditText.getText().toString();
            if(nameVal.trim().length()==0){
                nameEditText.setError(getString(R.string.name_error));
            }else if(ageVal.trim().length()==0){
                ageEditText.setError(getString(R.string.age_error));
            }else if(cityVal.trim().length()==0){
                cityEditText.setError(getString(R.string.city_error));
            }else{
                db.open();
                db.createElementsDetail(nameVal, cityVal, ageVal);
                db.close();
                Toast.makeText(MainActivity.this, "Record saved successfully", Toast.LENGTH_SHORT).show();
                nameEditText.setText("");
                ageEditText.setText("");
                cityEditText.setText("");
                nameTextView.setText("");
                ageTextView.setText("");
                cityTextView.setText("");
            }
        }
    
        /**
         * Validating blank fields
         */
        private void errorDismiss(){
            nameEditText.addTextChangedListener(new TextWatcher() {
    
                @Override
                public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                }
    
                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                              int arg3) {
                }
    
                @Override
                public void afterTextChanged(Editable arg0) {
                    nameEditText.setError(null);
                }
            });
    
            ageEditText.addTextChangedListener(new TextWatcher() {
    
                @Override
                public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                }
    
                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                              int arg3) {
                }
    
                @Override
                public void afterTextChanged(Editable arg0) {
                    ageEditText.setError(null);
                }
            });
    
            cityEditText.addTextChangedListener(new TextWatcher() {
    
                @Override
                public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                }
    
                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                              int arg3) {
                }
    
                @Override
                public void afterTextChanged(Editable arg0) {
                    cityEditText.setError(null);
                }
            });
        }
    
        // Hide keyboard
        public void hideKeyboard() {
            //start with an 'always hidden' command for the activity's window
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            //now tell the IMM to hide the keyboard FROM whatever has focus in the activity
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            View currentFocusedView = getCurrentFocus();
            if(currentFocusedView != null) {
                inputMethodManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), 0);
            }
        }
    }
    
    

    Database class to handle create database, create table and save record in database.
    CreateDatabase.java

    public class CreateDatabase {
    
        public DatabaseHelper mDbHelper;
        public SQLiteDatabase mDb;  
        public static final String DATABASE_NAME= "Detail_database";    // Internal Database
    //    public static final String DATABASE_NAME= Environment.getExternalStorageDirectory()+File.separator+"Detail_database.sqlite";      //External Database
        public static final String TAG = "tag";
        public static final int DATABASE_VERSION = 1;
    
        public static final String Id = "id";
    
        // Definition for Detail Table
        public static final String Key = "key";
        public static final String Name = "name";
        public static final String City = "city";
        public static final String Age = "age";
        public static final String DATABASE_TABLE_DETAIL = "DETAIL";
    
        /** * Database creation sql statement */
    
        //Detail Table creation
        private static final String DATABASE_CREATE_DETAIL = "CREATE TABLE IF NOT EXISTS "
                + DATABASE_TABLE_DETAIL + " (Key INTEGER PRIMARY KEY AUTOINCREMENT, "+" Name text, "+" City text" +
                ", "+" Age text)";
    
    
        private final Context mCtx;
    
        private static class DatabaseHelper extends SQLiteOpenHelper {
            DatabaseHelper(Context context) { 
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }
    
            /**
             * Creating Tables
             */
    
            @Override
            public void onCreate(SQLiteDatabase db) {
                try{
                    db.execSQL(DATABASE_CREATE_DETAIL);
    
                    Log.i(TAG, "DATABASE IS CREATING.............");
                }
                catch(SQLException e){
    
                }
            }
    
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                //  String alter_Query = "ALTER TABLE AREA ADD COLUMN Comment text";
                //  db.execSQL(alter_Query);
    
            }
        }
        public CreateDatabase(Context ctx) {
    
            this.mCtx = ctx;
        }
    
        public void DeleteDatabase(String table)
        {
            mDb.delete(table, null, null);   
        }
    
        public void DeleteDatabaseContent(String table){
            String query = "DELETE FROM " + table;
            mDb.execSQL(query);
        }
    
        public void DeleteLastRecord(String key)
        {
            String selection = "Key = ?";
            String[] selectionArgs = new String[]{key};
            mDb.delete(DATABASE_TABLE_DETAIL, selection, selectionArgs);
        }
    
        public CreateDatabase open() throws SQLException {
    
            //  Log.i(TAG, "OPening DataBase Connection....");
            mDbHelper = new DatabaseHelper(mCtx);
            mDb = mDbHelper.getWritableDatabase();
            return this;
        }
    
        public SQLiteDatabase openDB() throws SQLException{
            //  Log.i(TAG, "OPening DataBase Connection....");
            mDbHelper = new DatabaseHelper(mCtx);
            mDb = mDbHelper.getWritableDatabase();
            return mDb;
        }
        public void close() {
            //  Log.i(TAG, "Closing DataBase Connection....");
            mDbHelper.close();
    
        }
    
        // Inserting record values for Detail
        public long createElementsDetail(String name, String city, String age) {
            //  Log.i(TAG, "Inserting Detail   ...");
    
            ContentValues initialValues = new ContentValues();
            initialValues.put(Name, name);
            initialValues.put(City, city);
            initialValues.put(Age, age);
    
            return mDb.insert(DATABASE_TABLE_DETAIL, null, initialValues);
        }
    
        /**
         * Cursor for Detail
         * @return
         * @throws android.database.SQLException
         */
        public Cursor fetchDetail() throws SQLException{
            Cursor mCursor = mDb.query(DATABASE_TABLE_DETAIL, new String[] {Key, Name, City, Age},null,null,null,null,null);
            if (mCursor != null) {
                mCursor.moveToFirst();
            }
            return mCursor;
        }
    }
    

    This is the layout file for the above Main Activity
    activity_main.xml

    <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="${relativePackage}.${activityClass}" >
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:padding="10dp"
            android:text="@string/title"
            android:textSize="18sp" />
    
        <EditText
            android:id="@+id/NameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="5dp"
            android:hint="@string/name"
            android:singleLine="true" />
    
        <EditText
            android:id="@+id/AgeEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="5dp"
            android:hint="@string/age"
            android:inputType="numberSigned"
            android:singleLine="true" />
    
        <EditText
            android:id="@+id/CityEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="5dp"
            android:hint="@string/city"
            android:singleLine="true" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:gravity="center_horizontal"
            android:orientation="horizontal"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp">
    
            <Button
                android:id="@+id/SaveButton"
                android:layout_width="90dp"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:text="@string/save"
                android:textColor="@android:color/black" />
    
    
        </LinearLayout>
    
        <TextView
            android:id="@+id/NameTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp" />
    
        <TextView
            android:id="@+id/AgeTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp" />
    
        <TextView
            android:id="@+id/CityTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp" />
    
    </LinearLayout>
    

    This is the strings file
    strings.xml

     <string name="name">Enter name</string>
    <string name="age">Enter age</string>
    <string name="city">Enter city</string>
    <string name="save">Save</string>
    <string name="fetch_data">Fetch data</string>
    <string name="delete">Delete</string>
    <string name="name_error">Please enter name.</string>
    <string name="age_error">Please enter age.</string>
    <string name="city_error">Please enter city.</string>
    

    This is the manifest file
    manifest.xml

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: