How To Make An Object As A Favorite And Add It To Sqlite Database In Android
Android - SQLite Database
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC eastward.t.c
Database - Parcel
The main parcel is android.database.sqlite that contains the classes to manage your own databases
Database - Creation
In order to create a database yous only need to call this method openOrCreateDatabase with your database name and style as a parameter. It returns an instance of SQLite database which you lot accept to receive in your own object.Its syntax is given below
SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,naught);
Apart from this , there are other functions available in the database packet , that does this job. They are listed below
Sr.No | Method & Description |
---|---|
i | openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler) This method only opens the existing database with the appropriate flag mode. The common flags mode could be OPEN_READWRITE OPEN_READONLY |
2 | openDatabase(String path, SQLiteDatabase.CursorFactory mill, int flags) It is similar to the above method as information technology also opens the existing database but it does not define any handler to handle the errors of databases |
3 | openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory) It not only opens but create the database if information technology not exists. This method is equivalent to openDatabase method. |
4 | openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory) This method is similar to to a higher place method but information technology takes the File object as a path rather and then a string. Information technology is equivalent to file.getPath() |
Database - Insertion
we tin can create tabular array or insert data into table using execSQL method defined in SQLiteDatabase class. Its syntax is given below
mydatabase.execSQL("CREATE Table IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password VARCHAR);"); mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Some other method that as well does the same job but take some boosted parameter is given below
Sr.No | Method & Description |
---|---|
1 | execSQL(String sql, Object[] bindArgs) This method non only insert data , merely also used to update or modify already existing data in database using bind arguments |
Database - Fetching
We can think annihilation from database using an object of the Cursor class. We will telephone call a method of this class chosen rawQuery and it will render a resultset with the cursor pointing to the table. We can move the cursor forrard and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",zip); resultSet.moveToFirst(); String username = resultSet.getString(0); String countersign = resultSet.getString(one);
There are other functions available in the Cursor form that allows usa to effectively remember the data. That includes
Sr.No | Method & Description |
---|---|
one | getColumnCount() This method return the total number of columns of the tabular array. |
2 | getColumnIndex(Cord columnName) This method returns the index number of a column by specifying the proper name of the cavalcade |
3 | getColumnName(int columnIndex) This method returns the name of the column past specifying the index of the cavalcade |
4 | getColumnNames() This method returns the assortment of all the column names of the table. |
five | getCount() This method returns the total number of rows in the cursor |
half dozen | getPosition() This method returns the electric current position of the cursor in the table |
7 | isClosed() This method returns true if the cursor is closed and render false otherwise |
Database - Helper class
For managing all the operations related to the database , an helper course has been given and is called SQLiteOpenHelper. It automatically manages the cosmos and update of the database. Its syntax is given below
public class DBHelper extends SQLiteOpenHelper { public DBHelper(){ super(context,DATABASE_NAME,null,1); } public void onCreate(SQLiteDatabase db) {} public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {} }
Example
Here is an instance demonstrating the apply of SQLite Database. It creates a basic contacts applications that allows insertion, deletion and modification of contacts.
To experiment with this example, you lot need to run this on an actual device on which camera is supported.
Steps | Description |
---|---|
1 | You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. |
ii | Modify src/MainActivity.coffee file to get references of all the XML components and populate the contacts on listView. |
three | Create new src/DBHelper.java that volition manage the database piece of work |
4 | Create a new Activity every bit DisplayContact.java that will display the contact on the screen |
5 | Alter the res/layout/activity_main to add respective XML components |
6 | Modify the res/layout/activity_display_contact.xml to add respective XML components |
vii | Modify the res/values/string.xml to add necessary string components |
8 | Change the res/menu/display_contact.xml to add necessary menu components |
9 | Create a new card as res/carte/mainmenu.xml to add the insert contact selection |
ten | Run the awarding and choose a running android device and install the application on it and verify the results. |
Following is the content of the modified MainActivity.coffee.
parcel com.example.sairamkrishna.myapplication; import android.content.Context; import android.content.Intent; import android.back up.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import java.util.ArrayList; import java.util.Listing; public class MainActivity extends ActionBarActivity { public final static Cord EXTRA_MESSAGE = "MESSAGE"; private ListView obj; DBHelper mydb; @Override protected void onCreate(Package savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydb = new DBHelper(this); ArrayList array_list = mydb.getAllCotacts(); ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list); obj = (ListView)findViewById(R.id.listView1); obj.setAdapter(arrayAdapter); obj.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) { // TODO Car-generated method stub int id_To_Search = arg2 + 1; Bundle dataBundle = new Bundle(); dataBundle.putInt("id", id_To_Search); Intent intent = new Intent(getApplicationContext(),DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the bill of fare; this adds items to the activeness bar if information technology is nowadays. getMenuInflater().inflate(R.carte du jour.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem detail){ super.onOptionsItemSelected(particular); switch(particular.getItemId()) { instance R.id.item1:Bundle dataBundle = new Package(); dataBundle.putInt("id", 0); Intent intent = new Intent(getApplicationContext(),DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); return true; default: return super.onOptionsItemSelected(particular); } } public boolean onKeyDown(int keycode, KeyEvent event) { if (keycode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(truthful); } render super.onKeyDown(keycode, outcome); } }
Following is the modified content of display contact activity DisplayContact.java
package com.example.sairamkrishna.myapplication; import android.bone.Package; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class DisplayContact extends Activity { int from_Where_I_Am_Coming = 0; private DBHelper mydb ; TextView proper noun ; TextView phone; TextView email; TextView street; TextView place; int id_To_Update = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_contact); proper name = (TextView) findViewById(R.id.editTextName); phone = (TextView) findViewById(R.id.editTextPhone); email = (TextView) findViewById(R.id.editTextStreet); street = (TextView) findViewById(R.id.editTextEmail); place = (TextView) findViewById(R.id.editTextCity); mydb = new DBHelper(this); Bundle extras = getIntent().getExtras(); if(extras !=nada) { int Value = extras.getInt("id"); if(Value>0){ //means this is the view part not the add contact part. Cursor rs = mydb.getData(Value); id_To_Update = Value; rs.moveToFirst(); String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME)); String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE)); String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL)); String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET)); String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY)); if (!rs.isClosed()) { rs.close(); } Button b = (Button)findViewById(R.id.button1); b.setVisibility(View.INVISIBLE); name.setText((CharSequence)nam); name.setFocusable(false); name.setClickable(false); phone.setText((CharSequence)phon); telephone.setFocusable(imitation); phone.setClickable(false); email.setText((CharSequence)emai); e-mail.setFocusable(false); email.setClickable(simulated); street.setText((CharSequence)stree); street.setFocusable(false); street.setClickable(false); place.setText((CharSequence)plac); identify.setFocusable(imitation); place.setClickable(false); } } } @Override public boolean onCreateOptionsMenu(Carte menu) { // Inflate the menu; this adds items to the action bar if information technology is present. Parcel extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ getMenuInflater().inflate(R.menu.display_contact, menu); } else{ getMenuInflater().inflate(R.carte du jour.menu_main carte du jour); } } render true; } public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(particular); switch(item.getItemId()) { example R.id.Edit_Contact: Button b = (Button)findViewById(R.id.button1); b.setVisibility(View.VISIBLE); name.setEnabled(true); proper noun.setFocusableInTouchMode(true); name.setClickable(true); phone.setEnabled(true); phone.setFocusableInTouchMode(true); phone.setClickable(truthful); email.setEnabled(true); electronic mail.setFocusableInTouchMode(true); email.setClickable(true); street.setEnabled(true); street.setFocusableInTouchMode(true); street.setClickable(true); identify.setEnabled(true); identify.setFocusableInTouchMode(truthful); place.setClickable(true); return truthful; case R.id.Delete_Contact: AlertDialog.Builder builder = new AlertDialog.Builder(this); architect.setMessage(R.string.deleteContact) .setPositiveButton(R.cord.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mydb.deleteContact(id_To_Update); Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).testify(); Intent intent = new Intent(getApplicationContext(),MainActivity.form); startActivity(intent); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog d = architect.create(); d.setTitle("Are you sure"); d.show(); return true; default: return super.onOptionsItemSelected(item); } } public void run(View view) { Bundle extras = getIntent().getExtras(); if(extras !=zippo) { int Value = extras.getInt("id"); if(Value>0){ if(mydb.updateContact(id_To_Update,proper noun.getText().toString(), telephone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){ Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(),MainActivity.course); startActivity(intent); } else{ Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).bear witness(); } } else{ if(mydb.insertContact(proper noun.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){ Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(getApplicationContext(), "not washed", Toast.LENGTH_SHORT).evidence(); } Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } } } }
Post-obit is the content of Database form DBHelper.java
package com.example.sairamkrishna.myapplication; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; public class DBHelper extends SQLiteOpenHelper { public static concluding String DATABASE_NAME = "MyDBName.db"; public static final String CONTACTS_TABLE_NAME = "contacts"; public static final String CONTACTS_COLUMN_ID = "id"; public static final Cord CONTACTS_COLUMN_NAME = "proper noun"; public static final String CONTACTS_COLUMN_EMAIL = "email"; public static final String CONTACTS_COLUMN_STREET = "street"; public static final Cord CONTACTS_COLUMN_CITY = "identify"; public static final String CONTACTS_COLUMN_PHONE = "phone"; individual HashMap hp; public DBHelper(Context context) { super(context, DATABASE_NAME , null, 1); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL( "create table contacts " + "(id integer primary key, name text,phone text,email text, street text,identify text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Car-generated method stub db.execSQL("DROP TABLE IF EXISTS contacts"); onCreate(db); } public boolean insertContact (String proper noun, String phone, String email, String street,String place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("proper name", name); contentValues.put("phone", phone); contentValues.put("email", e-mail); contentValues.put("street", street); contentValues.put("place", place); db.insert("contacts", nada, contentValues); render true; } public Cursor getData(int id) { SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts where id="+id+"", zero ); render res; } public int numberOfRows(){ SQLiteDatabase db = this.getReadableDatabase(); int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME); return numRows; } public boolean updateContact (Integer id, String proper name, String telephone, String electronic mail, String street,Cord place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", proper noun); contentValues.put("telephone", phone); contentValues.put("email", e-mail); contentValues.put("street", street); contentValues.put("identify", identify); db.update("contacts", contentValues, "id = ? ", new Cord[] { Integer.toString(id) } ); render true; } public Integer deleteContact (Integer id) { SQLiteDatabase db = this.getWritableDatabase(); return db.delete("contacts", "id = ? ", new String[] { Integer.toString(id) }); } public ArrayList<String> getAllCotacts() { ArrayList<String> array_list = new ArrayList<String>(); //hp = new HashMap(); SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts", nada ); res.moveToFirst(); while(res.isAfterLast() == false){ array_list.add together(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME))); res.moveToNext(); } return array_list; } }
Following is the content of the res/layout/activity_main.xml
<?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:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" android:layout_alignParentTop="truthful" android:layout_centerHorizontal="true" android:textSize="30dp" android:text="Data Base" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorials Indicate" android:id="@+id/textView2" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:textSize="35dp" android:textColor="#ff16ff01" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:layout_below="@+id/textView2" android:layout_centerHorizontal="true" android:src="@drawable/logo"/> <ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/scrollView" android:layout_below="@+id/imageView" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true"> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" > </ListView> </ScrollView> </RelativeLayout>
Post-obit is the content of the res/layout/activity_display_contact.xml
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/scrollView1" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context=".DisplayContact" > <RelativeLayout android:layout_width="match_parent" android:layout_height="370dp" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"> <EditText android:id="@+id/editTextName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="truthful" android:layout_marginTop="5dp" android:layout_marginLeft="82dp" android:ems="10" android:inputType="text" > </EditText> <EditText android:id="@+id/editTextEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextStreet" android:layout_below="@+id/editTextStreet" android:layout_marginTop="22dp" android:ems="10" android:inputType="textEmailAddress" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editTextName" android:layout_alignParentLeft="truthful" android:text="@string/proper noun" android:textAppearance="?android:attr/textAppearanceMedium" /> <Push android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextCity" android:layout_alignParentBottom="truthful" android:layout_marginBottom="28dp" android:onClick="run" android:text="@string/save" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editTextEmail" android:layout_alignLeft="@+id/textView1" android:text="@string/e-mail" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editTextPhone" android:layout_alignLeft="@+id/textView1" android:text="@string/phone" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/editTextEmail" android:layout_alignLeft="@+id/textView5" android:text="@string/street" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editTextCity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/editTextName" android:layout_below="@+id/editTextEmail" android:layout_marginTop="30dp" android:european monetary system="10" android:inputType="text" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editTextCity" android:layout_alignBottom="@+id/editTextCity" android:layout_alignParentLeft="truthful" android:layout_toLeftOf="@+id/editTextEmail" android:text="@string/country" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editTextStreet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextName" android:layout_below="@+id/editTextPhone" android:european monetary system="x" android:inputType="text" > <requestFocus /> </EditText> <EditText android:id="@+id/editTextPhone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextStreet" android:layout_below="@+id/editTextName" android:ems="10" android:inputType="phone|text" /> </RelativeLayout> </ScrollView>
Following is the content of the res/value/string.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string proper noun="app_name">Accost Book</string> <cord name="action_settings">Settings</string> <string name="hello_world">Hullo world!</string> <cord name="Add_New">Add together New</string> <string name="edit">Edit Contact</string> <string name="delete">Delete Contact</string> <string name="title_activity_display_contact">DisplayContact</string> <string proper noun="proper name">Name</string> <string name="phone">Phone</string> <string name="email">Email</string> <string name="street">Street</cord> <string proper noun="land">City/Country/Zip</cord> <string name="relieve">Save Contact</string> <cord name="deleteContact">Are yous certain, you want to delete information technology.</string> <string name="yes">Yes</string> <string name="no">No</cord> </resources>
Following is the content of the res/menu/main_menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/item1" android:icon="@drawable/add" android:title="@string/Add_New" > </item> </menu>
Following is the content of the res/menu/display_contact.xml
<?xml version="1.0" encoding="utf-8"?> <bill of fare xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/Edit_Contact" android:orderInCategory="100" android:title="@cord/edit"/> <detail android:id="@+id/Delete_Contact" android:orderInCategory="100" android:title="@string/delete"/> </menu>
This is the defualt AndroidManifest.xml of this project
<?xml version="ane.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.instance.sairamkrishna.myapplication" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@fashion/AppTheme" > <activity android:proper noun=".MainActivity" android:label="@cord/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:proper noun="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:proper noun=".DisplayContact"/> </application> </manifest>
Allow'southward endeavor to run your application. I assume yous have connected your actual Android Mobile device with your estimator. To run the app from Android studio , open one of your projection's action files and click Run icon from the tool bar. Before starting your awarding,Android studio will display following window to select an option where you desire to run your Android application.
Select your mobile device as an option and then bank check your mobile device which will brandish following screen −
Now open your optional menu, it will show as below epitome: Optional menu appears unlike places on unlike versions
Click on the add together push of the menu screen to add together a new contact. It will brandish the following screen −
It will display the following fields. Delight enter the required information and click on save contact. Information technology will bring yous back to main screen.
At present our contact sai has been added.In order to see that where is your database is created. Open your android studio, connect your mobile. Go tools/android/android device monitor. At present browse the file explorer tab. Now browse this folder /data/data/<your.package.proper name>/databases<database-name>.
How To Make An Object As A Favorite And Add It To Sqlite Database In Android,
Source: https://www.tutorialspoint.com/android/android_sqlite_database.htm
Posted by: baileyolonstake.blogspot.com
0 Response to "How To Make An Object As A Favorite And Add It To Sqlite Database In Android"
Post a Comment