Android SQLite issue - table __ has no column named ___ - java

I am a new developer and I am having an SQLite issue. Some reason I am not able to add two columns (table_row_three, and table_row_four) to my SQLite data table. When I read the database file currently, it has a table with "id", "table_row_one", and "table_row_two", but is missing "table_row_three" and "table_row_four".
The error message in my logcat reads: "(1) table database_table has no column named table_row_three".
I am really confused to why the columns "table_row_three" and "table_row_four" are not showing up on my table, and why only "id", "table_row_one", and "table_row_two" appear in my data table.
Here is my Database class:
DatabaseHandler.java
import java.util.ArrayList;
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;
import android.util.Log;
public class DatabaseHandler
{
Context context;
private SQLiteDatabase db;
private final String DB_NAME = "database_name";
private final int DB_VERSION = 2;
private final String TABLE_NAME = "database_table";
private final String TABLE_ROW_ID = "id";
private final String TABLE_ROW_ONE = "table_row_one";
private final String TABLE_ROW_TWO = "table_row_two";
private final String TABLE_ROW_THREE = "table_row_three";
private final String TABLE_ROW_FOUR = "table_row_four";
public DatabaseHandler(Context context)
{
this.context = context;
// create or open the database
CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
this.db = helper.getWritableDatabase();
}
public void addRow(String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
//TABLE_ROW_ONE = Title
//TABLE_ROW_TWO = Location
//TABLE_ROW_THREE = Notes
//TABLE_ROW_FOUR = Picture
values.put(TABLE_ROW_ONE, rowStringOne);
values.put(TABLE_ROW_TWO, rowStringTwo);
values.put(TABLE_ROW_THREE, rowStringThree);
values.put(TABLE_ROW_FOUR, rowStringFour);
// ask the database object to insert the new data
try{db.insert(TABLE_NAME, null, values);}
catch(Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void deleteRow(long rowID)
{
// ask the database manager to delete the row of given id
try {db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateRow(long rowID, String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{
ContentValues values = new ContentValues();
values.put(TABLE_ROW_ONE, rowStringOne);
values.put(TABLE_ROW_TWO, rowStringTwo);
values.put(TABLE_ROW_THREE, rowStringThree);
values.put(TABLE_ROW_FOUR, rowStringFour);
try {db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);}
catch (Exception e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
public ArrayList<Object> getRowAsArray(long rowID)
{
ArrayList<Object> rowArray = new ArrayList<Object>();
Cursor cursor;
try
{
cursor = db.query
(
TABLE_NAME,
new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO, TABLE_ROW_THREE, TABLE_ROW_FOUR },
TABLE_ROW_ID + "=" + rowID,
null, null, null, null, null
);
cursor.moveToFirst();
if (!cursor.isAfterLast())
{
do
{
rowArray.add(cursor.getLong(0));
rowArray.add(cursor.getString(1));
rowArray.add(cursor.getString(2));
rowArray.add(cursor.getString(3));
rowArray.add(cursor.getString(4));
}
while (cursor.moveToNext());
}
cursor.close();
}
catch (SQLException e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
// return the ArrayList containing the given row from the database.
return rowArray;
}
public ArrayList<ArrayList<Object>> getAllRowsAsArrays()
{
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
Cursor cursor;
try
{
cursor = db.query(
TABLE_NAME,
new String[]{TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO, TABLE_ROW_THREE, TABLE_ROW_FOUR},
null, null, null, null, null
);
cursor.moveToFirst();
if (!cursor.isAfterLast())
{
do
{
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataList.add(cursor.getString(4));
dataArrays.add(dataList);
}
while (cursor.moveToNext());
}
}
catch (SQLException e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
return dataArrays;
}
private class CustomSQLiteOpenHelper extends SQLiteOpenHelper
{
public CustomSQLiteOpenHelper(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_ONE + " text," +
TABLE_ROW_TWO + " text" +
TABLE_ROW_THREE + " text" +
TABLE_ROW_FOUR + " text" +
");";
db.execSQL(newTableQueryString);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
Here is my Test class:
public class DatabaseExampleActivity extends Activity {
EditText textFieldOne, textFieldTwo, textFieldThree, textFieldFour,
idField,
updateIDField, updateTextFieldOne, updateTextFieldTwo,updateTextFieldThree, updateTextFieldFour;
Button addButton, deleteButton, retrieveButton, updateButton;
TableLayout dataTable;
DatabaseHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
// this try catch block returns better error reporting to the log
try {
// Android specific calls
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_databaseexample);
// create the database manager object
db = new DatabaseHandler(this);
// create references and listeners for the GUI interface
setupViews();
// make the buttons clicks perform actions
addButtonListeners();
// load the data table
updateTable();
} catch (Exception e) {
Log.e("ERROR", e.toString());
e.printStackTrace();
}
}
private void setupViews() {
// THE DATA TABLE
dataTable = (TableLayout) findViewById(R.id.data_table);
// THE DATA FORM FIELDS
textFieldOne = (EditText) findViewById(R.id.text_field_one);
textFieldTwo = (EditText) findViewById(R.id.text_field_two);
textFieldThree = (EditText) findViewById(R.id.text_field_three);
textFieldFour = (EditText) findViewById(R.id.text_field_four);
idField = (EditText) findViewById(R.id.id_field);
updateIDField = (EditText) findViewById(R.id.update_id_field);
updateTextFieldOne = (EditText) findViewById(R.id.update_text_field_one);
updateTextFieldTwo = (EditText) findViewById(R.id.update_text_field_two);
updateTextFieldThree = (EditText) findViewById(R.id.update_text_field_three);
updateTextFieldFour = (EditText) findViewById(R.id.update_text_field_four);
addButton = (Button) findViewById(R.id.add_button);
deleteButton = (Button) findViewById(R.id.delete_button);
retrieveButton = (Button) findViewById(R.id.retrieve_button);
updateButton = (Button) findViewById(R.id.update_button);
}
private void addButtonListeners() {
addButton.setOnClickListener
(
new View.OnClickListener() {
#Override
public void onClick(View v) {
addRow();
}
}
);
deleteButton.setOnClickListener
(
new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteRow();
}
}
);
updateButton.setOnClickListener
(
new View.OnClickListener() {
#Override
public void onClick(View v) {
updateRow();
}
}
);
retrieveButton.setOnClickListener
(
new View.OnClickListener() {
#Override
public void onClick(View v) {
retrieveRow();
}
}
);
}
private void addRow() {
try {
// ask the database manager to add a row given the two strings
db.addRow
(
textFieldOne.getText().toString(),
textFieldTwo.getText().toString(),
textFieldThree.getText().toString(),
textFieldFour.getText().toString()
);
// request the table be updated
updateTable();
// remove all user input from the Activity
emptyFormFields();
} catch (Exception e) {
Log.e("Add Error", e.toString());
e.printStackTrace();
}
}
private void deleteRow() {
try {
// ask the database manager to delete the row with the give rowID.
db.deleteRow(Long.parseLong(idField.getText().toString()));
// request the table be updated
updateTable();
// remove all user input from the Activity
emptyFormFields();
} catch (Exception e) {
Log.e("Delete Error", e.toString());
e.printStackTrace();
}
}
private void retrieveRow() {
try {
// The ArrayList that holds the row data
ArrayList<Object> row;
// ask the database manager to retrieve the row with the given rowID
row = db.getRowAsArray(Long.parseLong(updateIDField.getText().toString()));
// update the form fields to hold the retrieved data
updateTextFieldOne.setText((String) row.get(1));
updateTextFieldTwo.setText((String) row.get(2));
updateTextFieldThree.setText((String) row.get(3));
updateTextFieldFour.setText((String) row.get(4));
} catch (Exception e) {
Log.e("Retrieve Error", e.toString());
e.printStackTrace();
}
}
private void updateRow() {
try {
// ask the database manager to update the row based on the information
// found in the corresponding user entry fields
db.updateRow
(
Long.parseLong(updateIDField.getText().toString()),
updateTextFieldOne.getText().toString(),
updateTextFieldTwo.getText().toString(),
updateTextFieldThree.getText().toString(),
updateTextFieldFour.getText().toString()
);
updateTable();
emptyFormFields();
} catch (Exception e) {
Log.e("Update Error", e.toString());
e.printStackTrace();
}
}
private void emptyFormFields() {
textFieldOne.setText("");
textFieldTwo.setText("");
textFieldThree.setText("");
textFieldFour.setText("");
idField.setText("");
updateIDField.setText("");
updateTextFieldOne.setText("");
updateTextFieldTwo.setText("");
updateTextFieldThree.setText("");
updateTextFieldFour.setText("");
}
private void updateTable() {
// delete all but the first row. remember that the count
// starts at one and the index starts at zero
while (dataTable.getChildCount() > 1) {
// while there are at least two rows in the table widget, delete
// the second row.
dataTable.removeViewAt(1);
}
// collect the current row information from the database and
// store it in a two dimensional ArrayList
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
// iterate the ArrayList, create new rows each time and add them
// to the table widget.
for (int position = 0; position < data.size(); position++) {
TableRow tableRow = new TableRow(this);
ArrayList<Object> row = data.get(position);
TextView idText = new TextView(this);
idText.setText(row.get(0).toString());
tableRow.addView(idText);
TextView textOne = new TextView(this);
textOne.setText(row.get(1).toString());
tableRow.addView(textOne);
TextView textTwo = new TextView(this);
textTwo.setText(row.get(2).toString());
tableRow.addView(textTwo);
TextView textThree = new TextView(this);
textThree.setText(row.get(3).toString());
tableRow.addView(textThree);
TextView textFour = new TextView(this);
textFour.setText(row.get(4).toString());
tableRow.addView(textFour);
dataTable.addView(tableRow);
}
}

Missing ',' in create statement :
String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_ONE + " text," +
TABLE_ROW_TWO + " text," +
TABLE_ROW_THREE + " text," +
TABLE_ROW_FOUR + " text" +
");";

String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_ONE + " text," +
TABLE_ROW_TWO + " text" +
TABLE_ROW_THREE + " text" +
TABLE_ROW_FOUR + " text" +
");";
In this statement you missed two commas after type defind. Thats why the field is not created so you found that exception. And one another thing after the close parenthesis ");" the semicolon is not required.
Replace your code to :-
String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_ONE + " text," +
TABLE_ROW_TWO + " text," +
TABLE_ROW_THREE + " text," +
TABLE_ROW_FOUR + " text" +
")";
I hope this will help you. :)

TABLE_ROW_TWO + " text" +
TABLE_ROW_THREE + " text" +
TABLE_ROW_FOUR + " text" +
put , after text
TABLE_ROW_TWO + " text," +
TABLE_ROW_THREE + " text," +
TABLE_ROW_FOUR + " text" +

Change CustomSQLiteOpenHelper code like this,
private class CustomSQLiteOpenHelper extends SQLiteOpenHelper
{
public CustomSQLiteOpenHelper(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_ONE + " text," +
TABLE_ROW_TWO + " text," +
TABLE_ROW_THREE + " text," +
TABLE_ROW_FOUR + " text" +
");";
db.execSQL(newTableQueryString);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}

Related

How to sum my column value in SQLite?

I know this question has been asked several times, but I just can't get the right syntax for my problem.
I want to sum my value of "einnahmen".
This is my SqlDbHelper class:
public class SqlDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_TABLE = "PHONE_CONTACTS";
public static final String COLUMN1 = "nr";
public static final String COLUMN2 = "name";
public static final String COLUMN3 = "einnahmen";
public static final String COLUMN4 = "ausgaben";
public static final String COLUMN5 = "datum";
private static final String SCRIPT_CREATE_DATABASE =
"create table "+ DATABASE_TABLE
+ " (" + COLUMN1+ " integer primary key autoincrement, "
+ COLUMN2+ " text not null, "
+ COLUMN3 + " text not null, "
+ COLUMN4 + " text not null, "
+ COLUMN5 + " text not null);";
public SqlDbHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#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);
}
}
This is my MainActivity:
public class BookActivity extends Activity {
SqlHandler sqlHandler;
ListView lvCustomList;
EditText etName, etEinnahmen, etAusgaben, etDatum;
ImageButton btn_add;
TextView gesamteinnahmen;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
gesamteinnahmen = (TextView) findViewById(R.id.tVgesamtEinnahmen);
lvCustomList = (ListView) findViewById(R.id.lv_custom_list);
etName = (EditText) findViewById(R.id.et_name);
etEinnahmen = (EditText) findViewById(R.id.et_einnahmen);
etAusgaben = (EditText) findViewById(R.id.et_ausgaben);
etDatum = (EditText) findViewById(R.id.et_datum);
btn_add = (ImageButton) findViewById(R.id.btn_add);
sqlHandler = new SqlHandler(this);
showList();
btn_add.setOnClickListener(new OnClickListener() {
#SuppressLint("ShowToast")
#Override
public void onClick(View v) {
String name = etName.getText().toString();
String einnahmen = etEinnahmen.getText().toString();
String ausgaben = etAusgaben.getText().toString();
String datum = etDatum.getText().toString();
if (TextUtils.isEmpty(name)) {etName.setError("Das Feld ist leer");return;}
else if (TextUtils.isEmpty(einnahmen)) {etEinnahmen.setError("Das Feld ist leer");return;
} else if (TextUtils.isEmpty(ausgaben)) {etAusgaben.setError("Das Feld ist leer");return;
} else if (TextUtils.isEmpty(datum)) {etDatum.setError("Das Feld ist leer");return;
} else {
Toast.makeText(BookActivity.this,"Daten wurden erfolgreich gespeichert", Toast.LENGTH_SHORT).show();
String query = "INSERT INTO PHONE_CONTACTS(name,einnahmen,ausgaben,datum) values " +
"('" + name + "','" + einnahmen +"','" + ausgaben + "','" + datum + "')";
sqlHandler.executeQuery(query);
showList();
etName.setText("");
etEinnahmen.setText("");
etAusgaben.setText("");
etDatum.setText("");
}
}
});
}
private void showList() {
ArrayList contactList = new ArrayList();
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS";
Cursor c1 = sqlHandler.selectQuery(query);
if (c1 != null && c1.getCount() != 0) {
if (c1.moveToFirst()) {
do {
ContactListItems contactListItems = new ContactListItems();
contactListItems.setNr(c1.getString(c1.getColumnIndex("nr")));
contactListItems.setName(c1.getString(c1.getColumnIndex("name")));
contactListItems.setEinnahmen(c1.getString(c1.getColumnIndex("einnahmen")));
contactListItems.setAusgaben(c1.getString(c1.getColumnIndex("ausgaben")));
contactListItems.setDatum(c1.getString(c1.getColumnIndex("datum")));
contactList.add(contactListItems);
} while (c1.moveToNext());
}
}
c1.close();
ContactListAdapter contactListAdapter = new ContactListAdapter(
BookActivity.this, contactList);
lvCustomList.setAdapter(contactListAdapter);}
}
I hope this code helps you.
Your sql query should looks like
query = "SELECT *, SUM(einnahmen) as sum FROM PHONE_CONTACS";
in your SqlDbHelper class:
public long sumEinnahmen() {
SQLiteStatement statement = getReadableDatabase().compileStatement(
"select sum(" + COLUMN3 + " from " + DATABASE_TABLE);
try {
return statement.simpleQueryForLong();
} finally {
statement.close();
}
}
Note that your column is currently declared as a text column instead of as integer or real column. If you are only storing numeric data in that column, you should declare it with either of those numeric types instead.

How to create multiple table?

Please help me, I'm newbie and I have problem. I try to create multiple table in this code but always error. this error say there is no table PENGINAPAN and i can't solve it.
this is DatabaseHelper class :
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbwisata";
public static final String NAMA = "nama";
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
// method createTable untuk membuat table WISATA
public void createTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS WISATA");
db.execSQL("CREATE TABLE if not exists WISATA (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
db.execSQL("DROP TABLE IF EXISTS PENGINAPAN");
db.execSQL("CREATE TABLE if not exists PENGINAPAN (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
}
// method generateData untuk mengisikan data ke table Wisata.
public void generateData(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(NAMA, "Ancol");
db.insert("WISATA", NAMA, cv);
cv.put(NAMA, "Ragunan");
db.insert("WISATA", NAMA, cv);
cv.put(NAMA, "Taman Mini");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Melati");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Villa");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Bintang");
db.insert("PENGINAPAN", NAMA, cv);
}
// method delAllAdata untuk menghapus data di table Wisata.
public void delAllData(SQLiteDatabase db) {
db.delete("WISATA", null, null);
db.delete("WISATA", null, null);
}
public Cursor fetchAllWisata(SQLiteDatabase db) {
return db.query("WISATA", new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
public Cursor fetchAllPenginapan(SQLiteDatabase db) {
return db.query("PENGINAPAN", new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
please help me.
I cleaned up your code. If it doesn't work, uninstall your app and install it again. Be sure you create the database before you try to write/read any data.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbwisata";
private static final String TABLE_WISATA = "WISATA";
private static final String TABLE_PENGINAPAN = "PENGINAPAN";
public static final String NAMA = "nama";
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
// method createTable untuk membuat table WISATA
public void createTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_WISATA);
db.execSQL("CREATE TABLE if not exists " + TABLE_WISATA + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
db.execSQL("DROP TABLE IF EXISTS PENGINAPAN");
db.execSQL("CREATE TABLE if not exists " + TABLE_PENGINAPAN + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAMA + " TEXT);");
}
// method generateData untuk mengisikan data ke table Wisata.
public void generateData(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(NAMA, "Ancol");
db.insert(TABLE_WISATA, null, cv);
cv.put(NAMA, "Ragunan");
db.insert(TABLE_WISATA, null, cv);
cv.put(NAMA, "Taman Mini");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Melati");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Villa");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Bintang");
db.insert(TABLE_PENGINAPAN, null, cv);
}
// method delAllAdata untuk menghapus data di table Wisata.
public void delAllData(SQLiteDatabase db) {
db.delete(TABLE_WISATA, null, null);
db.delete(TABLE_WISATA, null, null);
}
public Cursor fetchAllWisata(SQLiteDatabase db) {
return db.query(TABLE_WISATA, new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
public Cursor fetchAllPenginapan(SQLiteDatabase db) {
return db.query(TABLE_PENGINAPAN, new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Use this code and modify it as per your needs. i have added all comments so that you can understand where i am adding a table, where i am adding a column and where i am adding entries.
public class DatabaseHelper extends SQLiteOpenHelper {
//changing master
// Logcat tag
//add comment
private static final String LOG = "DatabaseHelper";
// Database Version
private static final int DATABASE_VERSION = 3;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Table Names
private static final String TABLE_VIDEO = "video";
private static final String TABLE_PICTURE = "pictures";
private static final String TABLE_MUSIC = "music";
// Common column names
private static final String KEY_ID = "id";
private static final String KEY_FAV = "fav";
// MUSIC Table - column names
private static final String KEY_MUSIC_PATH = "path";
private static final String KEY_MUSIC_CAT_ID = "cat_id";
private static final String KEY_MUSIC_NAME = "music_name";
// PICTURE Table - column names
private static final String KEY_PICTURE_PATH = "path";
private static final String KEY_PICTURE_CAT_ID = "cat_id";
private static final String KEY_PICTURE_NAME = "picture_name";
// VIDEO Table - column names
private static final String KEY_VIDEO_PATH = "path";
private static final String KEY_VIDEO_CAT_ID = "cat_id";
private static final String KEY_VIDEO_SUBCAT_ID = "subcat_id";
private static final String KEY_VIDEO_NAME = "video_name";
// Table Create Statements
// Video table create statement
private static final String CREATE_TABLE_VIDEO = "CREATE TABLE "
+ TABLE_VIDEO + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_VIDEO_PATH + " TEXT,"
+ KEY_VIDEO_CAT_ID+ " INTEGER,"
+ KEY_VIDEO_SUBCAT_ID + " TEXT,"
+ KEY_VIDEO_NAME + " TEXT)";
// PICTURE table create statement
private static final String CREATE_TABLE_PICTURE = "CREATE TABLE "
+ TABLE_PICTURE + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_PICTURE_PATH + " TEXT," + KEY_PICTURE_CAT_ID+ " INTEGER,"
+ KEY_PICTURE_NAME + " TEXT)";
// MUSIC table create statement
private static final String CREATE_TABLE_MUSIC = "CREATE TABLE "
+ TABLE_MUSIC + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_MUSIC_PATH + " TEXT," + KEY_MUSIC_CAT_ID+ " INTEGER,"
+ KEY_MUSIC_NAME + " TEXT)";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// creating required tables
db.execSQL(CREATE_TABLE_PICTURE);
db.execSQL(CREATE_TABLE_MUSIC);
db.execSQL(CREATE_TABLE_VIDEO);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_VIDEO);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PICTURE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MUSIC);
// create new tables
onCreate(db);
}
/*
* create videos
* */
/* public boolean addVideos(List<Video> video, int category_id){
SQLiteDatabase db = this.getWritableDatabase();
long id = 0;
for(int i = 0; i <video.size(); ++i){
ContentValues values = new ContentValues();
values.put(KEY_VIDEO_NAME, video.get(i).getName());
values.put(KEY_VIDEO_PATH, video.get(i).getPath());
values.put(KEY_VIDEO_CAT_ID, category_id);
// insert row
id = db.insert(TABLE_VIDEO, null, values);
}
if (id < 0)
return false;
return true;
}*/
// add videos
public void addvideos(Video item, int catid, String subcat) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (fav, path, cat_id, subcat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + subcat + "'," + "'" + item.getName() + "'" + ")");
}
// add pictures
public void addpictures(Picture item, int catid) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (path, cat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + item.getName() + "'" + ")");
}
// add music
public void addmusic(Music item, int catid) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (path, cat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + item.getName() + "'" + ")");
}
/*
* getting all videos
* */
public List<Video> getAllVideos() {
List<Video> lstVideo = new ArrayList<Video>();
String selectQuery = "SELECT * FROM " + TABLE_VIDEO;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Video video = new Video();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
video.setSubcategory(c.getString(c.getColumnIndex(KEY_VIDEO_SUBCAT_ID)));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
/*
* getting all videos by categories
* */
public List<Video> getAllVideosByCategory(String category) {
List<Video> lstVideo = new ArrayList<Video>();
String selectQuery = "SELECT * FROM " + TABLE_VIDEO +
" WHERE " + TABLE_VIDEO + "." + KEY_VIDEO_SUBCAT_ID +
" = " + category;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Video video = new Video();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
video.setSubcategory(c.getString(c.getColumnIndex(KEY_VIDEO_SUBCAT_ID)));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// getting all pictures
public List<Picture> getAllPictures() {
List<Picture> lstVideo = new ArrayList<Picture>();
String selectQuery = "SELECT * FROM " + TABLE_PICTURE;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Picture video = new Picture();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_PICTURE_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_PICTURE_PATH))));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// getting all music
public List<Music> getAllMusic() {
List<Music> lstVideo = new ArrayList<Music>();
String selectQuery = "SELECT * FROM " + TABLE_MUSIC;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Music video = new Music();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// closing database
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
}
Updated Answer: Picture class code is added
public class Picture {
public int id;
public String name;
public String path;
public int favourite;
public int getFavourite() {
return favourite;
}
public void setFavourite(int favourite) {
this.favourite = favourite;
}
public Picture(){
}
public Picture(int id, String name, String path){
this.id = id;
this.name = name;
this.path = path;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}

SQLite db duplicate values Android

I'm using a spinner in my application that takes the values from a SQLite database. The problem is that every time I run the application from Eclipse the values loads again and again. So if the first time I have 5 values in the spinner, the second time I have 10 values, then 15, then 20 etc. How can I solve this?
This is the db part:
In the onCreate:
createTable();
insertIntoTable();
ArrayList<String> my_array = new ArrayList<String>();
my_array = getTableValues();
My_spinner = (Spinner) findViewById(R.id.scelte);
My_spinner.setOnItemSelectedListener(this);
ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row, my_array);
My_spinner.setAdapter(my_Adapter);
and then:
// CREATE TABLE IF NOT EXISTS
public void createTable() {
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE
+ " (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT);");
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Errore durante la creazione della tabella",
Toast.LENGTH_LONG);
}
}
// THIS FUNCTION INSERTS DATA TO THE DATABASE
public void insertIntoTable() {
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Cibo e Bevande','cibo')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Trasporti','trasporti')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Svago','svago')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Acquisti vari','acquisti')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Sanità','sanità')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Altro','altro')");
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Error in inserting into table", Toast.LENGTH_LONG);
}
}
// THIS FUNCTION SHOWS DATA FROM THE DATABASE
public ArrayList<String> getTableValues() {
ArrayList<String> my_array = new ArrayList<String>();
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
System.out.println("COUNT : " + allrows.getCount());
if (allrows.moveToFirst()) {
do {
String ID = allrows.getString(0);
String NAME = allrows.getString(1);
String PLACE = allrows.getString(2);
my_array.add(NAME);
} while (allrows.moveToNext());
}
allrows.close();
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Errore.",
Toast.LENGTH_LONG);
}
return my_array;
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String selecteditem = My_spinner.getSelectedItem().toString();
TextView categorietext = (TextView) findViewById(R.id.sceltelabel);
categorietext.setText(selecteditem);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
You run this
insertIntoTable();
every time in onCreate so it adds more and more data.
You should use extend SQLiteOpenHelper class and use onCreate method to create your database and initialise tables. See Android developer reference.
Every time you will open your activity onCreate method of activity will be invoke and in your onCreate method you are calling insertIntoTable(); which will insert new record every time.
Every time you run yor application you call insertintotable() method, so its is happenning
to solve this:
check the table is empty or not . if it is empty then call insertintotable() method else dont
Every time you run the app, onCreate() will be called, and thus insertIntoTable() will also be called. You have to add a checking before inserting the data. One of the way is to check whether the DB is empty or not before inserting the data.
public void insertIntoTable() {
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
Cursor c = mydb.query(TABLE, null, null, null, null, null, null);
if (c == null || c.getCount() == 0) {
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Cibo e Bevande','cibo')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Trasporti','trasporti')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Svago','svago')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Acquisti vari','acquisti')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Sanità','sanità')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Altro','altro')");
mydb.close();
}
c.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Error in inserting into table", Toast.LENGTH_LONG);
}
}

Inserting and updating data on multiple table on SQLite database

In my project, I created a SQLite database with using a class that extends SQLiteOpenHelper library in android to creating three tables in one database.
the problem is when in MainActivity class (comes below) I want to create and update a data row, instead of putting data in desired table, they saved only in "table3db" table and the other tables are still empty (I saw this condition with an application can browse SQLite databases), but I want to save each data in desired table. for example first and second data must be saved in first table and third must be in second table and fourth data integer must be save in third table.
what should I do to correct this problem??
for first step I created three Tables with below codes in DatabaseHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
private final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "db";
private static final int DATABASE_VERSION = 1;
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_VALUE = "value";
private static final String COLUMN_VALUE2 = "value2";
private static final String TABLE_NAME = "table1db";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
private static final String COLUMN_ID_2 = "_id";
private static final String COLUMN_NAME_2 = "name";
private static final String COLUMN_VALUE_2 = "value";
private static final String COLUMN_VALUE2_2 = "value2";
private static final String TABLE_NAME_2 = "table2db";
private static final String CREATE_TABLE_2 = "CREATE TABLE " + TABLE_NAME_2 + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME_2 + " INTEGER," +
COLUMN_VALUE_2 + " INTEGER," +
COLUMN_VALUE2_2 + " TEXT" +
");";
private static final String COLUMN_ID_3 = "_id";
private static final String COLUMN_NAME_3 = "name";
private static final String COLUMN_VALUE_3 = "value";
private static final String COLUMN_VALUE2_3 = "value2";
private static final String TABLE_NAME_3 = "table3db";
private static final String CREATE_TABLE_3 = "CREATE TABLE " + TABLE_NAME_3 + " (" +
COLUMN_ID_3 + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME_3 + " INTEGER," +
COLUMN_VALUE_3 + " INTEGER," +
COLUMN_VALUE2_3 + " TEXT" +
");";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_2);
Log.i(TAG, "editTexts Table created.");
db.execSQL(CREATE_TABLE);
Log.i(TAG, "Table created.");
db.execSQL(CREATE_TABLE_3);
Log.i(TAG, "Table created.");
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.i(TAG, "Object created.");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
newVersion=oldVersion+1;
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_2 + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_3 + ";");
onCreate(db);
}
public String getTableName(int tableNumber) {
String out="";
switch (tableNumber){
case 1:
out=TABLE_NAME;
case 2:
out=TABLE_NAME_2;
case 3:
out=TABLE_NAME_3;
}
return out;
}
public String getRowIdName(int tableNumber) {
String out="";
switch (tableNumber){
case 1:
out=COLUMN_ID;
case 2:
out=COLUMN_ID_2;
case 3:
out=COLUMN_ID_3;
}
return out;
}
}
Then I created this class to use DatabaseHelper class with following code by the name of DatabaseHandler
public class DatabaseHandler {
private final String TAG = "DatabaseHandler";
static final String NAME = "name";
static final String VALUE = "value";
static final String VALUE2 = "value2";
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
public DatabaseHandler(Context context) {
dbHelper = new DatabaseHelper(context);
Log.i(TAG, "DatabaseHelper Object created.");
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void insertCBox(int tableNumber, CBox checkBox) {
ContentValues cv = new ContentValues();
cv.put(NAME, checkBox.getName());
cv.put(VALUE, checkBox.getStatus());
cv.put(VALUE2, checkBox.getText());
database.insert(dbHelper.getTableName(tableNumber), NAME, cv);
Log.i(TAG, "Contact added successfully.");
}
public void deleteCheckBox(int tableNumber, int id) {
database.delete(dbHelper.getTableName(tableNumber), dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public void updateCheckBox(int tableNumber, int id,int name,int state, String text) {
ContentValues cv = new ContentValues();
cv.put(NAME, name);
cv.put(VALUE, state);
cv.put(VALUE2, text);
database.update(dbHelper.getTableName(tableNumber), cv, dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public CBox getCBox(int tableNumber, int id){
Log.i(TAG, "getCBOX started");
Cursor cursor = database.query(dbHelper.getTableName(tableNumber), null, null, null, null, null, null);
Log.i(TAG, "cursor query done");
cursor.moveToFirst();
cursor.moveToPosition(id-1);
Log.i(TAG, "cursor is here: "+ cursor.getPosition());
// cursor.moveToPosition(id--);
Log.i(TAG, "cursor moved to position successfully "+ id--);
CBox CBox = cursorToContact(cursor);
Log.i(TAG, "cursor to contact done");
cursor.close();
Log.i(TAG, "cursor closed");
return CBox;
}
public void clearTable(int tableNumber) {
database.delete(dbHelper.getTableName(tableNumber), null, null);
}
private CBox cursorToContact(Cursor cursor) {
CBox checkBox = new CBox();
Log.i(TAG, "cursor to contact > started");
checkBox.setId(cursor.getInt(0));
Log.i(TAG, "cursor to contact > getInt(0) done " + checkBox.getId());
checkBox.setName(cursor.getInt(1));
Log.i(TAG, "cursor to contact > getInt(1) done " + checkBox.getName());
checkBox.setStatus(cursor.getInt(2));
Log.i(TAG, "cursor to contact > getInt(2) done " + checkBox.getStatus());
checkBox.setText(cursor.getString(3));
Log.i(TAG, "cursor to contact > getString(3) done " + checkBox.getText());
return checkBox;
}
}
for 3rd step in my Mainactivity class I used following codes to use database and inserting and updating and saving data:
public class MainActivity extends Activity {
private DatabaseHandler dbHandler;
private static final int databaseTableNumber1=1;
private static final int databaseTableNumber2=2;
private static final int databaseTableNumber3=3;
private CBox cBox01;
private CBox cBox02;
private CBox cBox03;
private CBox cBox04;
private boolean firstRunPassed=false;
private SharedPreferences sharedperefs;
private String preferenceName = "Preferences";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.i(TAG, "On Create");
setContentView(R.layout.activity_main);
dbHandler = new DatabaseHandler(this);
final Button saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dbHandler.open();
int state;
String text;
CheckBox checkBox01= (CheckBox) findViewById(R.id.checkBox1);
if(checkBox01.isChecked()) state=1; else state=0;
dbHandler.updateCheckBox(databaseTableNumber1,1,R.id.checkBox1,state,"");
RadioGroup radioGroup01=(RadioGroup) findViewById(R.id.radioGroup1);
state= radioGroup01.getCheckedRadioButtonId();
dbHandler.updateCheckBox(databaseTableNumber1,2, R.id.radioGroup1, state,"");
EditText editText01=(EditText) findViewById(R.id.editText1);
text=editText01.getText().toString();
dbHandler.updateCheckBox(databaseTableNumber2,1, R.id.editText1,state,text);
ToggleButton toggleButton01 =(ToggleButton) findViewById(R.id.toggleButton1);
if(toggleButton01.isChecked()) state=1; else state=0;
dbHandler.updateCheckBox(databaseTableNumber3,1,R.id.toggleButton1,state,"");
dbHandler.close();
}
});
}
#Override
protected void onPause(){
super.onPause();
Log.i(TAG, "On Pause");
sharedperefs = getSharedPreferences(preferenceName, MODE_PRIVATE);
SharedPreferences.Editor editor =sharedperefs.edit();
firstRunPassed=true;
editor.putBoolean("firstRunPassed", firstRunPassed);
editor.commit();
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume");
sharedperefs=getSharedPreferences(preferenceName, MODE_PRIVATE);
firstRunPassed=sharedperefs.getBoolean("firstRunPassed", false);
dbHandler.open();
Log.i(TAG, "dbhandler opened");
if(firstRunPassed){
cBox01=new CBox();
cBox01=dbHandler.getCBox(databaseTableNumber1,1);
CheckBox checkBox01= (CheckBox) findViewById(R.id.checkBox1);
if(cBox01.getStatus()==1)
checkBox01.setChecked(true);
else
checkBox01.setChecked(false);
cBox02=new CBox();
cBox02=dbHandler.getCBox(databaseTableNumber1,2);
RadioGroup radioGroup01=(RadioGroup) findViewById(R.id.radioGroup1);
radioGroup01.check(cBox02.getStatus());
cBox03=new CBox();
cBox03=dbHandler.getCBox(databaseTableNumber2,4);
EditText editText01=(EditText) findViewById(R.id.editText1);
editText01.setText(cBox03.getText());
cBox04=new CBox();
cBox04=dbHandler.getCBox(databaseTableNumber3,1);
ToggleButton toggleButton01 =(ToggleButton) findViewById(R.id.toggleButton1);
if(cBox04.getStatus()==1)
toggleButton01.setChecked(true);
else
toggleButton01.setChecked(false);
} else {
cBox01 = new CBox(); cBox01.setId(1); cBox01.setName(R.id.checkBox1); cBox01.setStatus(0); cBox01.setText(""); dbHandler.insertCBox(databaseTableNumber1,cBox01);
cBox02 = new CBox(); cBox02.setId(2); cBox02.setName(R.id.radioGroup1); cBox02.setStatus(0); cBox02.setText(""); dbHandler.insertCBox(databaseTableNumber1,cBox02);
cBox03 = new CBox(); cBox03.setId(1); cBox03.setName(R.id.editText1); cBox03.setStatus(0); cBox03.setText("Start please"); dbHandler.insertCBox(databaseTableNumber2,cBox03);
cBox04 = new CBox(); cBox04.setId(1); cBox04.setName(R.id.toggleButton1); cBox04.setStatus(0); cBox04.setText(""); dbHandler.insertCBox(databaseTableNumber3,cBox04);
}
dbHandler.close();
Log.i(TAG, "dbhandler closed");
}
}
and the CBox is my last class, used for setting and getting data cells:
public class CBox {
private int id;
private int name;
private int Status;
private String text;
private String unit;
public long getId() {
return id;
}
public String getIdInString() {
return Long.toString(id);
}
public int getName() {
return name;
}
public int getStatus() {
return Status;
}
public String getText() {
return text;
}
public String getUnit() {
return unit;
}
public void setId(int id) {
this.id = id;
}
public void setName(int name) {
this.name = name;
}
public void setStatus(int status) {
this.Status = status;
}
public void setText(String text) {
this.text = text;
}
public void setUnit(String unit) {
this.unit = unit;
}
}
I did it at last. :D
I don't what was the problem but with changing the DatabaseHelper and Database Helperclass as below and changing input variable of functions used in this class to string, the problems had been eliminated.
here is the DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
private final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "database";
private static final int DATABASE_VERSION = 1;
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_VALUE = "value";
private static final String COLUMN_VALUE2 = "value2";
private static final String TABLE_NAME_1 = "table1db";
private static final String CREATE_TABLE_1 = "CREATE TABLE " + TABLE_NAME_1 + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
private static final String TABLE_NAME_2 = "table2db";
private static final String CREATE_TABLE_2 = "CREATE TABLE " + TABLE_NAME_2 + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
private static final String TABLE_NAME_3 = "table3db";
private static final String CREATE_TABLE_3 = "CREATE TABLE " + TABLE_NAME_3 + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_1); Log.i(TAG, "Table 1 created.");
db.execSQL(CREATE_TABLE_2); Log.i(TAG, "Table 2 created.");
db.execSQL(CREATE_TABLE_3); Log.i(TAG, "Table 3 created.");
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.i(TAG, "Object created.");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
newVersion=oldVersion+1;
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_1 + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_2 + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_3 + ";");
onCreate(db);
}
public String getTableName(String tableNumber) {
return tableNumber;
}
public String getRowIdName(String tableNumber) {
return COLUMN_ID;
}
}
and the Database Handler class:
public class DatabaseHandler {
private final String TAG = "DatabaseHandler";
static final String NAME = "name";
static final String VALUE = "value";
static final String VALUE2 = "value2";
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
public DatabaseHandler(Context context) {
dbHelper = new DatabaseHelper(context);
Log.i(TAG, "DatabaseHelper Object created.");
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void insertCBox(String tableNumber, CBox checkBox) {
ContentValues cv = new ContentValues();
cv.put(NAME, checkBox.getName());
cv.put(VALUE, checkBox.getStatus());
cv.put(VALUE2, checkBox.getText());
database.insert(dbHelper.getTableName(tableNumber), null, cv);
Log.i(TAG, "Contact added successfully.");
}
public void deleteCheckBox(String tableNumber, int id) {
database.delete(dbHelper.getTableName(tableNumber), dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public void updateCheckBox(String tableNumber, int id,int name,int state, String text) {
ContentValues cv = new ContentValues();
cv.put(NAME, name);
cv.put(VALUE, state);
cv.put(VALUE2, text);
database.update(dbHelper.getTableName(tableNumber), cv, dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public CBox getCBox(String tableNumber, int id){
Log.i(TAG, "getCBOX started");
Cursor cursor = database.query(true,dbHelper.getTableName(tableNumber), null, null, null, null, null, null, null);
Log.i(TAG, "cursor query done");
cursor.moveToPosition(id-1);
Log.i(TAG, "cursor is here: "+ cursor.getPosition());
// cursor.moveToPosition(id--);
Log.i(TAG, "cursor moved to position successfully "+ (id-1));
CBox CBox = cursorToContact(cursor);
Log.i(TAG, "cursor to contact done");
cursor.close();
Log.i(TAG, "cursor closed");
return CBox;
}
public void clearTable(String tableNumber) {
database.delete(dbHelper.getTableName(tableNumber), null, null);
}
private CBox cursorToContact(Cursor cursor) {
CBox checkBox = new CBox();
Log.i(TAG, "cursor to contact > started");
checkBox.setId(cursor.getInt(0));
Log.i(TAG, "cursor to contact > getInt(0) done " + checkBox.getId());
checkBox.setName(cursor.getInt(1));
Log.i(TAG, "cursor to contact > getInt(1) done " + checkBox.getName());
checkBox.setStatus(cursor.getInt(2));
Log.i(TAG, "cursor to contact > getInt(2) done " + checkBox.getStatus());
checkBox.setText(cursor.getString(3));
Log.i(TAG, "cursor to contact > getString(3) done " + checkBox.getText());
return checkBox;
}
}

Populate Android Listview from SQLite database

I've been trying to populate an Android Listview from a SQLite database using the code below. I have successfully done this from an array inside the same class. But in this case I'm attempting to populate it from a String array I have returned from another class. I'm new to this so am possibly doing this completely wrong. If anyone could look at the code and advise to what I'm doing wrong that'd be brilliant.
Any help would be really appreciated with this as I'm under serious pressure to get it finished, Thanks!
LoginActivity Class
public class LoginActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText txtUserName = (EditText)findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText)findViewById(R.id.txtPassword);
Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
try{
if(username.length() > 0 && password.length() >0)
{
DBUserAdapter dbUser = new DBUserAdapter(LoginActivity.this);
dbUser.open();
int UID = dbUser.Login(username, password);
if(UID != -1)
{
// TEST
//int UID = dbUser.getUserID(username, password);
//getSitesByClientname(UID);
// END TEST
// MY TEST CODE TO CHANGE ACTIVITY TO CLIENT SITES
Intent myIntent = new Intent(LoginActivity.this, ClientSites.class);
//Intent myIntent = new Intent(getApplicationContext(), ClientSites.class);
myIntent.putExtra("userID", UID);
startActivity(myIntent);
//finish();
// END MY TEST CODE
//Cursor UserID = dbUser.getUserID();
Toast.makeText(LoginActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(LoginActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e)
{
Toast.makeText(LoginActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
Method from DBHelper Class to return String Array
public String[] getSitesByClientname(String id) {
String[] args={id};
//return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
// loop through all rows and adding to array
int count;
count = myCursor.getCount();
final String[] results = new String[count];
results[0] = new String();
int i = 0;
try{
if (myCursor.moveToFirst()) {
do {
results[i] = myCursor.getString(myCursor.getColumnIndex("client_sitename"));
} while (myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
// return results array
return results;
ClientSites Class
public class ClientSites extends ListActivity {
public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
//private Cursor ourCursor = null;
private ArrayAdapter<String> adapter=null;
//#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
//dbHelper.openDataBase();
dbHelper.open();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
}
Any help with this would be great, Thanks!
Create own project with few activities. Start working with sqlite database
Create new application. Create login activity and DB helper. Trying to upload dada from DB. Reseach and development
Here is an example how to work with SQLite DB.
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper instance;
private static final String DATABASE_NAME = "UserClientBase";
private static final int DATABASE_VERSION = 1;
public static interface USER extends BaseColumns {
String TABLE_NAME = "userTable";
String NAME = "userName";
String PASSWORD = "userPassword";
}
public static interface CLIENT extends BaseColumns {
String TABLE_NAME = "clientTable";
String NAME = "clientName";
String USER_ID = "userId";
}
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS ";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS ";
private static final String UNIQUE = "UNIQUE ON CONFLICT ABORT";
private static final String CREATE_TABLE_USER = CREATE_TABLE + USER.TABLE_NAME + " (" + USER._ID
+ " INTEGER PRIMARY KEY, " + USER.NAME + " TEXT " + UNIQUE + ", " + USER.PASSWORD + " TEXT);";
private static final String CREATE_TABLE_CLIENT = CREATE_TABLE + CLIENT.TABLE_NAME + " (" + CLIENT._ID
+ " INTEGER PRIMARY KEY, " + CLIENT.NAME + " TEXT UNIQUE, " + CLIENT.USER_ID + " INTEGER);";
private DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USER);
db.execSQL(CREATE_TABLE_CLIENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE + USER.TABLE_NAME);
db.execSQL(DROP_TABLE + CLIENT.TABLE_NAME);
onCreate(db);
}
public long createUser(String newUserName, String newUserPassword) {
ContentValues values = new ContentValues();
values.put(USER.NAME, newUserName);
values.put(USER.PASSWORD, newUserPassword);
return getWritableDatabase().insert(USER.TABLE_NAME, null, values);
}
public long createClient(long userId, String newClientName) {
ContentValues values = new ContentValues();
values.put(CLIENT.USER_ID, userId);
values.put(CLIENT.NAME, newClientName);
return getWritableDatabase().insert(CLIENT.TABLE_NAME, null, values);
}
public boolean isCorrectLoginPassword(String login, String password) {
Cursor userListCursor = getReadableDatabase().rawQuery(
"SELECT * FROM " + USER.TABLE_NAME + " WHERE " + USER.NAME + " =? AND " + USER.PASSWORD
+ " =?", new String[] { login, password });
if ((userListCursor != null) && (userListCursor.getCount() > 0)) {
return true;
} else {
return false;
}
}
public Cursor getUserClientList(String userName) {
Cursor userClientList = getReadableDatabase().rawQuery(
"SELECT * FROM " + CLIENT.TABLE_NAME + " INNER JOIN " + USER.TABLE_NAME
+ " ON " + CLIENT.USER_ID + " = " + USER.TABLE_NAME + "." + USER._ID + " WHERE "
+ USER.NAME + " =?", new String[] { userName });
return userClientList;
}
}
Example of login button click listener.
String login = loginEdt.getText().toString();
String password = passwordEdt.getText().toString();
boolean loginSuccess = databaseHelper.isCorrectLoginPassword(login, password);
if(loginSuccess) {
Intent clientListIntent = new Intent(LoginActivity.this, ClientListActivity.class);
clientListIntent.putExtra(ClientListActivity.EXTRAS_LOGIN, login);
startActivity(clientListIntent);
} else {
Toast.makeText(LoginActivity.this, "Incorrect login/password", Toast.LENGTH_SHORT).show();
}
And example of listview with data from sql:
clientLv= (ListView)findViewById(R.id.listClient);
login = getIntent().getExtras().getString(EXTRAS_LOGIN);
dbHelper = DBHelper.getInstance(this);
Cursor clientList = dbHelper.getUserClientList(login);
adapter = new SimpleCursorAdapter(this, R.layout.row_client, clientList, new String[]{DBHelper.CLIENT.NAME}, new int[]{R.id.txtClientName} , SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
clientLv.setAdapter(adapter);

Categories