Hie,This Is Naresh...[Senior Member of Xda-Developers]..
Tutorial of How to Create and Access Database in single java file in Android?
MainActivity code:
public class MainActivity extends Activity{
//creating access variable for DataBase
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button) findViewById(R.id.delapp);
//To open or create a database
final SQLiteDatabase db =openOrCreateDatabase("Example",MODE_WORLD_WRITEABLE, null);
//for creating table in database
db.execSQL("CREATE TABLE IF NOT EXISTS EXAMPLE(NAME VARCHAR);");
//inserting values into table
for(int i=0;i<10;i++)
{
db.execSQL("INSERT INTO EXAMPLE VALUES('"+i+"')");
}
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//cursor is used for accessing data from database table..
//SELECT NAME[you can add columns hereseparating them with comma] FROM EXAMPLE..
Cursor c1=db.rawQuery("SELECT NAME FROM EXAMPLE", null);
//moveToFirst() is used to point to starting row of the database table
if (c1.moveToFirst())
{
do
{
//c1.getString(0) will provide the column NAME value..here '0' is column index..if you have //any other column //in database after NAME then the index number will be "1" and so on..
String v = c1.getString(0);
//Toasting the values inserted into table..
Toast.makeText(app.getApplicationContext(),v,100).show();
}
while (c1.moveToNext());
//c1.moveToNext() will make cursor to move to next position..
}
if (c1 != null && !c1.isClosed())
{
//c1.close(); is closing of cursor.[it is not mandatory in some cases..but better practice with closing cursor]..
c1.close();
}
});
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fullView"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/delapp"
android:layout_width="45dp"
android:layout_height="match_parent"
android:layout_above="@+id/button3"
android:layout_centerHorizontal="true"
android:layout_marginLeft="61dp"
android:text="Button" />
</RelativeLayout>
CHECK My Android APPS:
NCDupRemover-Backup,Clear all Contacts and Remove Duplicate Contacts..
NLauncherV2.2.2-Multipurpose Launcher
NLauncherCV0.2
NMemoV0.2
Any Queries,post a comment...
No comments:
Post a Comment