SQLite db duplicate values Android - java

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);
}
}

Related

Apps keeps crashing because of syntax error

please help me with this problem. My app keeps crashing because of this. What I want to do is to display the user's information from the SQLite database after they login in a text view on the profile activity. Please help me with my project. I'm still new to android studio.
this is the syntax error in my logcat
android.database.sqlite.SQLiteException: near "null": syntax error (code 1 SQLITE_ERROR): , while compiling: Select * from USER_TABLE where null=?null =?null =?
This is my Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
public static String C_EMAIL,C_PREFERENCES,C_PASSWORD;;
public DatabaseHelper(#Nullable Context context) {
super(context, constants.DB_NAME, null, constants.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(constants.CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + constants.TABLE_NAME);
onCreate(db);
}
public boolean insertInfo(String email, String preference,String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(constants.C_EMAIL, email);
values.put(constants.C_PREFERENCES, preference);
values.put(constants.C_PASSWORD , password);
long id = db.insert(constants.TABLE_NAME, null, values);
if (id == -1) {
return false;
}else {
return true;
}
}
public boolean userExists (String email){
String [] columns = {C_EMAIL};
SQLiteDatabase db = getReadableDatabase();
String selection = C_EMAIL + "=?";
String selectionArgs []= { email };
Cursor cursor = db.query(TABLE_NAME,columns,selection,selectionArgs,null,null,null);
int count = cursor.getCount();
cursor.close();
db.close();
if (count > 0)
return true;
else
return false;
}
public Cursor getData(String email, String Password){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(" Select * from "+ TABLE_NAME + " where "+ C_EMAIL + "=?" + C_PASSWORD + " =?", new String[]{email,Password});
return res;
}
}
This is my login.java
loginacc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor rs = dbHelper.getData(loginemail.getText().toString(),loginpassword.getText().toString());
if(rs.moveToFirst()){
String email = rs.getString(rs.getColumnIndex(DatabaseHelper.C_EMAIL));
String preference = rs.getString(rs.getColumnIndex(DatabaseHelper.C_PREFERENCES));
String password = rs.getString(rs.getColumnIndex(DatabaseHelper.C_PASSWORD));
Toast.makeText(login.this,"Login Successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(login.this,profile.class);
intent.putExtra("email", email);
intent.putExtra("preference", preference);
intent.putExtra("password", password);
startActivity(intent);
if(rs != null && rs.isClosed()){
rs.close();
}
}
else{
Toast.makeText(login.this,"Invalid Login", Toast.LENGTH_SHORT).show();
}
}
});
}
This is my profile.java
public class profile extends AppCompatActivity {
DatabaseHelper dbHelper;
TextView pemail,ppreferences, ppassword;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
dbHelper = new DatabaseHelper(this);
pemail = findViewById(R.id.pemail);
ppreferences = findViewById(R.id.ppreferences);
ppassword = findViewById(R.id.ppassword);
pemail.setText(getIntent().getStringExtra("email"));
ppreferences.setText(getIntent().getStringExtra("preferences"));
ppassword.setText((getIntent().getStringExtra("password")));
Thanks for your help!
You are declaring 3 static variables here:
public static String C_EMAIL,C_PREFERENCES,C_PASSWORD;
without assigning any value to them so they are all null.
When you use them inside getData():
" Select * from "+ TABLE_NAME + " where "+ C_EMAIL + "=?" + C_PASSWORD + " =?"
the result is:
Select * from USER_TABLE where null=?null =?null =?
(it's not clear from your code where the 3d null =? comes from)
What you want is (I guess) to use these variables for the column names of the table.
So change the declarations to:
public static String C_EMAIL = "email"; // change to the actual column name
public static String C_PASSWORD = "password"; // change to the actual column name
public static String C_PREFERENCES = "preferences"; // change to the actual column name
Also add the AND operator in the sql statement:
"Select * from "+ TABLE_NAME + " where "+ C_EMAIL + "= ? AND " + C_PASSWORD + " = ?"
Edit
Inside the method insertInfo() you use constants.C_EMAIL, constants.C_PREFERENCES and constants.C_PASSWORD which it seems are the names of your columns.
If so, then use them also in the sql statement and drop the static variables:
"Select * from "+ TABLE_NAME + " where "+ constants.C_EMAIL + "= ? AND " + constants.C_PASSWORD + " = ?"

can not Creating tables in sqlite database on android

I can not create a table. It shows that the database is created and I can also insert a row, but the table is not created.
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int Database_version = 2;
public static final String Tag = DatabaseOperations.class.getSimpleName();
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT "+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ");";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null,Database_version);
Log.d("Tag", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb) {
sdb.execSQL(SQL_CREATE_ENTRIES);
Log.d("Tag", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void putInformation(DatabaseOperations drop, String name, String pass, String email) {
SQLiteDatabase SQ = drop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_ID, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Tag", "inert a row");
}
public Cursor getInformation(DatabaseOperations dop) {
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] coloumns = {TableData.TableInfo.USER_ID, TableData.TableInfo.USER_PASS, TableData.TableInfo.USER_EMAIL};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, null, null, null, null, null);
return CR;
}
}
You're missing a , between USER_EMAIL and USER_PASS columns in the CREATE TABLE.
After adding it you can uninstall your app to recreate the database. When is SQLiteOpenHelper onCreate() / onUpgrade() run?
You miss comma in USER PASS type.Uninstall the application and install it again each time you add something new to sqlite database because the table structure has been changed.So you need to reinstall the new application .
The code should be like this
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT ,"+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ")";

Show Data from Multiple Tables with connected id in SQLite

I have two tables in my SQLite database, first users and second jobs, where a user can have multiple jobs to do
Data in users table
id name
1 Me
2 You
where id generated through : id integer primary key autoincrement
Data in jobs table
id jobname userid
1 JobA 2
2 JobB 2
3 JobC 1
where id generated through : id integer primary key autoincrement
where user_id fetched from users table
Now, I would like to loop through all the users and jobs table one by one, if user has some job to do then need to show Toast
JobC assigned to user1
DatabaseHandler.java:
public class DatabaseHandler extends SQLiteOpenHelper {
..................
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TABLE_USERS +
"(id integer primary key autoincrement," +
" name text);");
db.execSQL("CREATE TABLE " + TABLE_JOBS +
"(id integer primary key autoincrement," +
" jobname text" +
" userid long);");
}
// Insert data into users table
public long InsertUsers(String name) {
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("name", name);
long rows = db.insert(TABLE_USERS, null, Val);
db.close();
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
// Insert data into jobs table
public long InsertJobs(String jobname, long userid) {
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("jobname", jobname);
Val.put("userid", userid);
long rows = db.insert(TABLE_JOBS, null, Val);
db.close();
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
public String[] getUsersId() {
String selectQuery = "SELECT id FROM " + TABLE_USERS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;
if (cursor.moveToFirst()) {
do {
int id_row=cursor.getInt(cursor.getColumnIndex("id"));
Log.d("TAG","id is ::"+id_row);
} while (cursor.moveToNext());
}
db.close();
return data;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_JOBS);
onCreate(db);
}
}
And in MainActivity.java:
DatabaseHandler dh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dh = new DatabaseHandler(MainActivity.this);
buttonGetData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dh.getUsersId();
}
});
}
You can do it using join:
db.rawQuery("SELECT j.jobname, u.name FROM jobs j JOIN users u ON j.userid=u.id");
I won't give you the exact code but try to execute the query something similar to this. And do a little research before asking the question.
String newQuery="SELECT db1.your_column db2.you_coloum2 from table1 db1, table2 db2 where db2.u_id=db1.id;
fetch the results using Cursor

Why Can't I update the values of the sqlite database

public void onClick(View v) {
if (btn66 == v) {
ContentValues value = new ContentValues();
value.put(DBhelper.Amount, txtBudget.getText().toString());
value.put(DBhelper.Description, txr.getText().toString());
if(DBhelper.Amount == null)
{
db = helper.getWritableDatabase();
db.insert(DBhelper.TABLE2, null, value);
db.close();
clearfield();
Toast.makeText(this, "Budget add Successfully", Toast.LENGTH_LONG).show();
fetchData2();
Intent i = new Intent(addbudget.this, MainActivity.class);
startActivity(i);
}
else{
db = helper.getWritableDatabase();
db.update(DBhelper.TABLE2, value, "_id "+"="+1, null);
db.close();
fetchData2();
Toast.makeText(this, "Update Successfully", Toast.LENGTH_LONG).show();
clearfield();
}
}
}
The above one is my code to add and update values to the sqlite database,after I include the Update method in my code,my add function is not working and my update function also not working.Is there any problem with my code,but I didn't get any error message.
This is my Database tables
static final String C_ID = "_id";
static final String Name = "name";
static final String B_ID = "_id";
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE " + TABLE1+ "(" +C_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," +Name+ " text unique not null)");
db.execSQL("CREATE TABLE " + TABLE2+ "(" +B_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," +Description+ " text,"
+Amount+ " text, FOREIGN KEY ("+Description+") REFERENCES "+TABLE1+"("+Name+"));");
}
Try using something like this to check if a row with the given name is present in the table1:
public boolean checkIfRowPresent(String name) {
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor =
db.query(DBhelper.TABLE1, null, DBHelper.NAME + "='" + name + "'", null, null, null,
null, null);
boolean ret = false;
if (cursor.getCount() > 0) {
ret = true; // There is a row present in table1 with the given name
}
db.close();
return ret;
}
You should be calling it with this:
checkIfRowPresent(txr.getText().toString())
Let me know if it helps?

Android SQLite issue - table __ has no column named ___

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)
{
}
}

Categories