1 works

Storing data in SQLite Database in android


dashboard+ Project

Posted by @Awais malik #android #java

Step 0: First of all we create a Class and extend it from SQLiteOpenHelper Class and create database

public class LocalDatabase extends SQLiteOpenHelper {
         
    private static final String mDatabaseName = "LocalDatabase";
    private static final int mDatabaseVersion = 1;

public LocalDatabase(Context context) {
        super(context, mDatabaseName, null, mDatabaseVersion);
        SQLiteDatabase db = this.getWritableDatabase();
    }      

}
content_copyCopy to Clipboard

Step 1: Now we override onCreate and onUpgrade methods and create table in our database here i am creating a table for storing profiles #Remember this code will reside in the class which we created in step 1

    //Profile Table
    public static final String TABLE_profile = "profile";
    //Profile Table Columns
    public static final String COLUMN_pID = "profileID";
    public static final String COLUMN_pName = "profileName";
    public static final String COLUMN_uName = "userName";

 @Override
    public void onCreate(SQLiteDatabase db) {
        //profile Table
        String profileTableQuery =
                " CREATE TABLE  " + TABLE_profile
                        + "( "
                        + COLUMN_pID + "  INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE , "
                        + COLUMN_pName + "   TEXT NOT NULL , "
                        + COLUMN_uName + "   TEXT NOT NULL "
                        + " );";
        db.execSQL(profileTableQuery);
}
 @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS "+TABLE_profile);
        onCreate(db);

    }
content_copyCopy to Clipboard

Step 2: As our table is created in database now we store data into that table for that purpose i am creating a method named as addProfile

  public boolean addProfile( ProfileDTO profileDTO ){


        ContentValues values = new ContentValues();
        SQLiteDatabase db = getWritableDatabase();

        //inserting data
        values.put(COLUMN_pName, profileDTO.getpName());
        values.put(COLUMN_uName, profileDTO.getuName());

        Log.d("1" , "Addind"+profileDTO.getpName()+"to"+TABLE_profile);

        long res = db.insert(TABLE_profile , null , values);
        db.close();
        if(res == -1){
            return false;
        }else{
            return true;
        }

    }
content_copyCopy to Clipboard

Step 3: Now we create DTO Class for passing data to Database Class

public class ProfileDTO {

 public  ProfileDTO(){}

    //Variables
    private String uName;
    private String pName;

    public String getuName() {
        return uName;
    }

    public void setpName(String uName) {
        this.uName = uName;
    }

    public void setpName(String pName) {
        this.pName = pName;
    }

    public String getpName() {
        return pName;
    }
}
content_copyCopy to Clipboard

Step 4: Now Let suppose we created an activity which ask user to provide userName and profileName and when user click button it stores data into database we will do it as follow Assume user already created activity if you didn't created yet then create it. Let suppose activity name is MyProfile


public class MyProfile extends AppCompatActivity {


    private LocalDatabase localDatabase;
    private EditText mProfileName;
    private EditText mUserName;
    private Button mConfirmButton;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_profile);

        mProfileName = findViewById(R.id.profileName);
        mUserName = findViewById(R.id.userName);
        mConfirmButton = findViewById(R.id.confirmButton);
        localDatabase = new LocalDatabase(this);

        mConfirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

         //exception handling
             
                try {

                    if(mProfileName.getText().toString().trim().isEmpty()){
                        Toast.makeText(getApplicationContext() , "Enter profile name" , Toast.LENGTH_SHORT).show();
                    }else if(mUserName.getText().toString().trim().isEmpty()){
                        Toast.makeText(getApplicationContext() , "Enter user name" , Toast.LENGTH_SHORT).show();
                    }else{

                        profileDTO.setpName(mProfileName.getText().toString());
                        profileDTO.setuName(mUserName.getText().toString());
                        if(localDatabase.addProfile(profileDTO)){
                            Toast.makeText(getApplicationContext(),"Profile created",Toast.LENGTH_SHORT ).show();
       
                        }
                    }
                    

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

   }
}
content_copyCopy to Clipboard

In this tutorial we learn about how to create local Database in android using SQLite and store values in it

,

>> Browse more code snippets

more_vert