i have a spinner filled with value (category from category table) from sqlite now i need a select query to retrieve items into listView. such that on spinner selection change listview values also change . items are coming from another table (items).cid is foreign key in items table and cid is primary key in category table i tried this but showing empty listview....
String select = "SELECT " +
Support.KEY_INAME + " FROM "
+ Support.TABLE_ITEMS + " LEFT JOIN "
+ Support.TABLE_CAT + " ON "
+ (Support.TABLE_ITEMS + "." + Support.KEY_CID) +" = "
+ (Support.TABLE_CAT + "." + Support.KEY_CID)
+ " WHERE " + Support.TABLE_CAT + "." + Support.KEY_CID + " =?";
this is my spinner selection and loading listview data code...
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
Spinner spinner = (Spinner)parent;
if (spinner.getId() == R.id.spinner1) {
dbRepo = new DBRepo(getApplicationContext());
final List<Support> list = dbRepo.getItems1();
adapter = new Custom(Category.this, R.layout.view_entry, list);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
adapter.notifyDataSetChanged();
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setAdapter(adapter);
}
the above query is true and alternatively i solve my problem using these two queries
String selectQuery = "SELECT * FROM " + TABLE_ITEM + " WHERE " + KEY_CID + " ='" + cid + "'";
Cursor c = db.rawQuery(selectQuery, null);
OR
Cursor c = db.rawQuery("SELECT * FROM item_table WHERE _CategoryID =? " ,new String[]{cid}, null );
and change also change the code spinner.setonItemSelected like this
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
handler = new DBSQLite(getBaseContext());
String selected = (String) parent.getItemAtPosition(position);
// Toast.makeText(getApplicationContext(), selected, Toast.LENGTH_SHORT).show();
String cid = handler.getCid(selected);
final ArrayList<Support> item = handler.getItems(cid);
adapter = new CustomAdapter(AvailableItems.this, R.layout.available_view, item);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Related
I have a Class of User that has name,id,email and other attributes, and i am making a movie app.The users for this app are saved inside a database (SQLite databse) and i want to add the movies that this person rated to the same database by adding the Title of each movie to a list and adding the rating to another list in the Users database.
so the database would look something like:
Users
Email Name Password (List<String>) RatedMovies (List<Float>)Ratings
u1#test.com user1 asd32r2sa!#3 ["firstMovie","secondMovie"] [2.5,5.0]
u2#test.com user2 asdasd12%#s1 ["MovieTest"] [9.5]
u3#test.com user dfg234DS##sad ["Testing","firstMovie"] [7.0,2.0]
so how can i create those RatedMovies and Ratings lists in SQLite database in android (i already created the database) and how can i add items or read the items from it?
Here is the code used for DataBaseHelper and how i added the information for each user:
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;
import java.util.List;
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DataBaseHelper";
public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context,name,factory,version);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE USER(EMAIL TEXT PRIMARY KEY,Password TEXT,NAME TEXT,PHONE LONG,GENDER TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public boolean insertUser (User user){
SQLiteDatabase sqLiteDatabase=getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("EMAIL",user.getEmail());
contentValues.put("Password",user.getPassword());
contentValues.put("NAME",user.getName());
contentValues.put("PHONE",user.getPhone());
contentValues.put("GENDER",user.getGender());
try {
sqLiteDatabase.insert("USER",null,contentValues);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public Cursor getAllUsers() {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
return sqLiteDatabase.rawQuery("SELECT * FROM USER ORDER BY EMAIL ASC", null); //set it to sort by name ascending
}
public void updateName(String newName, String email, String oldName,String newPassword,String oldPassword){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE USER" + " SET " + "NAME" +
" = '" + newName + "' WHERE " + "EMAIL" + " = '" + email + "'" +
" AND " + "NAME" + " = '" + oldName + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newName);
db.execSQL(query);
String query2 = "UPDATE USER" + " SET " + "Password" +
" = '" + newPassword + "' WHERE " + "EMAIL" + " = '" + email + "'" +
" AND " + "Password" + " = '" + oldPassword + "'";
Log.d(TAG, "updateName: query: " + query2);
Log.d(TAG, "updateName: Setting name to " + newPassword);
db.execSQL(query);
}
I'm currently working on UWP project and I use sqlite database.In this project I want to update field in sqlite table(classroomteam).When I entered value with apostrophe(') It gives error saying "SQLite.SQLiteException: 'near "s": syntax error'"
This is the code that I used to save updated data to the table
public static async Task UpdateTeamName(ClassroomTeamItem classroomTeamItem)
{
IWAppUtils.PrintDebug("====Start ", CLASS_NAME, "UpdateTeamName()");
ClassroomTeam classroomTeam = new ClassroomTeam()
{
TeamName = classroomTeamItem.TeamName,
Id = classroomTeamItem.Id,
};
String teamName = classroomTeamItem.TeamName;
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(IWSQLite.DATABASE_NAME);
//Task<int> a = conn.UpdateAsync(configInfo);
await conn.ExecuteAsync("UPDATE classroomteam SET TeamName = '" + classroomTeamItem.TeamName + "' WHERE Id = '" + classroomTeam.Id + "'");
await conn.CloseAsync();
IWAppUtils.PrintDebug("====End ", CLASS_NAME, "UpdateTeamName()");
}
I tried this to solve my issue and what I did is applying new String[] {classroomTeamItem.TeamName } in the query.Then I didn't get any error but the value is stored as System.String[] not the value I entered in sqlite table.The code I tried as follows.
public static async Task UpdateTeamName(ClassroomTeamItem classroomTeamItem)
{
IWAppUtils.PrintDebug("====Start ", CLASS_NAME, "UpdateTeamName()");
ClassroomTeam classroomTeam = new ClassroomTeam()
{
TeamName = classroomTeamItem.TeamName,
Id = classroomTeamItem.Id,
};
String teamName = classroomTeamItem.TeamName;
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(IWSQLite.DATABASE_NAME);
//Task<int> a = conn.UpdateAsync(configInfo);
await conn.ExecuteAsync("UPDATE classroomteam SET TeamName = '" + new String[] { classroomTeam.TeamName } + "' WHERE Id = '" + classroomTeam.Id + "'");
await conn.CloseAsync();
IWAppUtils.PrintDebug("====End ", CLASS_NAME, "UpdateTeamName()");
}
I would appreciate if anyone can help me to resolve this issue.
The sql string about how to update field is:
string SQL_UPDATE = "UPDATE " + TABLE_NAME + " SET Value = ? WHERE Key = ?";
So you could try to change your update string to
await db.ExecuteAsync("UPDATE classroomteam SET TeamName = " + classroomTeamItem.TeamName + " WHERE Id = " + classroomTeam.Id);
Or you can query for the specific data is most straightforwardly done using the Table method and then update your field. For example:
private async void update(ClassroomTeamItem classroomTeamItem)
{
var query = db.Table<ClassroomTeam>().Where(s => s.Id==classroomTeam.Id);
var result = await query.ToListAsync();
foreach (var s in result)
{
s.TeamName = classroomTeamItem.TeamName;
await db.UpdateAsync(s);
}
}
I would like to delete a row in tableview but also in the
underlying SQLite Database which populate the tableview
Here I get the selectedRow
public void deleteDBRow() {
if (tableV.getSelectionModel().getSelectedItem() != null) {
Bew selBew = tableV.getSelectionModel().getSelectedItem();
System.out.println(selBew.getName());
}
}
and can delete it with casual code
DELETE FROM Table WHERE name = ""+selBew.getName()");
But I would like to delete the entry in the sqlite database also
From time to time I have rows with the same text in every column - so this way
was critical - can I use rowID to delete the selected row in sqlite?
Here one try from me to get rowid in tableview
ObservableList bewList = FXCollections.observableArrayList();
try {
String sql = "SELECT rowID, Name, Date, Action, Info FROM tab1";
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestB1.db");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
bewList.add(new Bew(rs.getInt("rowID"), rs.getString("name"), rs.getString("date"),
rs.getString("action"), rs.getString("Info")));
System.out.println("rs.next : " + rs.getInt("rowID") +" - " + rs.getString("date") +" " +
rs.getString("action") +" " + rs.getString("Info"));
}
}catch (Exception e) {
System.out.println("SQLiteDB.getData ---> Error RS");
System.err.println("*E"+e.getClass().getName() + ": " + e.getMessage());
}
return bewList;
String sql = "CREATE TABLE IF NOT EXISTS tab1" +
"(rowID INT PRIMARY KEY," +
"NAME CHAR(50) NOT NULL ,"+
"DATE CHAR(15) ,"+
"ACTION CHAR(50) ,"+
"INFO CHAR(3));";
conn.createStatement().executeUpdate(sql);
rowID ist always 0 - don't know why ???
edit:
Controller
ObservableList bewList = DB.getData();
tableV.setItems(bewList);
Edit:
Maybe error in here - add data
i add 4 values - rowid missing??
public void add(String Name, String Date, String Action, String Info) {
try {
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestB2.db");
stmt = conn.createStatement();
String ValStr = "\'"+Name+"\' ,\'"+Date+"\',\'"+Action+"\' ,\'"+Info+"\'";
String sql = "INSERT INTO tab1 (rowID, NAME,DATE,ACTION, INFO) VALUES ("+ValStr+")";
// System.out.println("Button Click add"+conn.createStatement().toString());
stmt.executeUpdate(sql); //geƤndert
ObservableList<Bew> list = getData();
conn.close();
System.out.println("DB ROW add");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
I've created database and inserted the values to the tables. Now I'm trying to select a data but I'm getting following error:
I've pasted my entire SQLHelper class code. Please can anyone let me know where I'm doing mistake?
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "MyDB.db";
// Table Names
private static final String TABLE_USERS = "Users";
private static final String TABLE_SCORES = "Scores";
private static final String TABLE_SYNCSTATUS = "SyncStatus";
// Common column names
private static final String KEY_ID = "id";
private static final String KEY_CREATED_AT = "created_at";
// USERS Table - column names
private static final String KEY_USERID = "userID";
private static final String KEY_USERNAME = "userName";
private static final String KEY_USERPSWD = "userPswd";
private static final String KEY_FIRSTNAME = "firstName";
private static final String KEY_LASTNAME = "lastName";
// SCORES Table - column names
private static final String KEY_USER_ID = "userID";
private static final String KEY_GAME_ID = "gameID";
private static final String KEY_SCORES = "scores";
// SYNCSTATUS Table - column names
private static final String KEY_STATRDATE = "startDate";
private static final String KEY_ENDDATE = "endDate";
private static final String KEY_STATUS = "status";
// Table Create Statements
// USERS table create statement
private static final String CREATE_TABLE_USERS = "CREATE TABLE IF NOT EXISTS "
+ TABLE_USERS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID
+ " TEXT," + KEY_USERNAME + " INTEGER," + KEY_USERPSWD + " TEXT,"
+ KEY_FIRSTNAME + " TEXT," + KEY_LASTNAME + " TEXT,"
+ KEY_CREATED_AT + " DATETIME" + ")";
// Scores table create statement
private static final String CREATE_TABLE_SCORES = "CREATE TABLE IF NOT EXISTS "
+ TABLE_SCORES + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USER_ID
+ " INTEGER," + KEY_GAME_ID + " INTEGER," + KEY_SCORES + " INTEGER,"
+ KEY_CREATED_AT + " DATETIME" + ")";
// Sync table create statement
private static final String CREATE_TABLE_SYNCSTATUS = "CREATE TABLE IF NOT EXISTS "
+ TABLE_SYNCSTATUS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_STATRDATE + " DATETIME," + KEY_ENDDATE + " DATETIME," + KEY_STATUS + " INTEGER,"
+ KEY_CREATED_AT + " DATETIME" + ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_USERS);
db.execSQL(CREATE_TABLE_SCORES);
db.execSQL(CREATE_TABLE_SYNCSTATUS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SYNCSTATUS);
// create new tables
onCreate(db);
}
public int validateUserLogin(String uname, String pswd)
{
SQLiteDatabase db = this.getReadableDatabase();
String[] whereArgs = new String[]{uname, pswd};
String query = "SELECT "+KEY_USERID+" FROM "+TABLE_USERS+" WHERE "+KEY_USERNAME+" = ? AND "+KEY_USERPSWD+" = ?";
try{
Cursor cur= db.rawQuery(query, whereArgs);
//Boolean b = cur.moveToFirst();
if (cur.moveToFirst() == true)
{
return cur.getInt(cur.getColumnIndex(KEY_USERID));
}
else
return -1;
}catch(Exception e){
return -1;
}
}
public void insertValues(UsersCredential uc){
SQLiteDatabase db= this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(KEY_USERID, uc.getUserID());
cv.put(KEY_USERNAME, uc.getUserName());
cv.put(KEY_USERPSWD, uc.getUserPassword());
cv.put(KEY_FIRSTNAME, uc.getUserFirstName());
cv.put(KEY_LASTNAME, uc.getUserLastName());
cv.put(KEY_CREATED_AT, getDateTime());
db.insert(TABLE_USERS, null, cv);
}
public void deleteRecords() {
SQLiteDatabase db= this.getWritableDatabase();
db.execSQL("delete from Users");
}
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
}
I'm getting the Exception in validateUserLogin(String uname, String pswd) method, What is wrong in my code?
Your query does not return any data.
You must check the return value of moveToFirst before you can try to access the data.
I'm getting results from my rawQuery that duplicate and follow an OR logic as opposed to an AND logic i.e. I will get all the entries that contain "tuxedo" as well as all the entries that contain "hotel" when I only want the ones that contain both.
This is my method:
public ArrayList<Integer> getAdvancedResultIDList(String[] search)
{
ArrayList<String> queryList = new ArrayList<String>();
ArrayList<Integer> resultsList = new ArrayList<Integer>();
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
this.mDB = GamesList.mDBHelper.getDatabase();
Cursor searchCursor = null;
try
{
//TODO:
// for each string in the search array search the whole of searchable table. Check that the results are only of the values that
// contain all the search strings, and add the id of that row to the results ArrayList
for(int i = 0; i < search.length; i++)
{
String query;
String s = '"' + search[i] + '"';
query = "SELECT " + KEY_ID + " FROM "+ SEARCHABLE_TABLE + " WHERE " + SEARCHABLE_TABLE + " MATCH " + s;
queryList.add(query);
}
String[] queryArray = queryList.toArray(new String[queryList.size()]);
String unionQuery = builder.buildUnionQuery(queryArray, KEY_ID + " ASC", null);
searchCursor = this.mDB.rawQuery(unionQuery, null);
int colId = searchCursor.getColumnIndex(KEY_ID);
String resultID;
for(searchCursor.moveToFirst(); !searchCursor.isAfterLast();searchCursor.moveToNext())
{
resultID = searchCursor.getString(colId);
Integer Id = Integer.parseInt(searchCursor.getString(colId));
resultsList.add(Id);
}
searchCursor.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
this.mDB.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
return resultsList;
}
Thanks in advance and Happy New Year!
The documentation explains how to use multiple search terms:
SELECT id FROM searchTable WHERE searchTable MATCH 'tuxedo hotel'