I am saving some data and pic to my db I found out the true way to save my pic in db is to use contentvalue so this the code:
try
{
MyDataBase = new MyDatabase(this);
mydb = MyDataBase.getWritableDatabase();
ContentValues tempval;
for (int j = 0; j < myarray.arrtitle.length; j++)
{
tempval = saveimage(myarray.arrpic.get(j),myarray.arrpath[j]);
mydb.execSQL("INSERT INTO news (title,content) VALUES (\"" + myarray.arrtitle[j] +
"\",\"" + myarray.arrcontent[j] + "\"" + ")");
mydb.insert("news", null, tempval);
}
mydb.close();
Toast.makeText(getApplicationContext(), "database 2 done", Toast.LENGTH_LONG).show();
count = 5;
} catch (Exception e) {
// TODO: daabase error2
Toast.makeText(getApplicationContext(), "data error2", Toast.LENGTH_LONG).show();
}
so this is how i can save my data correctly.
but the problem is when I insert my image, it insert in new row not the row as same as title was inserted.
is there any way to handle this?
You need to use UPDATE query, if you want to edit some column data of an already existing row. Every time you execute INSERT query, it will create a new row.
You are executing INSERT query twice, once you are inserting title and content and then in next query you are inserting image path. Instead while saving image path you should execute UPDATE query for the same row in which you saved corresponding data.
Use LIKE instead of = operator.
// updating row
db.update(TABLE, tempval , "title LIKE ?", new String[] { myarray.arrtitle[j] })
Related
I'm new to android. And I have an issue (noob question), could you help?
I have a database method getAllQuests() to fetch all records from the table into ArrayList. The code is below. I assume it works.
Next step is to fetch specific data from ArrayList. Question is: how to do this?
I assume i could use indexOf() or get(). But still i don't get how to fetch a proper row. The output is below.
So i need to put 1 row from a table into ArrayList? Or I need to use another approach?
// Getting All Quests
public List<Quest> getAllQuests() {
List<Quest> questList = new ArrayList<Quest>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Quest quest = new Quest();
quest.setID(Integer.parseInt(cursor.getString(0)));
quest.setQuestName(cursor.getString(1));
quest.setQuestPlayer(cursor.getString(2));
quest.setStatus(cursor.getInt(3));
// Adding quest to list
questList.add(quest);
} while (cursor.moveToNext());
}
// return quest list
return questList;
}
// I try to figure out what to do
List<Quest> questList = db.getAllQuests();
int index = questList.indexOf(1);
Log.d(LOG_TAG, "--- index of Quest= " + index);
Log.d(LOG_TAG, "--- element of " + index + " is " + questList.get(1));
The output of that code is:
10-20 08:39:30.210 D/myLogs: --- index of Quest= -1
10-20 08:39:30.210 D/myLogs: --- element of -1 is com.homemade.saga.Quest#41b10288
You can iterate through a list of objects using the for each construct
for (Quest q: questlist) {
Log.d(LOG_TAG,"--- index of Quest= " + String.valueOf(q.getIndex));
...... etc
}
Note this assumes the getIndex getter method has been setup in the Quest class.
I want to check the data in SQLite if already exist can update or else insert.I am checking code like this what i mentioned below.
Code:
public long addmenus(String navigationdrawer,String optionname)
{
SQLiteDatabase menus=this.getWritableDatabase();
try {
ContentValues values=new ContentValues();
values.put(HEADER_NAME,navigationdrawer);
values.put(CHILD_NAME,optionname);
// menus.insert(TABLE_NAME,null,values);
// String owner=optionname;
Cursor cursor = menus.rawQuery("select * from TABLE_NAME where CHILD_NAME ='"+ optionname +"'", null);
if(cursor.getCount()<1)
{
//execute insert query here
long rows = menus.insert(TABLE_NAME, null, values);
return rows;
// return rows inserted.
}
else
{
//Perform the update query
String strFilter = "CHILD_NAME" + optionname;
long updaterow=menus.update(TABLE_NAME,values,strFilter,null);
return updaterow;
// return rows updated.
}
// menus.close();
} catch (Exception e) {
return -1;
}
finally {
if (menus != null)
menus.close();
}
}
My activity:
I converted whole json data into string object then insert into SQLite.
String productpage=jsonObject.toString();
db.addmenus(productpage,"Navigationmenus");
But It doesn't work.It couldn't insert into sqlite.
Anyone solve this problem Glad to appreciate.
Thanks in advance
You can user insertWithOnConflict() like this
db.insertWithOnConflict(TABLE, null, yourContentValues, SQLiteDatabase.CONFLICT_REPLACE);
You can use refer this Link. That link explains how to find the email address available in a table or not, you can change the column name, table and pass the values according. In your scenario you want to check the whether the name exists already or not, so you must pass which name you want to find. If the name is there then this method will return true or false. You can validate whether you had to insert or update according the response.i.e., false means you had to insert, otherwise if it is true means then you had to update.
you should use replace into
REPLACE INTO table(...) VALUES(...);
Question is not much clear but, i think you want to check either data/record is inserted in SQLite or not. you will need to define some extra variable long rowInserted insert() method returns the row ID of the newly inserted row, or -1 when an error occurred.
menus.insert(TABLE_NAME, null, values);
long rowInserted = db.insert(AddNewPhysicalPerson, null, newValues);
if(rowInserted != -1)
Toast.makeText(myContext, "New row added :" + rowInserted, Toast.LENGTH_SHORT).show();
else
Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();
Updated
check either data is in table or column? for this you use this code
public boolean Exists(String id){
Cursor res = getAllData();
int count=0;
while (res.moveToNext()){
String email =res.getString(3);
if(email.equals(id)){
count++;
}
}
if(count==0){
return false;
} else{
return true;
}
}
Second you asking about json first store all data in any List run time and get string from it then you are able to store in SQlite
try {
items = jsonObject.getJSONArray("myjsonattribute");
List<MyAnySetterGetter> mList = new ArrayList<MyAnySetterGetter>();
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String mfilename = c.getString("myjsonattribute2");
mList.add(mfilename);
}
} catch (JSONException e) {
//e.printStackTrace();
}
then use above list to insert data from list to SQLite
like
String str1 = mList.get(position).getMYITEM1();
String str2 = mList.get(position).getMYITEM2();
insert str1 and str2 in SQLite hope you will get idea.
you should
set key for the table, then
insert(if the key existed it will not insert anymore), then
update all row.
I am working on sqllite. I've created the database successfully, and I can add new items to it.
// Adding new contact
public void Add_Contact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Image, contact.getImage()); // Contact image
values.put(KEY_Counter, contact.getCounter()); // Contact counter
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
This code working perfect, now I want to check if I can also save the same information, for example, if I first save "Hello Android" and in a second time try to save the same information, I want to show for example: Toast message or other.
First make a function like this:
public boolean somethingExists(String x) {
Cursor cursor = database.rawQuery("select 1 from " + TABLE_CONTACTS + " where KEY_Tittle like '%" + x
+ "%'", null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
And then before every insert call this funcition to return if it exists or not like this:
if (!somethingExists("hello world")) {
//HERE DO INSERTION if it is not already in Table e.g like call AddContact function here for insertion etc
} else {
//Display Toast message here "Record already exists"
}
p.s i just wanted to highlight the logic - your actual table names, schema & logic might be different. Anyways, try this - it should work. The actually working is supposed to follow all database constraints, structure and schema of your design.
I am new in Android Development.
Currently, working with SQLite Database in Android.
My problem is that I have a large amount of data which I have to store in SQLite Database in Android.
There are 2 tables: One having 14927 rows and the other one has 9903 rows.
Currently the database in sql. And I have copy these data in excel sheet but don't understand how can I import these data in SQLite Database.
I go through the following link:
Inserting large amount of data into android sqlite database?
Here, the solution is posted regarding CSV File. But want to know other ways of doing this.
Please let me know what is the best way to import such a large data in Android.
Please help me. Thanks in advance.
Do Like This
SQLiteDatabase sd;
sd.beginTransaction();
for (int i = 0; i < data.size(); i++) {
ContentValues values = new ContentValues();
values.put(DBAdapter.Column1, "HP");
values.put(DBAdapter.Column2, "qw");
values.put(DBAdapter.Column3, "5280");
values.put(DBAdapter.Column4, "345, 546");
sd.insert(DBAdapter.TABLE, null, values);
sd.insertWithOnConflict(tableName, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
sd.setTransactionSuccessful();
sd.endTransaction();
Try this
SQLiteDatabase db = Your_DATABASE;
db.beginTransaction();
db.openDatabase();
for (int i = 0; i < array.size(); i++)
{
String sql = ( "INSERT INTO " + Table_NAME
+ "(" + COLUMN_1 + ","
+ COLUMN_2 + ","
+ COLUMN_3 + ","
+ COLUMN_4 + ","
+ ") values (?,?,?,?)");
SQLiteStatement insert = db.compileStatement(sql);
}
db.setTransactionSuccessful();
db.endTransaction();
db.closeDatabase();
Use DatabaseUtils.InsertHelper. In this article you will find an example of how to use it and other ways to speed up insertions. The example is as follows:
import android.database.DatabaseUtils.InsertHelper;
//...
private class DatabaseHelper extends SQLiteOpenHelper {
#Override
public void onCreate(SQLiteDatabase db) {
// Create a single InsertHelper to handle this set of insertions.
InsertHelper ih = new InsertHelper(db, "TableName");
// Get the numeric indexes for each of the columns that we're updating
final int greekColumn = ih.getColumnIndex("Greek");
final int ionicColumn = ih.getColumnIndex("Ionic");
//...
final int romanColumn = ih.getColumnIndex("Roman");
try {
while (moreRowsToInsert) {
// ... Create the data for this row (not shown) ...
// Get the InsertHelper ready to insert a single row
ih.prepareForInsert();
// Add the data for each column
ih.bind(greekColumn, greekData);
ih.bind(ionicColumn, ionicData);
//...
ih.bind(romanColumn, romanData);
// Insert the row into the database.
ih.execute();
}
}
finally {
ih.close();
}
}
//...
}
I'm not sure what I'm doing wrong, but I'm trying to update a single integer value in a column of a table to 1 from 0. When creating the database, I set all values of the column to zero using:
for (int i = 0; i < setups.length; i++) {
ContentValues values = new ContentValues();
values.put(JokeDbContract.TblJoke.COLUMN_NAME_SETUP, setups[i]);
values.put(JokeDbContract.TblJoke.COLUMN_NAME_PUNCHLINE, punchlines[i]);
values.put(JokeDbContract.TblJoke.COLUMN_NAME_USED, 0);
db.insert(JokeDbContract.TblJoke.TABLE_NAME, null, values);
}
Then, in the actual activity, I'm doing:
private void findNewJoke() {
JokeDb jokeDb = JokeDb.getInstance(this);
SQLiteDatabase theDb = jokeDb.getDB();
String selection = JokeDbContract.TblJoke.COLUMN_NAME_USED + "=" + 0;
// Query database for a joke that has not been used, update the fields
// theJoke and thePunchline appropriately
String[] columns = {JokeDbContract.TblJoke._ID,
JokeDbContract.TblJoke.COLUMN_NAME_PUNCHLINE,
JokeDbContract.TblJoke.COLUMN_NAME_SETUP,
JokeDbContract.TblJoke.COLUMN_NAME_USED};
Cursor c = theDb.query(JokeDbContract.TblJoke.TABLE_NAME, columns, selection,
null, null, null, null);
if (c.moveToFirst() == false) {
Toast.makeText(this, R.string.error_retrieving_joke, Toast.LENGTH_LONG).show();
Log.e(getString(R.string.app_name),"No jokes retreived from DB in JokeActivity.findNewJoke()!");
}
else {
ContentValues values = new ContentValues();
theSetup = c.getString(c.getColumnIndexOrThrow(JokeDbContract.TblJoke.COLUMN_NAME_SETUP));
thePunchline = c.getString(c.getColumnIndexOrThrow(JokeDbContract.TblJoke.COLUMN_NAME_PUNCHLINE));
String updateSelection = JokeDbContract.TblJoke.COLUMN_NAME_SETUP + "=" + theSetup;
values.put(JokeDbContract.TblJoke.COLUMN_NAME_USED, 1);
theDb.update(JokeDbContract.TblJoke.TABLE_NAME, values, updateSelection, null);
}
}
I'm getting an error on the update:
java.lang.RuntimeException: .... while compiling: UPDATE jokes SET used=?
WHERE setup=Why do programmers always mix up Halloween and Christmas?
It seems as though I'm not getting an actual value set for the used column. What the program ultimately does is cycle through jokes where used=0, then sets used to 1 when it has been viewed. So the query only pulls those jokes that aren't used yet. I have a feeling I'm missing something simple, one can hope.
I think you are having problems with quotation marks.
Example:
String updateSelection = JokeDbContract.TblJoke.COLUMN_NAME_SETUP + "=\"" + theSetup + "\"";
However, the recommended way to do this, would be:
theDb.update(JokeDbContract.TblJoke.TABLE_NAME, values, JokeDbContract.TblJoke.COLUMN_NAME_SETUP + " = ?", new String[] { theSetup });
It is better to use field = ?, because this helps sqlite cache queries (I believe).