I want to create a android sqlite table with only one single row, for insert or update and read, how can i do that, cause i only know how to create mulitiple row
the table contain only 1 single row , is for user insert data and store , when read the data will come out , and last the update mean it will override the data which in that row.
this is my DBHelperNote.java
public static final String TABLE_GOAL = "goal";
public static final String GOAL_ID= "goal_id";
public static final String GENDER = "gender";
public static final String AGE = "age";
public static final String HEIGHT = "height";
public static final String WEIGHT = "weight";
public static final String GOAL = "goal";
private static final String CREATE_TABLE_GOAL = "CREATE TABLE " + TABLE_GOAL + " (" +
GOAL_ID + " INTEGER PRIMARY KEY, " +
GENDER + " text not null, " +
AGE + " text not null, "+
HEIGHT + " text not null, "+
WEIGHT + " text not null, "+
GOAL + " text not null "+
" );";
this is SQLControlerWeight.java
public void insertGoal(String gd,String age,String hg,String wg,,String gl) {
ContentValues cv = new ContentValues();
cv.put(DBHelperNote.GENDER, gd);
cv.put(DBHelperNote.AGE, age);
cv.put(DBHelperNote.HEIGHT, hg);
cv.put(DBHelperNote.WEIGHT, wg);
cv.put(DBHelperNote.GOAL, gl);
database.insert(DBHelperNote.TABLE_GOAL, null, cv);
}
public Cursor readGoal() {
String[] allColummn = new String[] {
DBHelperNote.GOAL_ID,
DBHelperNote.GENDER,
DBHelperNote.AGE,
DBHelperNote.HEIGHT,
DBHelperNote.WEIGHT,
DBHelperNote.GOAL,
};
Cursor c = database.query(DBHelperNote.TABLE_GOAL, allColummn, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
this actually is the method to read data put but it is from array mean multiple row , but i don't Know how to change it to only call one row
dbconnection = new SQLControlerWeight(this);
dbconnection.openDatabase();
Cursor cursor = dbconnection.readGoal();
String[] from = new String[]{
DBHelperNote.GOAL_ID,
DBHelperNote.GENDER,
DBHelperNote.AGE,
DBHelperNote.HEIGHT,
DBHelperNote.WEIGHT,
DBHelperNote.GOAL,
};
int[] to = new int[]{
R.id.goal_id,
R.id.field_gender,
R.id.field_age,
R.id.field_height,
R.id.field_weight,
R.id.field_goal,
};
As you will be having GOAL_ID ones inserted you can modify you insert function as
public void insertGoal(String goal_id, String gd,String age,String hg,String wg,,String gl) {
ContentValues cv = new ContentValues();
if (goal_id != null){
cv.put(DBHelperNote.GOAL_ID, goal_id);
}
cv.put(DBHelperNote.GENDER, gd);
cv.put(DBHelperNote.AGE, age);
cv.put(DBHelperNote.HEIGHT, hg);
cv.put(DBHelperNote.WEIGHT, wg);
cv.put(DBHelperNote.GOAL, gl);
database.replace(DBHelperNote.TABLE_GOAL, null, cv);
}
Modification done is changed insert to replace, which will make sure if primary key value is provided and row exists with that id then it will replace the existing row without creating new one. Most important is the if condition for checking whether goal_id is null or not, if null then don't provide that in contentvalue.
Modify the if condition properly for proper comparison for Goal_id as i have just used the one i can visualize from your question content.
Use RawQuery method its little bit easier.
c1 = db.rawQuery("select * from Table_Name", null);
c1.moveToFirst();
do {
str = c1.getString(c1.getColumnIndex("FieldName"));
ab.add(str);
} while (c1.moveToNext());
Related
I have following table
private static final String DB_TABLE = "create table user (id integer primary key autoincrement, "
+ "username text not null, password text not null, tel text not null, info text not null, job text);";
How can I fetch data using cursor and convert it to string? because I am getting null Should I have set gets?
I have to fetch job and info by username and password?
Cursor theUser = dbHelper.fetchUser(thisUsername, thisPassword);
if (theUser != null) {
// How here also fetch a info and job in String?
startManagingCursor(theUser);
if (theUser.getCount() > 0) {
//saveLoggedInUId(theUser.getLong(theUser.getColumnIndex(DatabaseAdapter.COL_ID)), thisUsername, thePassword.getText().toString());
stopManagingCursor(theUser);
theUser.close();
// String text = dbHelper.getYourData();
Intent i = new Intent(v.getContext(), InfoActivity.class);
startActivity(i);
}
//Returns appropriate message if no match is made
else {
Toast.makeText(getApplicationContext(),
"You have entered an incorrect username or password.",
Toast.LENGTH_SHORT).show();
// saveLoggedInUId(0, "", "");
}
stopManagingCursor(theUser);
theUser.close();
}
else {
Toast.makeText(getApplicationContext(),
"Database query error",
Toast.LENGTH_SHORT).show();
}
}
private static final String LOGIN_TABLE = "user";
//Table unique id
public static final String COL_ID = "id";
//Table username and password columns
public static final String COL_USERNAME = "username";
public static final String COL_PASSWORD = "password";
private static final String KEY_PHONE = "tel";
private static final String INFO = "info";
private static final String JOB = "info";
public Cursor fetchUser(String username, String password) {
Cursor myCursor = database.query(LOGIN_TABLE,
new String[] { COL_ID, COL_USERNAME, COL_PASSWORD },
COL_USERNAME + "='" + username + "' AND " +
COL_PASSWORD + "='" + password + "'", null, null, null, null);
if (myCursor != null) {
myCursor.moveToFirst();
}
return myCursor;
}
thank you in advance!!!
Update:
String name = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.COL_USERNAME));
String phone = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.KEY_PHONE));
String tel = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.KEY_PHONE));
String info = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.INFO));
String job = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.JOB));
String id = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.COL_ID));
How can I wrote request fir this one:
public Cursor fetchAllUsers() {
return database.query(LOGIN_TABLE, new String[] { COL_ID, COL_USERNAME,
COL_PASSWORD }, null, null, null, null, null);
}
To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. The isAfterLast() method allows to check if the end of the query result has been reached.
Cursor provides typed get*() methods, e.g. getLong(columnIndex), getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing.
Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table.
A Cursor needs to be closed with the close() method call when you are finished with it.
Your code should look something like this to get the info column, but please note in your question that the JOB and INFO columns have the same string, so they'll return the same column index until you fix that
String info = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.INFO))
I'm trying to create a score database that increments the players 'score' by one when they win by calling updateScore(). The primary key and player number are identical (I may need to restructure the DB at some point) and the final column is 'score'.
Below is the code that initially sets the score (this works), the method that gets the score (also works fine) and the method that updates the score, incrementing the relevant players score by 1. This is the part the doesn't work, is there something I should be doing differently here? Thanks.
/** Add a record to the database of two player scores
* #param playerId
* #param playerScore
**/
public void addScore (int playerId, int playerScore) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID, playerId);
values.put(PLAYERNUM, playerId);
values.put(SCORE, playerScore);
database.insert(TABLE_2PSCORES, null, values);
database.close();
}
// Get the score
public int getScore (int playerId) {
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.query(TABLE_2PSCORES, COLUMNS, " player = ?", new String[] {String.valueOf(playerId) }, null, null, null, null); //null = groupby, having, orderby, limit
if (cursor !=null) { cursor.moveToFirst(); }
int output = cursor.getInt(2);
return output;
}
// Increment score by 1
public void updateScore (int playerId) {
SQLiteDatabase database = this.getWritableDatabase();
int playerScore = getScore(playerId);
int playerScoreInc = playerScore ++;
ContentValues values = new ContentValues();
values.put("score", playerScoreInc);
database.update(TABLE_2PSCORES, values, PLAYERNUM+" = ?", new String[] {String.valueOf(playerId)} );
database.close();
}
int playerScoreInc = playerScore ++;
This assigns playerScore to playerScoreInc and only after that increments playerScore. To first increment and then assign, change to ++playerScore.
However, you can do it all in SQL, no need to fetch score, increment it in code and then update the database table separately:
database.execSQL("UPDATE " + TABLE_2PSCORES + " SET " + SCORE + "=" + SCORE + "+1" + " WHERE " + PLAYERNUM + "=?",
new String[] { String.valueOf(playerId) } );
The other answers solve the original question, but the syntax makes it hard to understand. This is a more general answer for future viewers.
How to increment a SQLite column value
SQLite
The general SQLite syntax is
UPDATE {Table} SET {Column} = {Column} + {Value} WHERE {Condition}
An example of this is
UPDATE Products SET Price = Price + 1 WHERE ProductID = 50
(Credits to this answer)
Android
Now that the general syntax is clear, let me translate that into Android syntax.
private static final String PRODUCTS_TABLE = "Products";
private static final String ID = "ProductID";
private static final String PRICE = "Price";
String valueToIncrementBy = "1";
String productId = "50";
String[] bindingArgs = new String[]{ valueToIncrementBy, productId };
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("UPDATE " + PRODUCTS_TABLE +
" SET " + PRICE + " = " + PRICE + " + ?" +
" WHERE " + ID + " = ?",
bindingArgs);
db.close();
TODO
This answer should be updated to use update rather than execSQL. See comment below.
Change
int playerScoreInc = playerScore ++;
to
int playerScoreInc = ++ playerScore;
I think this will work
// Increment score by 1
public void updateScore (int playerId) {
SQLiteDatabase database = this.getWritableDatabase();
int playerScore = getScore(playerId);
int playerScoreInc = ++ playerScore;
ContentValues values = new ContentValues();
values.put("score", playerScoreInc);
database.update(TABLE_2PSCORES, values, PLAYERNUM+" = ?", new String[] {String.valueOf(playerId)} );
database.close();
}
Have you tried debugging? Try debugging this line:
int playerScoreInc = playerScore ++;
The playerScoreInc doesn't increment.
Im trying to get the data of an entire column into a string array. My database contains two columns Id and Names. I want to read all the entries of the names column and put it into a array. Please help.
EDIT #1:
Im using the following code but i can get only one name with this code.
String query = "Select * FROM " + TABLE_APPS + " WHERE " + COLUMN_NAME + " = \"" + productname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
cursor.moveToFirst();
name = cursor.getString(1);
cursor.close();
} else {
name = null;
}
db.close();
int total=0;
Cursor csr=sdb.query("tablename", null, null,null,null,null,null);
csr.moveToFirst();
while(!csr.isAfterLast())
{
total++;
csr.moveToNext();
}
String strarray[] = new String[total];
Cursor csrs=sdb.query("tablename", null, null,null,null,null,null);
csrs.moveToFirst();
int aray=0;
while(!csrs.isAfterLast())
{
strarray[aray]=csrs.getString(1);
aray++;
csrs.moveToNext();
}
I have a page which can retrieve user data from database
but after whole day of trying, I am only able to get the table column name but not the value inside.
this is my code to create database
public static final String LASTLOGIN = "lastuser";
public static final String USER_ID = "suser_id";
public static final String USER_NAME = "suser_name";
public static final String USER_PASSWORD = "spassword";
public static final String PRIME_ID = "id";
private static final String TABLE_USER =
"create table "+ LASTLOGIN+" ("
+PRIME_ID+" integer primary key autoincrement, "
+ USER_ID + " text, "
+ USER_NAME +" text, "
+USER_PASSWORD+" text); ";
and here is the function implemented to get user data
public Cursor getuser()
{
String[] columns = new String[]{PRIME_ID, USER_NAME, USER_PASSWORD};
Cursor cursor = sqLiteDatabase.query(
LASTLOGIN, columns, null, null, null, null, PRIME_ID +" DESC");
Log.d("TAG", columns[1]);
return cursor;
}
and here is my code to display the result
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.getuser();
String[] resultvalue = new String{
SQLiteAdapter.PRIME_ID,SQLiteAdapter.USER_NAME, SQLiteAdapter.USER_PASSWORD};
Toast.makeText(this, resultvalue[0]+resultvalue[1], Toast.LENGTH_LONG).show();
and the toast result only show the column name but not the value inside, is there any mistake i made? and I want to set limit to 1, but where to set it?
Thanks for helping me
the way you try reading the values is completly wrong.
you create an array
String[] resultvalue = new String[]{
SQLiteAdapter.PRIME_ID,
SQLiteAdapter.USER_NAME,
SQLiteAdapter.USER_PASSWORD};
after that you read the values 0 and 1 from this array.
Your toast works absolutly correctly becouse inside this array you define the column names!
If you want to show the values from your query do it this way:
while(cursor.moveToNext()){
Integer str1 = str 1 + cursor.getInteger(1);
String str2 =str2 + cursor.getString(2);
Toast.makeText(this, str1 + str2, Toast.LENGTH_LONG).show();
}
or a better way receiving the correct index:
cursor.getInteger( cursor.getColumnIndex(SQLiteAdapter.PRIME_ID) );
cursor.getString( cursor.getColumnIndex(SQLiteAdapter.USER_NAME) );
Please note when retrieving data from a database, you store it in a Cursor in the memory and hence can only access it using that particular Cursor object, which you have used in the following line of code.
Cursor cursor = mySQLiteAdapter.getuser();
The Following line retrieves the column names and not the values.
String[] resultvalue = new String[]{SQLiteAdapter.PRIME_ID,SQLiteAdapter.USER_NAME, SQLiteAdapter.USER_PASSWORD};
So the following is doing what you have asked it to do, retrieve column names not values
Toast.makeText(this, resultvalue[0]+resultvalue[1], Toast.LENGTH_LONG).show();
You need something like following:
if(cursor.getCount() != 0)
{
while(cursor.moveToNext())
{
resultvalue [0] = csr.getString(0);
resultvalue [1] = csr.getString(1);
//....
}
}
Hope this helps
here is my solution:
final String TABLE_NAME = "table_name";
String selectQuery = "SELECT Column FROM "+TABLE_NAME+" WHERE column='"+some_value+"'";
SQLiteDatabase db = this.openDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = new String[cursor.getCount()];;
int i = 0;
if (cursor.moveToFirst()) {
do {
i=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));
} while (cursor.moveToNext());
}
cursor.close();
I'm attempting to do the following SQL query within Android:
String names = "'name1', 'name2"; // in the code this is dynamically generated
String query = "SELECT * FROM table WHERE name IN (?)";
Cursor cursor = mDb.rawQuery(query, new String[]{names});
However, Android does not replace the question mark with the correct values. I could do the following, however, this does not protect against SQL injection:
String query = "SELECT * FROM table WHERE name IN (" + names + ")";
Cursor cursor = mDb.rawQuery(query, null);
How can I get around this issue and be able to use the IN clause?
A string of the form "?, ?, ..., ?" can be a dynamically created string and safely put into the original SQL query (because it is a restricted form that does not contain external data) and then the placeholders can be used as normal.
Consider a function String makePlaceholders(int len) which returns len question-marks separated with commas, then:
String[] names = { "name1", "name2" }; // do whatever is needed first
String query = "SELECT * FROM table"
+ " WHERE name IN (" + makePlaceholders(names.length) + ")";
Cursor cursor = mDb.rawQuery(query, names);
Just make sure to pass exactly as many values as places. The default maximum limit of host parameters in SQLite is 999 - at least in a normal build, not sure about Android :)
Here is one implementation:
String makePlaceholders(int len) {
if (len < 1) {
// It will lead to an invalid query anyway ..
throw new RuntimeException("No placeholders");
} else {
StringBuilder sb = new StringBuilder(len * 2 - 1);
sb.append("?");
for (int i = 1; i < len; i++) {
sb.append(",?");
}
return sb.toString();
}
}
Short example, based on answer of user166390:
public Cursor selectRowsByCodes(String[] codes) {
try {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {COLUMN_NAME_ID, COLUMN_NAME_CODE, COLUMN_NAME_NAME, COLUMN_NAME_PURPOSE, COLUMN_NAME_STATUS};
String sqlTables = "Enumbers";
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, COLUMN_NAME_CODE+" IN (" +
TextUtils.join(",", Collections.nCopies(codes.length, "?")) +
")", codes,
null, null, null);
c.moveToFirst();
return c;
} catch (Exception e) {
Log.e(this.getClass().getCanonicalName(), e.getMessage() + e.getStackTrace().toString());
}
return null;
}
Sadly there's no way of doing that (obviously 'name1', 'name2' is not a single value and can therefore not be used in a prepared statement).
So you will have to lower your sights (e.g. by creating very specific, not reusable queries like WHERE name IN (?, ?, ?)) or not using stored procedures and try to prevent SQL injections with some other techniques...
As suggest in accepted answer but without using custom function to generate comma-separated '?'. Please check code below.
String[] names = { "name1", "name2" }; // do whatever is needed first
String query = "SELECT * FROM table"
+ " WHERE name IN (" + TextUtils.join(",", Collections.nCopies(names.length, "?")) + ")";
Cursor cursor = mDb.rawQuery(query, names);
You can use TextUtils.join(",", parameters) to take advantage of sqlite binding parameters, where parameters is a list with "?" placeholders and the result string is something like "?,?,..,?".
Here is a little example:
Set<Integer> positionsSet = membersListCursorAdapter.getCurrentCheckedPosition();
List<String> ids = new ArrayList<>();
List<String> parameters = new ArrayList<>();
for (Integer position : positionsSet) {
ids.add(String.valueOf(membersListCursorAdapter.getItemId(position)));
parameters.add("?");
}
getActivity().getContentResolver().delete(
SharedUserTable.CONTENT_URI,
SharedUserTable._ID + " in (" + TextUtils.join(",", parameters) + ")",
ids.toArray(new String[ids.size()])
);
Actually you could use android's native way of querying instead of rawQuery:
public int updateContactsByServerIds(ArrayList<Integer> serverIds, final long groupId) {
final int serverIdsCount = serverIds.size()-1; // 0 for one and only id, -1 if empty list
final StringBuilder ids = new StringBuilder("");
if (serverIdsCount>0) // ambiguous "if" but -1 leads to endless cycle
for (int i = 0; i < serverIdsCount; i++)
ids.append(String.valueOf(serverIds.get(i))).append(",");
// add last (or one and only) id without comma
ids.append(String.valueOf(serverIds.get(serverIdsCount))); //-1 throws exception
// remove last comma
Log.i(this,"whereIdsList: "+ids);
final String whereClause = Tables.Contacts.USER_ID + " IN ("+ids+")";
final ContentValues args = new ContentValues();
args.put(Tables.Contacts.GROUP_ID, groupId);
int numberOfRowsAffected = 0;
SQLiteDatabase db = dbAdapter.getWritableDatabase());
try {
numberOfRowsAffected = db.update(Tables.Contacts.TABLE_NAME, args, whereClause, null);
} catch (Exception e) {
e.printStackTrace();
}
dbAdapter.closeWritableDB();
Log.d(TAG, "updateContactsByServerIds() numberOfRowsAffected: " + numberOfRowsAffected);
return numberOfRowsAffected;
}
This is not Valid
String subQuery = "SELECT _id FROM tnl_partofspeech where part_of_speech = 'noun'";
Cursor cursor = SQLDataBase.rawQuery(
"SELECT * FROM table_main where part_of_speech_id IN (" +
"?" +
")",
new String[]{subQuery}););
This is Valid
String subQuery = "SELECT _id FROM tbl_partofspeech where part_of_speech = 'noun'";
Cursor cursor = SQLDataBase.rawQuery(
"SELECT * FROM table_main where part_of_speech_id IN (" +
subQuery +
")",
null);
Using ContentResolver
String subQuery = "SELECT _id FROM tbl_partofspeech where part_of_speech = 'noun' ";
final String[] selectionArgs = new String[]{"1","2"};
final String selection = "_id IN ( ?,? )) AND part_of_speech_id IN (( " + subQuery + ") ";
SQLiteDatabase SQLDataBase = DataBaseManage.getReadableDatabase(this);
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables("tableName");
Cursor cursor = queryBuilder.query(SQLDataBase, null, selection, selectionArgs, null,
null, null);
In Kotlin you can use joinToString
val query = "SELECT * FROM table WHERE name IN (${names.joinToString(separator = ",") { "?" }})"
val cursor = mDb.rawQuery(query, names.toTypedArray())
I use the Stream API for this:
final String[] args = Stream.of("some","data","for","args").toArray(String[]::new);
final String placeholders = Stream.generate(() -> "?").limit(args.length).collect(Collectors.joining(","));
final String selection = String.format("SELECT * FROM table WHERE name IN(%s)", placeholders);
db.rawQuery(selection, args);