Hello, everyone.
I am beginner in the android programming.
Two days ago, I face same problem about connecting to database in android.
But now, I have found solution code to connect to database in android.
Please try this code ( You only create a new project and copy this code in .java and change the package name ) :
Using java Syntax Highlighting
package com.Android.Beta; //Please change with your package name
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class insert extends Activity { // change class name too
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SQLiteDatabase myDB= null;
String TableName = "dictionary";
String Data = "";
/* Create a Database. */
try {
myDB = this.openOrCreateDatabase("handwriting", MODE_PRIVATE, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (japan_word VARCHAR, english_word VARCHAR);");
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (japan_word, english_word)"
+ " VALUES ('konpyuta ', 'computer');");
/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
int Column1 = c.getColumnIndex("japan_word");
int Column2 = c.getColumnIndex("english_word");
// Check if our result was valid.
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
String word1 = c.getString(Column1);
String word2 = c.getString(Column2);
Data =Data +word1+"/"+word2+"\n";
}while(c.moveToNext());
}
TextView tv = new TextView(this);
tv.setText(Data);
setContentView(tv);
}
catch(Exception e) {
Log.e("Error", "Error", e);
} finally {
if (myDB != null)
myDB.close();
}
}
}
Parsed in 0.038 seconds, using
GeSHi 1.0.8.4
I hope this code help you.
I use eclipse 3.5 and Android 2.1