how to insert data in sqlite
database in android studio
Today's article discusses how
to insert data in the SQLite database in an android studio. SQLite database is storing a local
database using an android studio. So let's start how to insert data in the SQLite
database in the android studio. Using an Editext button in layout. This example
a student information store an SQLite database
in android studio step by step activity
follows in the tutorial so let's start a how
to insert data in SQLite database in android studio .
1. MainActivity.java :
import
android.content.ContentValues;
import
android.content.Intent;
import
android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import
android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import
android.view.MenuItem;
import android.view.View;
import
android.widget.Button;
import
android.widget.EditText;
import
android.widget.TextView;
import android.widget.Toast;
public class MainActivity
extends ActionBarActivity {
DBController controller = new
DBController(this);
Button add, view, update, delete;
EditText placeid, place, country;
TextView infotext;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
placeid = (EditText)
findViewById(R.id.edplaceid);
place = (EditText)
findViewById(R.id.edplace);
country = (EditText)
findViewById(R.id.edcountry);
add = (Button)
findViewById(R.id.btnadd);
update = (Button)
findViewById(R.id.btnupdate);
delete = (Button)
findViewById(R.id.btndelete);
view = (Button)
findViewById(R.id.btnview);
infotext = (TextView) findViewById(R.id.txtresulttext);
view.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new
Intent(MainActivity.this, PlacesList.class);
startActivity(i);
}
});
add.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if
(place.getText().toString().trim().equals("") || country.getText().toString().trim().equals(""))
{
infotext.setText("Please insert place name and country..");
} else {
controller = new
DBController(getApplicationContext());
SQLiteDatabase db =
controller.getWritableDatabase();
ContentValues cv = new
ContentValues();
cv.put("place", place.getText().toString());
cv.put("country", country.getText().toString());
db.insert("places", null, cv);
db.close();
infotext.setText("Place added Successfully");
}
} catch (Exception ex) {
infotext.setText(ex.getMessage().toString());
}
}
});
update.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if
((place.getText().toString().trim().equals("") &&
country.getText().toString().trim().equals("")) ||
placeid.getText().toString().trim().equals("")) {
infotext.setText("Please insert values to update..");
} else {
controller = new
DBController(getApplicationContext());
SQLiteDatabase db =
controller.getWritableDatabase();
ContentValues cv = new
ContentValues();
cv.put("place",
place.getText().toString());
cv.put("country", country.getText().toString());
db.update("places", cv, "id=" +
placeid.getText().toString(), null);
Toast.makeText(MainActivity.this,
"Updated
successfully", Toast.LENGTH_SHORT)
.show();
infotext.setText("Updated Successfully");
}
} catch (Exception ex) {
infotext.setText(ex.getMessage().toString());
}
}
});
delete.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if
(placeid.getText().toString().trim().equals("")) {
infotext.setText("Please insert place ID to delete..");
} else {
controller = new
DBController(getApplicationContext());
SQLiteDatabase db =
controller.getWritableDatabase();
db.delete("places", "id=" +
placeid.getText().toString(), null);
Toast.makeText(MainActivity.this,
"deleted
successfully", Toast.LENGTH_SHORT)
.show();
infotext.setText("Deleted Successfully");
}
} catch (Exception ex) {
infotext.setText(ex.getMessage().toString());
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu
menu) {
//
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean
onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//if (id == R.id.action_settings) {
return true;
}
//return
super.onOptionsItemSelected(item);
}
1. DBController.java :
import
android.content.Context;
import
android.database.Cursor;
import
android.database.sqlite.SQLiteDatabase;
import
android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.HashMap;
public class DBController
extends SQLiteOpenHelper {
private static final String tablename =
"places"; // tablename
private static final String place =
"place"; // column name
private static final String id =
"ID"; // auto generated ID
column
private static final String country =
"country"; // column name
private static final String databasename =
"placesinfo"; // Dtabasename
private static final int versioncode = 1;
//versioncode of the database
public DBController(Context context) {
super(context, databasename, null,
versioncode);
}
@Override
public void onCreate(SQLiteDatabase
database) {
String query;
query = "CREATE TABLE IF NOT
EXISTS " + tablename + "(" + id + " integer primary key,
" + place + " text, " + country + " text)";
database.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase database,
int version_old,
int current_version)
{
String query;
query = "DROP TABLE IF EXISTS
" + tablename;
database.execSQL(query);
onCreate(database);
}
public ArrayList<HashMap<String,
String>> getAllPlace() {
ArrayList<HashMap<String,
String>> wordList;
wordList = new
ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM " + tablename;
SQLiteDatabase database =
this.getWritableDatabase();
Cursor cursor =
database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String>
map = new HashMap<String, String>();
map.put("id",
cursor.getString(0));
map.put("place",
cursor.getString(1));
map.put("country",
cursor.getString(2));
wordList.add(map);
} while (cursor.moveToNext());
}
// return contact list
return wordList;
}
}
3.
PlacesList.java :
import android.os.Bundle;
import
android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import
android.view.MenuItem;
import
android.widget.ListView;
import
android.widget.SimpleAdapter;
import
android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class PlacesList
extends ActionBarActivity {
DBController controller = new
DBController(this);
ListView ls;
TextView infotext;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.placeslist);
ls = (ListView)
findViewById(R.id.placeslist);
infotext = (TextView)
findViewById(R.id.txtresulttext);
try {
List<HashMap<String,
String>> data = controller.getAllPlace();
if (data.size() != 0) {
// Srno, RMCode, Fileno, Loc,
FileDesc, TAGNos
SimpleAdapter adapter = new
SimpleAdapter(
PlacesList.this, data,
R.layout.rows,
new
String[]{"id", "place", "country"}, new int[]{
R.id.txtplaceid,
R.id.txtplacename,
R.id.txtcountry});
ls.setAdapter(adapter);
String length =
String.valueOf(data.size());
infotext.setText(length +
" places");
} else {
infotext.setText("No data
in database");
}
} catch (Exception ex) {
infotext.setText(ex.getMessage().toString());
}
}
@Override
public boolean onCreateOptionsMenu(Menu
menu) {
//
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean
onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//if (id == R.id.action_settings) {
return true;
}
// return
super.onOptionsItemSelected(item);
}
Create a layout files:
1.activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="7"
android:background="#ffb6ffb0">
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_margin="5dp"
android:gravity="center_horizontal"
android:text="PLACES TO VISIT : "
android:textSize="25sp"
android:textStyle="italic|normal" />
<EditText
android:id="@+id/edplaceid"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_margin="5dp"
android:hint="PLACE ID" />
<EditText
android:id="@+id/edplace"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_margin="5dp"
android:hint="PLACE NAME" />
<EditText
android:id="@+id/edcountry"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_margin="5dp"
android:hint="COUNTRY" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.8"
android:orientation="horizontal"
android:weightSum="3">
<Button
android:id="@+id/btnadd"
android:layout_width="0dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#ffff2f5d"
android:textColor="#fff"
android:textSize="20sp"
android:text="ADD" />
<Button
android:id="@+id/btnupdate"
android:layout_width="0dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#ffff2f5d"
android:textColor="#fff"
android:textSize="20sp"
android:text="UPDATE" />
<Button
android:id="@+id/btndelete"
android:layout_width="0dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#ffff2f5d"
android:textColor="#fff"
android:textSize="20sp"
android:text="DELETE" />
</LinearLayout>
<Button
android:id="@+id/btnview"
android:layout_width="match_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_height="0dp"
android:layout_weight="0.8"
android:background="#ff2b84ff"
android:textColor="#fff"
android:textSize="20sp"
android:text="VIEW PLACES" />
<TextView
android:id="@+id/txtresulttext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="15dp"
android:gravity="left"
android:text=""
android:layout_weight="1"
android:textStyle="italic|bold"
android:textSize="20sp" />
</LinearLayout>
2. placeslist.xml
:
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10">
<ListView
android:id="@+id/placeslist"
android:layout_width="match_parent"
android:layout_weight="9"
android:layout_height="0dp"
android:layout_alignParentLeft="true"></ListView>
<TextView
android:id="@+id/txtresulttext"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:gravity="left"
android:text=""
android:layout_weight="1"
android:textStyle="italic|bold"
android:textSize="13sp" />
</LinearLayout>
3.rows.xml
:
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/lvh"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:scrollbars="horizontal"
android:weightSum="4" >
<TextView
android:id="@+id/txtplaceid"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.6"
android:gravity="center"
android:text="1"
android:background="#ffb6ffb0"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="@+id/txtplacename"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.7"
android:gravity="center"
android:text="Barcelona"
android:background="#ffc5ffe3"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="@+id/txtcountry"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.7"
android:gravity="center"
android:text="Spain"
android:background="#ffd3f5ff"
android:textColor="#000"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
4.AndroidManifest.xml
:
<?xml version="1.0"
encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.prakash.shree.studentinformation">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>
</manifest>
No comments:
Post a Comment