Anyone who follows Android tags are probably familiar with me. I am having the hardest time implementing a SQLite database for my highscores. This is also my first time working with SQLite.
I am trying to insert just two variables -- int and long. My insert() method is not working correctly. Any advice other than the stuff talked about above is also appreciated.
Thank you in advance for your help.
Highscores.java
public class Highscores extends Activity {
DatabaseHelper dh;
SQLiteDatabase db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.highscoresmain);
dh = new DatabaseHelper(this);
dh.openDB(db);
long x = 11;
int y = 22;
TextView rank = (TextView)findViewById(R.id.rank);
TextView percentage = (TextView)findViewById(R.id.percentage);
TextView score = (TextView)findViewById(R.id.score);
TextView r1r = (TextView)findViewById(R.id.r1r);
TextView r1p = (TextView)findViewById(R.id.r1p);
TextView r1s = (TextView)findViewById(R.id.r1s);
dh.insert(x, y, db); //Line 55
scores = dh.getScore(db);
percentages = dh.getPercentage(db);
rank.setText("Rank Column - TEST");
percentage.setText("Percentage Column - TEST ");
score.setText("Score Column - Test");
r1r.setText("test..rank");
r1p.setText("" + percentages);
r1s.setText("test..score");
table = (TableLayout)findViewById(R.id.tableLayout);
dh.closeDB(db);
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
// Table columns names.
private static final String RANK = "_id";
private static final String SCORE = "score";
private static final String PERCENTAGE = "percentage";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
}
public SQLiteDatabase openDB(SQLiteDatabase db) {
db = this.getWritableDatabase();
return db;
}
public int getPercentage(SQLiteDatabase db) {
//Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + " WHERE " + PERCENTAGE + " = " + 22 + ";", null);
Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + ";", null);
int i = 0;
if(c.getCount() == 0) {
i = 333;
} else if (c.getCount() == 1) {
i = 444;
} else {
i = 888;
/*c.moveToFirst();
int columnIndex = c.getInt(c.getColumnIndex("PERCENTAGE"));
if(columnIndex != -1) {
i = c.getInt(columnIndex);
} else {
i = 999;
}*/
}
c.close();
return i;
}
//Insert new record.
public long insert(long score, int percentage, SQLiteDatabase db) {
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
return db.insert(TABLE, null, values); //Line 120
}
public synchronized void closeDB(SQLiteDatabase db) {
if(db != null) {
db.close();
}
super.close();
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE + " ("
+ RANK + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SCORE + " LONG,"
+ PERCENTAGE + " INTEGER"
+ ");");
}
LogCat output
01-03 17:09:18.232: E/AndroidRuntime(1712): FATAL EXCEPTION: main
01-03 17:09:18.232: E/AndroidRuntime(1712): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.Highscores}: java.lang.NullPointerException
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.os.Looper.loop(Looper.java:137)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-03 17:09:18.232: E/AndroidRuntime(1712): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 17:09:18.232: E/AndroidRuntime(1712): at java.lang.reflect.Method.invoke(Method.java:511)
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-03 17:09:18.232: E/AndroidRuntime(1712): at dalvik.system.NativeStart.main(Native Method)
01-03 17:09:18.232: E/AndroidRuntime(1712): Caused by: java.lang.NullPointerException
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.example.test.DatabaseHelper.insert(DatabaseHelper.java:120)
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.example.test.Highscores.onCreate(Highscores.java:55)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.Activity.performCreate(Activity.java:5104)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-03 17:09:18.232: E/AndroidRuntime(1712): ... 11 more
On this line, you open the DB:
dh.openDB(db);
This stores the member variable of the database in DatabaseHelper.db (but nowhere else, and particularly not in Highscores.db). Then, you call:
dh.insert(x, y, db);
Using a null db object from Highscores. Lastly, within insert(), you use this null db object:
return db.insert(TABLE, null, values);
What you should do instead is use the following as your insert() method:
public long insert(long score, int percentage) { // Remove db parameter
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
return db.insert(TABLE, null, values); // This will use the member variable
}
Then, call dh.insert(x, y); instead.
You should also change openDB(SQLiteDatabase db) to openDB() so that it is writing the correct DB; as it stands, it just overwrites the local variable's value (which changes nothing once the function's scope is done).
Instead of
dh.openDB(db);
say
db = dh.openDB(db);
(although the openDB method really doesn't need to have an argument). Your call to openDB doesn't store the database object reference in db, so it's NULL when you get around to calling dh.insert(..., db);.
Related
I have one database but I want to make 2 tables for separate classes. One for saving new user data and one for saving user's sessions. The one I am trying to get to work is the table consisted of the Session Title, Time, Active. The table for User Username, First, Last works but the one for the session doesn't. Ultimately, I want to put 2 tables in one database/java class which is the "ListBaseHelper". Where did I go wrong?
Here is the Java Class with the database and tables:
public class ListBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "listBase.db";
private static final int DATABASE_VERSION = 2;
//Define a query for creating table so you don't get lost
private static final String CREATE_QUERY =
"CREATE TABLE " + ListTable.TABLE_NAME + "(" + ListDbSchema.ListTable.USERNAME + " TEXT," +
ListDbSchema.ListTable.FIRST + " TEXT," + ListDbSchema.ListTable.LAST + " TEXT);";
private static final String CREATE_QUERY2 =
"CREATE TABLE " + ListTable.TABLE_NAME2 + "(" + ListDbSchema.ListTable.TITLE + " TEXT," +
ListDbSchema.ListTable.TIME + " TEXT," + ListDbSchema.ListTable.ACTIVE + " TEXT);";
public ListBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//Log message
Log.e("DATABASE OPERATIONS", "Database created /opened...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATIONS", "Table created...");
db.execSQL(CREATE_QUERY2);
Log.e("DATABASE OPERATIONS", "Table created...");
}
public void addInformations(String username, String first, String last, SQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
contentValues.put(ListTable.USERNAME, username);
contentValues.put(ListTable.FIRST, first);
contentValues.put(ListTable.LAST, last);
db.insert(ListDbSchema.ListTable.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted...");
}
public void addSessionInfo(String title, String time, String active, SQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
contentValues.put(ListTable.TITLE, title);
contentValues.put(ListTable.TIME, time);
contentValues.put(ListTable.ACTIVE, active);
db.insert(ListDbSchema.ListTable.TABLE_NAME2, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted...");
}
public Cursor getInformations(SQLiteDatabase db) {
Cursor cursor;
String[] projections = {ListTable.USERNAME, ListTable.FIRST, ListTable.LAST};
cursor = db.query(ListDbSchema.ListTable.TABLE_NAME, projections, null, null, null, null, null);
return cursor;
}
public Cursor SessionInformations(SQLiteDatabase db) {
Cursor cursor2;
String[] projections = {ListTable.TITLE, ListTable.TIME, ListTable.ACTIVE};
cursor2 = db.query(ListDbSchema.ListTable.TABLE_NAME2, projections, null, null, null, null, null);
return cursor2;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
When this java class runs, it will ask user for input.
public class NewSessionActivity extends AppCompatActivity {
EditText SessionTitle, SessionTime, SessionActive;
Context context = this;
ListBaseHelper sessionbasehelper;
SQLiteDatabase sqliteDatabase;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logoff_menu_item) {
super.onOptionsItemSelected(item);
Toast.makeText(this, "Logging You Off...", Toast.LENGTH_LONG).show();
startActivity(new Intent(NewSessionActivity.this, LaunchActivity.class));
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_session);
SessionTitle = (EditText) findViewById(R.id.title);
SessionTime = (EditText) findViewById(R.id.time);
SessionActive = (EditText) findViewById(R.id.active);
}
public void btn_submit(View view) {
{
context = this;
String title = SessionTitle.getText().toString();
String time = SessionTime.getText().toString();
String active = SessionActive.getText().toString();
sessionbasehelper= new ListBaseHelper(context);
sqliteDatabase = sessionbasehelper.getWritableDatabase();
sessionbasehelper.addSessionInfo(title,time,active,sqliteDatabase);
Toast.makeText(getBaseContext(), "New Session Saved!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(NewSessionActivity.this, ViewAllSessionsActivity.class);
startActivity(intent);
sessionbasehelper.close();
}
}
}
When java class runs, it's supposed to show the data the user entered from NewSessionActivity above.
public class ViewAllSessionsActivity extends AppCompatActivity{
//Create instance of database
ListBaseHelper myDb;
Button btn_logout;
ListView sessionlistView;
SQLiteDatabase sqLiteDatabase;
ListBaseHelper listbaseDbHelper;
Cursor cursor2;
SessionDataAdapter sessionDataAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logoff_menu_item) {
super.onOptionsItemSelected(item);
Toast.makeText(this, "Logging You Off...", Toast.LENGTH_LONG).show();
startActivity(new Intent(ViewAllSessionsActivity.this, LaunchActivity.class));
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_sessions);
sessionlistView = (ListView) findViewById(R.id.listViewSession);
sessionDataAdapter = new SessionDataAdapter(getApplicationContext(),R.layout.all_session_layout);
sessionlistView.setAdapter(sessionDataAdapter);
listbaseDbHelper = new ListBaseHelper(getApplicationContext());
sqLiteDatabase = listbaseDbHelper.getReadableDatabase();
cursor2 = listbaseDbHelper.SessionInformations(sqLiteDatabase);
if(cursor2.moveToFirst())
{
do {
String title, time, active;
title = cursor2.getString(0);
time = cursor2.getString(1);
active = cursor2.getString(2);
SessionList sessionlist = new SessionList(title, time, active);
sessionDataAdapter.add(sessionlist);
}while (cursor2.moveToNext());
}
btn_logout = (Button)findViewById(R.id.complete_button);
btn_logout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//Use the name of this class, and the name class where you want to be taken when the button is clicked.
Intent intent = new Intent(ViewAllSessionsActivity.this, PaymentActivity.class);
startActivity(intent);
}
});
}
}
This is the LogCat when I run my app:
09-26 10:54:06.071 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.365 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.368 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:24.369 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteDatabase: Error inserting title=Hi time=10:22 active=yes
android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: INSERT INTO table_name2(title,time,active) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.addSessionInfo(ListBaseHelper.java:65)
at com.bignerdranch.android.assignment2.NewSessionActivity.btn_submit(NewSessionActivity.java:62)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-26 10:54:24.370 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: One row inserted...
09-26 10:54:24.919 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.941 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:24.951 2712-2712/com.bignerdranch.android.assignment2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bignerdranch.android.assignment2, PID: 2712
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.assignment2/com.bignerdranch.android.assignment2.ViewAllSessionsActivity}: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.SessionInformations(ListBaseHelper.java:82)
at com.bignerdranch.android.assignment2.ViewAllSessionsActivity.onCreate(ViewAllSessionsActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-26 10:54:38.877 3535-3535/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:38.892 3535-3535/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:38.893 3535-3535/com.bignerdranch.android.assignment2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bignerdranch.android.assignment2, PID: 3535
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.assignment2/com.bignerdranch.android.assignment2.ViewAllSessionsActivity}: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.SessionInformations(ListBaseHelper.java:82)
at com.bignerdranch.android.assignment2.ViewAllSessionsActivity.onCreate(ViewAllSessionsActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I have difficulties when they want to give a different name and a different marker images on Google Maps Marker, I use SQLite database to store the data from the marker, the following code from my project :
MaBase.java
public class MaBase extends SQLiteOpenHelper {
private static final String TABLE_MARK ="marqueur.db";
private static final String COL_ID = "ID";
private static final String COL_LONG = "LONGITUDE";
private static final String COL_LAT = "LATITUDE";
private static final String CREATE_BDD = "CREATE TABLE " + TABLE_MARK + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_LONG + " TEXT NOT NULL, " +COL_LAT+" TEXT NOT NULL);";
public MaBase (Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//on créé la table à partir de la requête écrite dans la variable CREATE_BDD
db.execSQL(CREATE_BDD);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE " + TABLE_MARK + ";");
onCreate(db);
}
}
MainActivity.java
public class MainActivity extends Activity {
private static final String NOM_BDD = "marqueur.db";
private static final String TABLE_GEOPOINT = "geopoint";
private static final String COL_ID = "ID";
private static final String COL_LONG = "LONGITUDE";
private static final String COL_LAT = "LATITUDE";
static final LatLng TUNIS = new LatLng(36.894883, 10.1432776); // https://www.google.tn/maps/#36.794883,10.1432776,9z
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// fct pour remplire la base avec qlq points pour le demo :)
sauver_point();
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
MaBase maBaseSQLite = new MaBase(MainActivity.this, NOM_BDD, null, 1);
SQLiteDatabase db = maBaseSQLite.getWritableDatabase();
Cursor c = db.query(TABLE_GEOPOINT, new String[] { COL_ID, COL_LONG,
COL_LAT }, null, null, null, null, null, null);
int col = c.getCount(); // col=0 pas de enregistrement qui verifie la
// condition
if (col == 0) {
Toast.makeText(MainActivity.this, "Pas de donnees ",
Toast.LENGTH_LONG).show();
// effacer le contenue champ login et mot de passe
} else {
c.moveToFirst();
while (c.isAfterLast() == false) {
// conversion int to string casting
String id = "" + c.getInt(0);
String longitude = c.getString(1);
String latitude = c.getString(2);
Marker marqueur = map.addMarker(new MarkerOptions()
.position(
new LatLng(Double.parseDouble(latitude),
Double.parseDouble(longitude)))
.title("Bonjour Tunis")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mark2)));
c.moveToNext();
}
}
c.close();
db.close();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(TUNIS, 12.0f));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// pour ajouter des points ala base sqlite juste pour le demo :)
void sauver_point() {
MaBase maBaseSQLite = new MaBase(MainActivity.this, NOM_BDD, null, 1);
SQLiteDatabase db = maBaseSQLite.getWritableDatabase();
ContentValues values = new ContentValues();
// values.put(COL_ID , "1");
values.put(COL_LAT, "36.830722");
values.put(COL_LONG, "10.165672");
db.insert(TABLE_GEOPOINT, null, values);
// creer un autre utilisateur
values = new ContentValues();
values.put(COL_LAT , "36.830922");
values.put(COL_LONG, "10.275572");
db.insert(TABLE_GEOPOINT, null, values);
values = new ContentValues();
values.put(COL_LAT, "36.930522");
values.put(COL_LONG, "10.385572");
db.insert(TABLE_GEOPOINT, null, values);
values = new ContentValues();
values.put(COL_LAT, "36.750422");
values.put(COL_LONG, "10.495572");
db.insert(TABLE_GEOPOINT, null, values);
values.put(COL_LAT, "36.936422");
values.put(COL_LONG, "11.495572");
db.insert(TABLE_GEOPOINT, null, values);
values.put(COL_LAT, "36.990422");
values.put(COL_LONG, "9.995572");
db.insert(TABLE_GEOPOINT, null, values);
db.close();
}
}
Then I would do different Marker calling on my other layout in the form of maps, but how do I enter data in the layout to display the marker that I insert in the database? The following layout will I enter along with the marker maps :
fragment_maps.xml
<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"
tools:context=".MainActivity" >
<TextView
android:id="#+id/tv_distance_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" />
<fragment
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
MapsFragment.java
public class GamesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_maps, container, false);
return rootView;
}
}
Please help, thank you :)
Long Cat
02-12 02:15:33.851: E/AndroidRuntime(2489): FATAL EXCEPTION: main
02-12 02:15:33.851: E/AndroidRuntime(2489): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bongkorr/com.bongkorr.maps.MainActivity}: android.database.sqlite.SQLiteException: unknown database marqueur (code 1): , while compiling: CREATE TABLE marqueur.db (ID INTEGER PRIMARY KEY AUTOINCREMENT, LONGITUDE TEXT NOT NULL, LATITUDE TEXT NOT NULL);
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.os.Looper.loop(Looper.java:137)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.app.ActivityThread.main(ActivityThread.java:5041)
02-12 02:15:33.851: E/AndroidRuntime(2489): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 02:15:33.851: E/AndroidRuntime(2489): at java.lang.reflect.Method.invoke(Method.java:511)
02-12 02:15:33.851: E/AndroidRuntime(2489): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-12 02:15:33.851: E/AndroidRuntime(2489): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-12 02:15:33.851: E/AndroidRuntime(2489): at dalvik.system.NativeStart.main(Native Method)
02-12 02:15:33.851: E/AndroidRuntime(2489): Caused by: android.database.sqlite.SQLiteException: unknown database marqueur (code 1): , while compiling: CREATE TABLE marqueur.db (ID INTEGER PRIMARY KEY AUTOINCREMENT, LONGITUDE TEXT NOT NULL, LATITUDE TEXT NOT NULL);
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
02-12 02:15:33.851: E/AndroidRuntime(2489): at com.bongkorr.maps.MaBase.onCreate(MaBase.java:31)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
02-12 02:15:33.851: E/AndroidRuntime(2489): at com.bongkorr.maps.MainActivity.sauver_point(MainActivity.java:86)
02-12 02:15:33.851: E/AndroidRuntime(2489): at com.bongkorr.maps.MainActivity.onCreate(MainActivity.java:35)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.app.Activity.performCreate(Activity.java:5104)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-12 02:15:33.851: E/AndroidRuntime(2489): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
I have two ideas.
You can query TABLE_GEOPOINT again, clear map and all markers again
public void reloadMarkers() {
MaBase maBaseSQLite = new MaBase(MainActivity.this, NOM_BDD, null, 1);
SQLiteDatabase db = maBaseSQLite.getWritableDatabase();
Cursor c = db.query(TABLE_GEOPOINT, new String[] { COL_ID, COL_LONG,
COL_LAT }, null, null, null, null, null, null);
int col = c.getCount(); // col=0 pas de enregistrement qui verifie la
// condition
if (col == 0) {
Toast.makeText(MainActivity.this, "Pas de donnees ",
Toast.LENGTH_LONG).show();
// effacer le contenue champ login et mot de passe
} else {
map.clear(); //Delete all markers in map
//Add them all again, including the new ones
c.moveToFirst();
while (c.isAfterLast() == false) {
// conversion int to string casting
String id = "" + c.getInt(0);
String longitude = c.getString(1);
String latitude = c.getString(2);
Marker marqueur = map.addMarker(new MarkerOptions()
.position(
new LatLng(Double.parseDouble(latitude),
Double.parseDouble(longitude)))
.title("Bonjour Tunis")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mark2)));
c.moveToNext();
}
}
c.close();
db.close();
}
You can keep a reference of the ids of new markers added to the database
void sauver_point() {
MaBase maBaseSQLite = new MaBase(MainActivity.this, NOM_BDD, null, 1);
SQLiteDatabase db = maBaseSQLite.getWritableDatabase();
ContentValues values = new ContentValues();
// values.put(COL_ID , "1");
values.put(COL_LAT, "36.830722");
values.put(COL_LONG, "10.165672");
long id = db.insert(TABLE_GEOPOINT, null, values); //Get the db id of the new inserted marker
//You can keep the id in an array and then query your database looking for those specific ids.
//The just add them to your map. Just don't clear the map his time! Or you will loose the old ones
db.close();
}
EDIT
To add more columns to your database you need to modify your create statement
private static final String CREATE_BDD = "CREATE TABLE " + TABLE_MARK + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_LONG + " TEXT NOT NULL, " +COL_LAT+" TEXT NOT NULL, "+COL_NAME+" VARCHAR(250) NOT NULL, " +COL_IMAGE+" TEXT NOT NULL);";
Then when you do the query just get the new columns value
String id = "" + c.getInt(0);
String longitude = c.getString(1);
String latitude = c.getString(2);
String name = c.getString(3);
String iconEncoded = c.getString(4);
And set that values as your markers name and icon
Marker marqueur = map.addMarker(new MarkerOptions()
.position(
new LatLng(Double.parseDouble(latitude),
Double.parseDouble(longitude)))
.title(name)
.icon(iconDecoded);
IMPORTANT
Note that iconEncoded is a string and the marker image is a 'BitmapDescriptor' so you first need to convert iconEncoded into a Bitmap and that bitmap into a BitmapDescriptor before setting it as the marker icon. I hope you know how to do this already, If not there are lots of posts related to that and I'm sure you'll find the way there.
Another important thing is that you need to delete your application data before creating the new columns in your database or your app will crash. The simplest way to do it is uninstall your app and run it again. This only needs to be done once.
I want to create a simple database for my android application in sqlite. I just want to add my values to the table.
This is my code but this is not working for me because the table is not shown at DDMS.
public class QuickSubmitContext extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "submitManager";
private static final String TABLE_CONTACTS = "submit";
private static final String KEY_ID = "id";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_DNCA = "donotca";
private static final String KEY_CA = "callagain";
private static final String KEY_NOTE = "note";
public QuickSubmitContext(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_PH_NO + " TEXT,"
+ KEY_DNCA + " TEXT," + KEY_CA + " TEXT," + KEY_NOTE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
}
Logcat
10-21 04:39:00.230: E/AndroidRuntime(835): FATAL EXCEPTION: main
10-21 04:39:00.230: E/AndroidRuntime(835): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aspeage.quikw/com.aspeage.quikw.FragmentLayout}: java.lang.NullPointerException
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.os.Handler.dispatchMessage(Handler.java:99)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.os.Looper.loop(Looper.java:137)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-21 04:39:00.230: E/AndroidRuntime(835): at java.lang.reflect.Method.invokeNative(Native Method)
10-21 04:39:00.230: E/AndroidRuntime(835): at java.lang.reflect.Method.invoke(Method.java:511)
10-21 04:39:00.230: E/AndroidRuntime(835): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-21 04:39:00.230: E/AndroidRuntime(835): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-21 04:39:00.230: E/AndroidRuntime(835): at dalvik.system.NativeStart.main(Native Method)
10-21 04:39:00.230: E/AndroidRuntime(835): Caused by: java.lang.NullPointerException
10-21 04:39:00.230: E/AndroidRuntime(835): at com.aspeage.quikw.FragmentLayout.onCreate(FragmentLayout.java:79)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.Activity.performCreate(Activity.java:5104)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-21 04:39:00.230: E/AndroidRuntime(835): ... 11 more
10-21 04:39:07.090: I/Process(835): Sending signal. PID: 835 SIG: 9
10-21 04:39:13.050: E/Trace(866): error opening trace file: No such file or directory (2)
The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database. For example:
public class DictionaryOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}
Here are instructions. http://developer.android.com/guide/topics/data/data-storage.html#db
I am inserting the data from data base using sqlite but I am getting an error .Here is my code and error.I just enter one entry and want to display that entry ?
package com.example.database_example;
public class Information {
String name;
public Information(String name) {
// TODO Auto-generated constructor stub
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Data Base.java class
package com.example.database_example;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Information inf=new Information("naveen");
DataBaseExample dbx=new DataBaseExample(MainActivity.this);
if(dbx.insertname(inf)){
Log.v("checkdbx.insertname(inf);", "save ok.");
}else{
Log.v("checkdbx.insertname(inf);", "save failed.");
}
}
}
package com.example.database_example;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseExample extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "information";
// Contacts table name
private static final String TABLE_Name= "Name";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
public DataBaseExample(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ ")";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Name);
// Create tables again
onCreate(db);
}
public boolean insertname(Information information) {
boolean createSuccessful = false;
ContentValues values = new ContentValues();
// values.put(KEY_ID, information.getId());
values.put(KEY_NAME, information.getName());
SQLiteDatabase db = this.getWritableDatabase();
createSuccessful = db.insert(TABLE_Name, null, values) > 0;
db.close();
return createSuccessful;
}
}
Here is my error
09-24 07:25:07.138: I/Database(392): sqlite returned: error code = 1, msg = near ")": syntax error
09-24 07:25:07.138: E/Database(392): Failure 1 (near ")": syntax error) on 0x2a7080 when preparing 'CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)'.
09-24 07:25:07.148: D/AndroidRuntime(392): Shutting down VM
09-24 07:25:07.148: W/dalvikvm(392): threadid=1: thread exiting with uncaught exception (group=0x40015560)
09-24 07:25:07.158: E/AndroidRuntime(392): FATAL EXCEPTION: main
09-24 07:25:07.158: E/AndroidRuntime(392): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.database_example/com.example.database_example.MainActivity}: android.database.sqlite.SQLiteException: near ")": syntax error: CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.os.Handler.dispatchMessage(Handler.java:99)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.os.Looper.loop(Looper.java:123)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.main(ActivityThread.java:3683)
09-24 07:25:07.158: E/AndroidRuntime(392): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): at java.lang.reflect.Method.invoke(Method.java:507)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-24 07:25:07.158: E/AndroidRuntime(392): at dalvik.system.NativeStart.main(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): Caused by: android.database.sqlite.SQLiteException: near ")": syntax error: CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1763)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.DataBaseExample.onCreate(DataBaseExample.java:34)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:126)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.DataBaseExample.insertname(DataBaseExample.java:55)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.MainActivity.onCreate(MainActivity.java:18)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
09-24 07:25:07.158: E/AndroidRuntime(392): ... 11 more
Change
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ ")";
to
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT"
+ ")";
removing the comma after TEXT
EDIT
To read all the values from the database, you can add the following method to your class DataBaseExample:
private List<Information> getAllItems()
List<Information> itemsList = new ArrayList<Information>();
Cursor cursor = null;
try {
//get all rows
cursor = mDatabase.query(TABLE_Name, null, null, null, null,
null, null);
if (cursor.moveToFirst()) {
do {
Information c = new Information();
c.setName(cursor.getString(KEY_NAME));
itemsList.add(c);
} while (cursor.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
cursor.close();
}
return itemsList;
}
i have a problem with my SQLite class. In fact, i was learning how to setting up (update and read) a database on android and I successfully wrote on the database, but when i try to read the informations and display them on the screen, my application just crashes.
I searched the problem and found that the cause of the crash is the Cursor. I commented the cursor's method, so if someone can help me with that, i would be thankful.
This my Database class.
package com.example.sqlprogramming;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseClass {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "person_name";
public static final String KEY_RATE = "person_rate";
private static final String DATABASE_NAME = "HotOrNotdb";
private static final String DATABASE_TABLE = "peopleTable";
private static final int DATABASE_VERSION = 2;
private Dhelper ourHelperdb;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class Dhelper extends SQLiteOpenHelper{
public Dhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table if not exists " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + "VARCHAR NOT NULL, " +
KEY_RATE + "VARCHAR NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public DatabaseClass(Context c){
ourContext = c;
}
public DatabaseClass open() throws SQLException{
ourHelperdb = new Dhelper(ourContext);
ourDatabase = ourHelperdb.getWritableDatabase();
return this;
}
public void close(){
ourHelperdb.close();
}
public long addEntry(String personName, String personHotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, personName);
cv.put(KEY_RATE, personHotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
//HERE IS MY PROBLEM WITH THE CURSOR
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_RATE};
String result = "hello";
Cursor c = ourDatabase.query(true, DATABASE_TABLE, columns, null, null, null, null, null, null);
int iRowId = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iRate = c.getColumnIndex(KEY_RATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRowId) + " " + c.getString(iName) +" " + c.getString(iRate) + "\n";
}
c.close();
return result;
}
}
And this Class call the Database Class and should take informations from database to display it on the screen.
package com.example.sqlprogramming;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLview extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_sqlview);
TextView textInfo = (TextView) findViewById (R.id.tvSQLinfo);
DatabaseClass info = new DatabaseClass(this);
info.open();
String _data = info.getData();
info.close();
textInfo.setText(_data);
}
}
Thank you again.
I'll post stacktrace and logcat soon.
Here is my Logcat/Stacktrace
02-24 20:08:12.378: E/Curosr!(1221): I got an error here :
02-24 20:08:12.378: E/Curosr!(1221): android.database.sqlite.SQLiteException: no such column: person_name (code 1): , while compiling: SELECT _id AS _id, person_name, person_rate FROM peopleTable
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
02-24 20:08:12.378: E/Curosr!(1221): at com.example.sqlprogramming.DatabaseClass.getData(DatabaseClass.java:75)
02-24 20:08:12.378: E/Curosr!(1221): at com.example.sqlprogramming.SQLview.onCreate(SQLview.java:14)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.Activity.performCreate(Activity.java:5104)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-24 20:08:12.378: E/Curosr!(1221): at android.os.Handler.dispatchMessage(Handler.java:99)
02-24 20:08:12.378: E/Curosr!(1221): at android.os.Looper.loop(Looper.java:137)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.main(ActivityThread.java:5039)
02-24 20:08:12.378: E/Curosr!(1221): at java.lang.reflect.Method.invokeNative(Native Method)
02-24 20:08:12.378: E/Curosr!(1221): at java.lang.reflect.Method.invoke(Method.java:511)
02-24 20:08:12.378: E/Curosr!(1221): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-24 20:08:12.378: E/Curosr!(1221): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-24 20:08:12.378: E/Curosr!(1221): at dalvik.system.NativeStart.main(Native Method)
Your create statement is missing a few spaces. Try using:
db.execSQL("create table if not exists " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " VARCHAR NOT NULL, " +
KEY_RATE + " VARCHAR NOT NULL);");
According to your current statement, your last two column names become person_nameVARCHAR and person_rateVARCHAR
If you're reading, you need to use:
ourDatabase = ourHelperdb.getReadableDatabase();
When you open your DB, you are setting it to write.
(That's my first guess, post stack trace).
Here's a working example from some of my code on how to read a cursor:
mDb = mDbHelper.getReadableDatabase();
Cursor c = mDb.query("Timesheets", new String[] {
KEY_TIMESHEETS_ROWID + " AS _id", KEY_TIMESHEETS_DESCRIPTION,
KEY_TIMESHEETS_TITLE, KEY_TIMESHEETS_DATE_START,
KEY_TIMESHEETS_DATE_END, KEY_TIMESHEETS_INVOICED,
KEY_TIMESHEETS_PROJECTID }, "timesheet_id = ?",
new String[] { String.valueOf(timesheetId) }, null, null, null);
c.moveToFirst();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Timesheet timesheet = new Timesheet();
while (c.isAfterLast() == false) {
timesheet.setTimesheetId(c.getInt(0));
// ...
c.moveToNext();
}
c.close();