mardi 31 mars 2015

Add and Retrieve data from SQLite Database Android in listview

Ok so i'm new here and i know this question has been asked many times but i cant seem to get anything to work i can get some samples i've found to work fine in a listview but if i try to modify or recreate i just cant seem to get it to work so im curreouse as to what i am doing wrong my code....sorry in advance for the bad formatting.



public class OrgEventCreationActivity extends Activity {

private SQLiteAdapter mySQLiteAdapter;
public EditText eventnames;
public EditText evedes;
public EditText numofv;
public EditText possisions;
public EditText skills;
public EditText minage;
public Button saveevent;
public Button proceed;
public Button stime;
public Button etime;
public Button date;
public ListView list;
public Button submit;

/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_org_event_creation);

eventnames = (EditText)findViewById(R.id.eventnameinput);
evedes = (EditText)findViewById (R.id.eventdescriptioninput);
numofv = (EditText)findViewById (R.id.numofv);
possisions = (EditText)findViewById (R.id.posinput);
skills = (EditText)findViewById (R.id.skillsinput);
minage = (EditText)findViewById (R.id.minage);
saveevent =(Button)findViewById (R.id.aeventbtn);
proceed = (Button)findViewById (R.id.submitbtn);
stime = (Button)findViewById (R.id.stimebtn);
etime = (Button)findViewById (R.id.etimebtn);
date = (Button)findViewById (R.id.datepicker);
list = (ListView)findViewById (R.id.orglist);
submit = (Button)findViewById (R.id.submitbtn);
submit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent us = new Intent (OrgEventCreationActivity.this,UserHomeActivity.class);
startActivity(us);
}
});

saveevent.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
populatelist();
}
});

}
public void populatelist(){

String evename = eventnames.getText().toString().trim();

/*
* Create/Open a SQLite database
* and fill with dummy content
* and close it
*/

mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.deleteAll();

mySQLiteAdapter.insert(evename);


mySQLiteAdapter.close();

Intent log = new Intent(OrgEventCreationActivity.this, UserHomeActivity.class);
startActivity(log);


}


mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();

Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);

String[] from = new String[]{SQLiteAdapter.MYDATABASE_TABLE};
int[] to = new int[]{R.id.text};

SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);

listContent.setAdapter(cursorAdapter);

mySQLiteAdapter.close();


}
}
}


the activity to display listview



import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class UserHomeActivity extends Activity {

private SQLiteAdapter mySQLiteAdapter;

/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listContent = (ListView)findViewById(R.id.contentlist);

/*
* Create/Open a SQLite database
* and fill with dummy content
* and close it
*
* mySQLiteAdapter = new SQLiteAdapter(this);
*mySQLiteAdapter.openToWrite();
* mySQLiteAdapter.deleteAll();

*mySQLiteAdapter.insert("Charity Dinner");
*mySQLiteAdapter.insert("Fundraiser");
*mySQLiteAdapter.insert("Benifit Concert");
*mySQLiteAdapter.insert("Silent Auction");
*

*mySQLiteAdapter.close();
*/
/*
* Open the same SQLite database
* and read all it's content.
*/
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();

Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);

String[] from = new String[]{SQLiteAdapter.MYDATABASE_TABLE};
int[] to = new int[]{R.id.text};

SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);

listContent.setAdapter(cursorAdapter);

mySQLiteAdapter.close();


}
}


and this is my database



import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.view.View.OnClickListener;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class SQLiteAdapter {

public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String NAME_COLUMN = "EVENTS";
public static final String KEY_ID = "_id";

public static final String KEY_CONTENT = "events";

//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key aautoincrement,"+ "evnents text);";

private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;

private Context context;

public SQLiteAdapter(Context c){
context = c;
}



public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}

public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}

public void close(){
sqLiteHelper.close();
}

public void insertEntry(String evename)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("EVETS",evename);


// Insert the row into your table
sqLiteDatabase.insert("ev", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}





public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}

public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
NAME_COLUMN, null, null, null, null);

return cursor;
}

public class SQLiteHelper extends SQLiteOpenHelper {

public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}

@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

}

}

}


i've been trying to figure this out for days now if you can help i would be truly greatful


Get offset of a row after performing sort operation in sql

I am using SQLite database.


Suppose I have rows with IDs 1 to 50. Then I perform select and order by operation.


Say, the result is IDs : 6,3,5,2,9,12,1,34,45,15.


Now, I want to know the offset of a particular row with given ID in the above result.e.g. offset of ID 1 is 6.


Can I do this in a single query?


how to deploy javafx application with sqlite database(preferably using inno script)

I want to deploy a javafx fxml application. I have used sqlite3 database. I tried deploying it using inno script by adding .db file, the first login page shows up but after i enter the credentials and Log-in the window just collapses. I think its because of an exception which I have not programmed to display in a pop window. The programs works just fine when i run in netbeans. Please suggest the best way to deploy an fxml application with sqlite database.


in project folder . I have 1.main project files 2.images in a separate folder named images(background image is displayed in login page)

3. database file.


Thanks in advance.


SQLite get row data using SELECT

Using SQLite Database, I have a table with 6 columns in each row as the rows are added. The first column is the name of the "person." I have it so when you click on the person in a listview, it brings up a screen with 5 edit texts. You fill them out and submit it and it adds it to another row in the database.


To retrieve that data later on, I am trying to use SELECT by the name to get it, but cannot figure out how this works.



public Cursor getChildRulesInformation(DatabaseOperations dop, String name) {
dop.getReadableDatabase().execSQL("SELECT * FROM "+CHILD_RULES_TABLE_NAME+" WHERE "+CHILD_NAME + "=\""+ name+"\"");
}


What do I do with that to retreive every column inside of that specific row. I am confused on the process to get it out.


Any lead in the write direction would be greatly appreciated. Thanks. If you need any more information please let me know.


Creating a MySQL database in memory with PHP PDO

I'm coding a library to compare two MySQL databases.


Sources can be a SQL string, SQL file or a MySQL database connection.


Use regular expressions to parse tables/alter/indexes form sources is terrible and with a lot of possible syntaxes.


I have the script to generate a SQL string from any source, and now I need to import this SQL into a temporal database, to launch the DESCRIBE table and parse this text. Is a lot of more easy and clean than originals sources.


There are any way to create a memory/temporal MySQL database from PHP PDO without user and password credentials?


I have same script to SQLite, that allow to create memory connections with:



$db1 = new PDO('sqlite::memory:');

$db1->exec($sql);

$tables = [];

foreach ($db1->query('.tables') as $table) {
$q = $db1->prepare('.schema ?');
$q->execute([$table]);

$tables[$table] = $q->fetchAll();
}


There is a lot of more easy to compare databases.


How can I do this with MySQL?


Thanks :)


Copying preloaded database, adding carriage returns

I have an app which comes with a preloaded database.


My temporary copy function is like so



private void copyDatabase() {

AssetManager assetManager = context.getResources().getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(DATABASE_NAME);
out = new FileOutputStream(DATABASE_FILE);
byte[] buffer = new byte[1024];
int read;

while ((read = in.read(buffer)) > 0){
out.write(buffer, 0, read);
}
} catch (IOException e) {
Log.e("error", e.getMessage());
} finally {
if(in != null) {
try {
in.close();
}catch (IOException e) {
Log.e("error", e.getMessage());
}
}
if(out != null) {
try {
out.close();
}catch (IOException e) {
Log.e("error", e.getMessage());
}
}
}
}


However on Android 2.2 I keep getting an error "database disk image malformed". So I went ahead and copied it off the device, onto my computer. And sure enough, it wouldn't open. I did a hex compare on the two files and there are 10 instances where 1 byte is different. Hex 0D has been added 10 times in random spots in the malformed copy.

The copy routine works fine in 3.x+. I also have developed other apps with the same method and don't have an issue.


Any ideas?


Xapian, MySqldb, and Sqlite

i want to make some database operations using python in ubuntu. I will implement searching function in tables in my database. I searched about how to do it. But i come across many different database apis, search engines etc.They are :



Xapian, MySqldb, and Sqlite


Although i read from official website, I cant understand what they are and what purpose they are used. I don't know which one i should use. Could you please explain them in your own simple words? And what is the difference of them?


Thanks in advance.


Getting the table name as a column prefix in SQLite

I'm trying to run the following query:



SELECT artist_trackings.status, artists.* FROM artists LEFT OUTER JOIN artist_trackings ON artists.id = artist_trackings.artist_id WHERE id = 510 AND tracker_id = 7294574


The cursor I am returned contains all the correct columns, however their names are things like "id", "name", etc instead of "artists.id" and "artists.name". Also, "artist_trackings.status" is just returned as "status".


One solution I know is to go through the projection and do something like:



SELECT artist_trackings.status AS artist_trackings_status....


And so on, but for very big tables I have this is a total pain and shouldn't be necessary I'd think.


How do I force queries to always return the table name as a prefix to the columns on join queries like this? Shouldn't that happen automatically?


i create database in firefox sqlite and i want to connect it in android eclipse

I have this problem on how to connect my SQLite database firefox to eclipse android. I want to retrieve the data from my database . Please help me for my thesis and step by step .thansk


How to put lists together into list holding them as 'tuples'

In Pythons SQLite documents we have the following example on how to put many values into SQL database:



purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)


But if I have one list containing the dates, one containing the buy/sell, one containing the stock tickers, one the amount and one the price, how to I combine them at the most optimal way, before I insert? I've tried looping over each list and just inserting them in the SQLite DB one by one, but that takes to much time.



dates = ['2006-03-28', '2006-04-05', '2006-04-06']
flags = ['buy', 'buy', 'sell']
tickers = ['IBM', 'MSFT', 'IBM']
amount = [1000, 1000, 500]
price = [45.00, 72.00, 53.00]


This takes too long:



for i in range(0, len(dates)):

c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', dates[i], flags[i], tickers[i], amount[i], price[i])

Retrieve Specific data from database android for each user

My question is that i want each user to get information that is relevent to him ie, in this local password protected program if user name matches when reading table ,i should only get his history(here latitude and longitude) any way to do the same??



package com.sset.jibin.wakemethere;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

com.sset.jibin.wakemethere.DatabaseOperations2.HISTORY_COLUMN_NAME;

public class History extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
DatabaseOperations2 databaseHelper;
String tex = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
Intent intent = getIntent();
String tex = intent.getStringExtra("text");

databaseHelper = new DatabaseOperations2(this);

Log.d("=====>", "valc0");

populatehistorylist();
}
private void populatehistorylist(){


Cursor cr = databaseHelper.getAllRecords();


startManagingCursor(cr);

String[] from = new String[]{databaseHelper.HISTORY_COLUMN_ID, databaseHelper.HISTORY_COLUMN_LAT, databaseHelper.HISTORY_COLUMN_LNG};

int[] to = new int[]{R.id.cid, R.id.lat, R.id.lng};

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list, cr, from, to);

ListView lv = (ListView) findViewById(android.R.id.list);

lv.setAdapter(adapter);

}










public void vmap(View view) {
Log.d("History","VMAP");

Intent intent = new Intent(this, MapsActivity.class);
startActivity(intent);

}

public void goToGoogleMaps(View view){
TextView textLng = (TextView)view.findViewById(R.id.lng);
String lng = (String) textLng.getText();
TextView textLat = (TextView)view.findViewById(R.id.lat);
String lat = (String) textLat.getText();
Log.d("History","lat : " + lat + " lng " + lng);
SavePreferences("lat", lat);
SavePreferences("lng", lng);

Intent intent = new Intent(this, MapsActivity.class);
intent.putExtra("lat", lat);
intent.putExtra("lan", lng);
startActivity(intent);



}

private void SavePreferences(String key, String value){


SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key,value);



editor.commit();


}





}


Database





package com.sset.jibin.wakemethere;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;



public class DatabaseOperations2 extends SQLiteOpenHelper {

static int DATABASE_VERSION = 1;
static String DATABASE_NAME = "data";
static String TABLE_NAME = "history";
static String HISTORY_COLUMN_LNG = "lng";
static String HISTORY_COLUMN_LAT = "lat";
static String HISTORY_COLUMN_NAME = "name";
static String HISTORY_COLUMN_ID = "_id";


public DatabaseOperations2(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("DatabaseHelper", "Database2 constructor");
}

@Override
public void onCreate(SQLiteDatabase database) {
Log.d("DatabaseOP2","onCreate");
database.execSQL("CREATE TABLE " + TABLE_NAME +
"( " + HISTORY_COLUMN_ID + " integer primary key, " + HISTORY_COLUMN_LNG + " text, " +
HISTORY_COLUMN_LAT +" text, "+ HISTORY_COLUMN_NAME + " text)");

}

@Override
public void onUpgrade(SQLiteDatabase database, int oldVer, int newVer) {
Log.d("DatabaseHelper","onUpgrade");
database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME );
onCreate(database);

}

public void saveRecord(String lat, String lng, String name){
Log.d("DatabaseHelper","saveRecord");
SQLiteDatabase database = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(HISTORY_COLUMN_LAT, lat);
contentValues.put(HISTORY_COLUMN_LNG, lng);
contentValues.put(HISTORY_COLUMN_NAME, name);

database.insert(TABLE_NAME , null, contentValues );

}

public Cursor getAllRecords(){



SQLiteDatabase database = this.getReadableDatabase();
return database.rawQuery("SELECT * FROM " + TABLE_NAME , null); }



}



SQLCipher and schema modification

I use SQLCipher in my iOS application (with help of FMDB library). I can't find any information about following case: I have encrypted DB and I want to update schema: alter some tables, insert some data. Do I need any additional steps behind opening DB and setting key?


Present string different in View than what it's set in ViewModel

I'm working on a project on Windows Phone 8 w/ SQLite, and I've been working with dates and times, and recently I've had to start using some aggregate functions to select some data, but these can only be implemented if the datetime strings are formatted in a certain way (SQLite DateTime) so I've had to change the formatting of these values so I get the results I expect from the aggregate queries.


My problem is that these formats aren't really the most appealing when presenting the data to the user. For example, before using aggregate functions, I was displaying a duration as "23h 32m 21s" (h'h 'm'm 's's') or a date as Tuesday 31 March 2015 (dddd dd MMMM yyyy) but I had to change these to the formats SQLite uses to perform aggregate queries, so they now read 00:00:00 for duration and 2015-03-31 for dates, etc.


Is there any way where you can change the format when presenting the data to the user regardless of how it's formatted and inserted into the database in the ViewModel/C#? I've tried using a StringFormatConverter and setting the parameter to my preferred format, but that didn't work.


Thanks.


Why JPA declaration of unique multiple constrains works in mySQL but not in SQLite

I have the following entity bean defined with JPA



@Entity
@Table(name = "Person", schema = "", uniqueConstraints = {
@UniqueConstraint(columnNames = {"Name", "Type"}),
@UniqueConstraint(columnNames = {"PersonID"})})
public class PersonDataBean implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Basic(optional = false)
@Column(name = "PersonID", nullable = false)
private Integer personID;
@Column(name = "Name", length = 255, nullable = false)
private String name;
@Column(name = "Type", length = 255, nullable = false)
private String type;

//getters and setters
}


I make use of the javax.persistence.EntityManager objects for accessing the database. I've made some unit tests to verify that records with the same name but different type can be correctly inserted in the database, and records with the same name AND type throw exceptions, as it is defined in the code above. When I make a connection to a mySQL database, everything works as expected. However, when I use the same JPA entity object with the same unit test in SQLite, then records with the same name and type can be wrongly added. My first impression was that SQLite does not support unique constraints on multiple columns. However, I read here Sqlite table constraint - unique on multiple columns that this is supported. During the initialization of the EntityManager, I can read from the logs the following auto-generated statement for the table creation



CREATE TABLE Person (PersonID INTEGER NOT NULL, Name VARCHAR(255) NOT NULL, Type VARCHAR(255) NOT NULL PRIMARY KEY (PersonID))
ALTER TABLE Person ADD CONSTRAINT UNQ_Person_0 UNIQUE (Name, Type)


Any ideas why this is happening?


SQLite not getting copied correctly with Wix installer

I have an SQLite database in my application which is set as content to copy always. I also have a wix installer, and I include the path to my db there too. However, when I try to perform any action, I get missing table errors, because the database hasn't copied over.


Is there anything else I need to do to ensure the db will be available with the application? Everything is working locally, by the way. It's the installed version that fails.


Thanks in advance.


SQLite not working on Galaxy S5

Me and a small group are working on a android app project. The app uses SQLite to read and write from a database and the code is the same from the developer.android.com. The code works on everyone elses phone but not mine, anytime my phone hits code that calls to SQLite my app crashes which leads me to believe it's my phone. Does anyone know why this is?


The error says I'm missing the first column, no matter what the first column is. What's wrong with my phone?


Share SQLite database from Android app, without intermediate copy

I want to allow users of my Android app to export the SQLite database file for content they create. My current solution copies the file to private storage (/data/data/http://ift.tt/1CtvgdC), then creates a URI for this file and opens the Share dialog. This is working, allowing me to export the database file using Dropbox, for example. Here is the code I'm using, partially adapted from http://ift.tt/1GJdeqL -



private void exportContent() {
copyContentToPrivateStorage();

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("application/octet-stream");

Uri uri = new FileProvider().getDatabaseURI(this);

intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

startActivity(Intent.createChooser(intent, "Backup via:"));
}

private void copyContentToPrivateStorage() {
// From http://ift.tt/1GJdeqL
try {
File data = Environment.getDataDirectory();
File sd = getFilesDir();

if (sd.canWrite()) {
String currentDBPath = "//data//http://ift.tt/1CtviC9";
String backupDBPath = "Content.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);

if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}

public class FileProvider extends android.support.v4.content.FileProvider {

public Uri getDatabaseURI(Context c) {
File exportFile = new File(c.getFilesDir(), "Content.db");
Uri uri = getUriForFile(c, "com.package.name.fileprovider", exportFile);

c.grantUriPermission("*", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

return uri;
}
}


It seems like I should be able to directly create a URI from the existing database path, instead of doing an intermediate copy. Is there a way to do this?


I could keep doing the intermediate copy, but I believe it would be bad practice to leave the second copy of the database in the data directory longer than necessary. Is there a way to clean it up and delete it after the chosen app has finished using the URI to share the file?


Structuring backend queries

So this is more of a methodology question than a coding question. I want to ask this before I actually start coding in order to choose the best route. I have a messaging app. When the app launches I query in the background all the messages from the backend where current_user_id is equal to recipient_id. Now I have all of the messages stored the user needs to see so I locally store them into a sqlite database.


Great, but what about when the user gets new messages? How can i structure a query to receive those without having to query the entire table again? Also how do I set this up as a continual process? Is the phone always requesting update information from the backend while its in the foreground?


Thanks. I really appreciate your help. I'm currently using iOS and as stated SQLite. Also my backend is AWS node.js.


Wanted to share this free SQL Book For Beginners [on hold]

This book "SQL QuickStart Guide" is available for free download for Kindle currently. It's a great introduction to SQL for beginners. Please share with anyone you think might be interested. Thank you.


SQL QuickStart Guide -- Download Link for Kindle (US)


Editing a table column through Python

I'm very new to python I am trying to edit a column in a database to make it auto increment and a primary key however I keep getting an error. the database is destination history from a Android smartphone which does not have a ID column. Any advise would be much appreciated.



import sqlite3 as lite
import sys
import simplekml
con = lite.connect('da_destination_history')
kml = simplekml.Kml()
with con:
cur = con.cursor()
cur.execute("ALTER TABLE destination_history ADD ID, INTEGER PRIMARY KEY AUTOINCREMENT")
cur.execute("ALTER TABLE destination_history ALTER COLUMN ID ")
cur.execute("SELECT dest_lat, dest_lng, source_lat, source_lng FROM destination_history")
rows = cur.fetchall()
for row in rows:
kml.newpoint(name="Kirstenbosch Start", coords=[(row[0])])


kml.save("andriod.kml")

Get AUTO INCREMENT ID for inserted element using ContentProviderOperation

I'm trying to insert element from the StackOverFlow web service :





operations.add((ContentProviderOperation.newInsert(TagProvider.CONTENT_URI))
.withValue(TagTable.COLUMN_ID,i)
.withValue(TagTable.COLUMN_DISPLAY, currentTag.getName())
.withValue(TagTable.COLUMN_NB_OCCURRENCES,currentTag.getCount())
.build()) ;



What I want to know is what argument should I use as a second argument of the first withValue method, because when I use i get this error :





03-31 14:32:31.160: E/memtrack(3029): Couldn't load memtrack module (No such file or directory)
03-31 14:32:31.161: E/android.os.Debug(3029): failed to load memtrack module: -2
03-31 14:32:45.504: E/ConfigFetchTask(1730): failed to build request; aborting config fetch
03-31 14:32:48.415: E/memtrack(3056): Couldn't load memtrack module (No such file or directory)
03-31 14:32:48.415: E/android.os.Debug(3056): failed to load memtrack module: -2
03-31 14:33:47.301: E/ActivityThread(1642): Service com.google.android.gms.backup.BackupTransportService has leaked ServiceConnection com.google.android.gms.http.f@9915f79 that was originally bound here
03-31 14:33:47.301: E/ActivityThread(1642): android.app.ServiceConnectionLeaked: Service com.google.android.gms.backup.BackupTransportService has leaked ServiceConnection com.google.android.gms.http.f@9915f79 that was originally bound here
03-31 14:33:47.301: E/ActivityThread(1642): at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1072)
03-31 14:33:47.301: E/ActivityThread(1642): at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:966)
03-31 14:33:47.301: E/ActivityThread(1642): at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1768)
03-31 14:33:47.301: E/ActivityThread(1642): at android.app.ContextImpl.bindService(ContextImpl.java:1751)
03-31 14:33:47.301: E/ActivityThread(1642): at android.content.ContextWrapper.bindService(ContextWrapper.java:538)
03-31 14:33:47.301: E/ActivityThread(1642): at com.google.android.gms.http.e.<init>(SourceFile:94)
03-31 14:33:47.301: E/ActivityThread(1642): at com.google.android.gms.http.GoogleHttpClient.<init>(SourceFile:234)
03-31 14:33:47.301: E/ActivityThread(1642): at com.google.android.gms.http.GoogleHttpClient.<init>(SourceFile:196)
03-31 14:33:47.301: E/ActivityThread(1642): at com.google.android.gms.backup.BackupTransportService.onCreate(SourceFile:1172)
03-31 14:33:47.301: E/ActivityThread(1642): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2731)
03-31 14:33:47.301: E/ActivityThread(1642): at android.app.ActivityThread.access$1800(ActivityThread.java:144)
03-31 14:33:47.301: E/ActivityThread(1642): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1361)
03-31 14:33:47.301: E/ActivityThread(1642): at android.os.Handler.dispatchMessage(Handler.java:102)
03-31 14:33:47.301: E/ActivityThread(1642): at android.os.Looper.loop(Looper.java:135)
03-31 14:33:47.301: E/ActivityThread(1642): at android.app.ActivityThread.main(ActivityThread.java:5221)
03-31 14:33:47.301: E/ActivityThread(1642): at java.lang.reflect.Method.invoke(Native Method)
03-31 14:33:47.301: E/ActivityThread(1642): at java.lang.reflect.Method.invoke(Method.java:372)
03-31 14:33:47.301: E/ActivityThread(1642): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-31 14:33:47.301: E/ActivityThread(1642): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
03-31 14:33:47.339: E/StrictMode(1642): null
03-31 14:33:47.339: E/StrictMode(1642): android.app.ServiceConnectionLeaked: Service com.google.android.gms.backup.BackupTransportService has leaked ServiceConnection com.google.android.gms.http.f@9915f79 that was originally bound here
03-31 14:33:47.339: E/StrictMode(1642): at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1072)
03-31 14:33:47.339: E/StrictMode(1642): at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:966)
03-31 14:33:47.339: E/StrictMode(1642): at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1768)
03-31 14:33:47.339: E/StrictMode(1642): at android.app.ContextImpl.bindService(ContextImpl.java:1751)
03-31 14:33:47.339: E/StrictMode(1642): at android.content.ContextWrapper.bindService(ContextWrapper.java:538)
03-31 14:33:47.339: E/StrictMode(1642): at com.google.android.gms.http.e.<init>(SourceFile:94)
03-31 14:33:47.339: E/StrictMode(1642): at com.google.android.gms.http.GoogleHttpClient.<init>(SourceFile:234)
03-31 14:33:47.339: E/StrictMode(1642): at com.google.android.gms.http.GoogleHttpClient.<init>(SourceFile:196)
03-31 14:33:47.339: E/StrictMode(1642): at com.google.android.gms.backup.BackupTransportService.onCreate(SourceFile:1172)
03-31 14:33:47.339: E/StrictMode(1642): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2731)
03-31 14:33:47.339: E/StrictMode(1642): at android.app.ActivityThread.access$1800(ActivityThread.java:144)
03-31 14:33:47.339: E/StrictMode(1642): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1361)
03-31 14:33:47.339: E/StrictMode(1642): at android.os.Handler.dispatchMessage(Handler.java:102)
03-31 14:33:47.339: E/StrictMode(1642): at android.os.Looper.loop(Looper.java:135)
03-31 14:33:47.339: E/StrictMode(1642): at android.app.ActivityThread.main(ActivityThread.java:5221)
03-31 14:33:47.339: E/StrictMode(1642): at java.lang.reflect.Method.invoke(Native Method)
03-31 14:33:47.339: E/StrictMode(1642): at java.lang.reflect.Method.invoke(Method.java:372)
03-31 14:33:47.339: E/StrictMode(1642): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-31 14:33:47.339: E/StrictMode(1642): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
03-31 14:33:49.816: E/Backup(1661): [LegacyBackupAccountManager] Fail to get legacy transport context.
03-31 14:33:49.816: E/Backup(1661): android.content.pm.PackageManager$NameNotFoundException: Application package com.google.android.backup not found
03-31 14:33:49.816: E/Backup(1661): at android.app.ContextImpl.createPackageContextAsUser(ContextImpl.java:2139)
03-31 14:33:49.816: E/Backup(1661): at android.app.ContextImpl.createPackageContext(ContextImpl.java:2115)
03-31 14:33:49.816: E/Backup(1661): at android.content.ContextWrapper.createPackageContext(ContextWrapper.java:658)
03-31 14:33:49.816: E/Backup(1661): at com.google.android.gms.backup.am.<init>(SourceFile:47)
03-31 14:33:49.816: E/Backup(1661): at com.google.android.gms.backup.BackupTransportMigratorService.b(SourceFile:162)
03-31 14:33:49.816: E/Backup(1661): at com.google.android.gms.backup.BackupTransportMigratorService.onHandleIntent(SourceFile:80)
03-31 14:33:49.816: E/Backup(1661): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
03-31 14:33:49.816: E/Backup(1661): at android.os.Handler.dispatchMessage(Handler.java:102)
03-31 14:33:49.816: E/Backup(1661): at android.os.Looper.loop(Looper.java:135)
03-31 14:33:49.816: E/Backup(1661): at android.os.HandlerThread.run(HandlerThread.java:61)
03-31 14:33:49.961: E/Backup(1661): [LegacyBackupAccountManager] Fail to get legacy transport context.
03-31 14:33:49.961: E/Backup(1661): android.content.pm.PackageManager$NameNotFoundException: Application package com.google.android.backup not found
03-31 14:33:49.961: E/Backup(1661): at android.app.ContextImpl.createPackageContextAsUser(ContextImpl.java:2139)
03-31 14:33:49.961: E/Backup(1661): at android.app.ContextImpl.createPackageContext(ContextImpl.java:2115)
03-31 14:33:49.961: E/Backup(1661): at android.content.ContextWrapper.createPackageContext(ContextWrapper.java:658)
03-31 14:33:49.961: E/Backup(1661): at com.google.android.gms.backup.am.<init>(SourceFile:47)
03-31 14:33:49.961: E/Backup(1661): at com.google.android.gms.backup.a.a(SourceFile:65)
03-31 14:33:49.961: E/Backup(1661): at com.google.android.gms.backup.c.a(SourceFile:39)
03-31 14:33:49.961: E/Backup(1661): at com.google.android.gms.backup.b.a(SourceFile:67)
03-31 14:33:49.961: E/Backup(1661): at com.google.android.gms.backup.b.a(SourceFile:39)
03-31 14:33:49.961: E/Backup(1661): at com.google.android.gms.backup.BackupAccountNotifierService.onHandleIntent(SourceFile:76)
03-31 14:33:49.961: E/Backup(1661): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
03-31 14:33:49.961: E/Backup(1661): at android.os.Handler.dispatchMessage(Handler.java:102)
03-31 14:33:49.961: E/Backup(1661): at android.os.Looper.loop(Looper.java:135)
03-31 14:33:49.961: E/Backup(1661): at android.os.HandlerThread.run(HandlerThread.java:61)
03-31 14:34:16.539: E/AndroidRuntime(3066): FATAL EXCEPTION: main
03-31 14:34:16.539: E/AndroidRuntime(3066): Process: fr.isima.android.tp3, PID: 3066
03-31 14:34:16.539: E/AndroidRuntime(3066): java.lang.NullPointerException: Attempt to get length of null array
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.text.TextUtils.join(TextUtils.java:298)
03-31 14:34:16.539: E/AndroidRuntime(3066): at fr.isima.android.tp3.ui.BookAdapter.getView(BookAdapter.java:55)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.widget.AbsListView.obtainView(AbsListView.java:2344)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.widget.ListView.makeAndAddView(ListView.java:1864)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.widget.ListView.fillDown(ListView.java:698)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.widget.ListView.fillFromTop(ListView.java:759)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.widget.ListView.layoutChildren(ListView.java:1673)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.widget.AbsListView.onLayout(AbsListView.java:2148)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.View.layout(View.java:15596)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.ViewGroup.layout(ViewGroup.java:4966)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.View.layout(View.java:15596)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.ViewGroup.layout(ViewGroup.java:4966)
03-31 14:34:16.539: E/AndroidRuntime(3066): at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:494)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.View.layout(View.java:15596)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.ViewGroup.layout(ViewGroup.java:4966)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.View.layout(View.java:15596)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.ViewGroup.layout(ViewGroup.java:4966)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.Choreographer.doCallbacks(Choreographer.java:580)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.Choreographer.doFrame(Choreographer.java:550)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.os.Handler.handleCallback(Handler.java:739)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.os.Handler.dispatchMessage(Handler.java:95)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.os.Looper.loop(Looper.java:135)
03-31 14:34:16.539: E/AndroidRuntime(3066): at android.app.ActivityThread.main(ActivityThread.java:5221)
03-31 14:34:16.539: E/AndroidRuntime(3066): at java.lang.reflect.Method.invoke(Native Method)
03-31 14:34:16.539: E/AndroidRuntime(3066): at java.lang.reflect.Method.invoke(Method.java:372)
03-31 14:34:16.539: E/AndroidRuntime(3066): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-31 14:34:16.539: E/AndroidRuntime(3066): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
03-31 14:34:58.938: E/SQLiteLog(3109): (1555) abort at 12 in [INSERT INTO tag(nb_occurrences,display,_id) VALUES (?,?,?)]: UNIQUE constraint failed: tag._id
03-31 14:34:58.943: E/SQLiteDatabase(3109): Error inserting nb_occurrences=816449 display=javascript _id=1
03-31 14:34:58.943: E/SQLiteDatabase(3109): android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: tag._id (code 1555)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at fr.isima.android.tp3.provider.TagProvider.insert(TagProvider.java:56)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at android.content.ContentProviderOperation.apply(ContentProviderOperation.java:240)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at android.content.ContentProvider.applyBatch(ContentProvider.java:1712)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at android.content.ContentProvider$Transport.applyBatch(ContentProvider.java:287)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at android.content.ContentProviderClient.applyBatch(ContentProviderClient.java:377)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at android.content.ContentResolver.applyBatch(ContentResolver.java:1244)
03-31 14:34:58.943: E/SQLiteDatabase(3109): at fr.isima.android.tp3.service.DataFetchingService$TestThread.run(DataFetchingService.java:126)
03-31 14:34:59.012: E/AndroidRuntime(3109): FATAL EXCEPTION: test
03-31 14:34:59.012: E/AndroidRuntime(3109): Process: fr.isima.android.tp3, PID: 3109
03-31 14:34:59.012: E/AndroidRuntime(3109): android.database.SQLException: Failed to insert row into content://fr.isima.android.tp3.provider.TagProvider/tags
03-31 14:34:59.012: E/AndroidRuntime(3109): at fr.isima.android.tp3.provider.TagProvider.insert(TagProvider.java:66)
03-31 14:34:59.012: E/AndroidRuntime(3109): at android.content.ContentProviderOperation.apply(ContentProviderOperation.java:240)
03-31 14:34:59.012: E/AndroidRuntime(3109): at android.content.ContentProvider.applyBatch(ContentProvider.java:1712)
03-31 14:34:59.012: E/AndroidRuntime(3109): at android.content.ContentProvider$Transport.applyBatch(ContentProvider.java:287)
03-31 14:34:59.012: E/AndroidRuntime(3109): at android.content.ContentProviderClient.applyBatch(ContentProviderClient.java:377)
03-31 14:34:59.012: E/AndroidRuntime(3109): at android.content.ContentResolver.applyBatch(ContentResolver.java:1244)
03-31 14:34:59.012: E/AndroidRuntime(3109): at fr.isima.android.tp3.service.DataFetchingService$TestThread.run(DataFetchingService.java:126)
03-31 14:34:59.060: E/gralloc_goldfish(933): gralloc_alloc: Mismatched usage flags: 288 x 288, usage 333
03-31 14:34:59.061: E/(933): GraphicBufferAlloc::createGraphicBuffer(w=288, h=288) failed (Invalid argument), handle=0x0
03-31 14:34:59.065: E/BufferQueueProducer(1244): [ScreenshotClient] dequeueBuffer: createGraphicBuffer failed
03-31 14:34:59.068: E/ActivityManager(1244): Invalid thumbnail dimensions: 288x288
03-31 14:37:24.259: E/CheckinTask(1730): SSL error, attempting time correction: javax.net.ssl.SSLHandshakeException: Connection closed by peer
03-31 14:37:24.736: E/CheckinTask(1730): Checkin failed: http://ift.tt/WF4AX4 (request #0): javax.net.ssl.SSLHandshakeException: Connection closed by peer
03-31 14:37:34.955: E/ActivityThread(1642): Service com.google.android.gms.backup.BackupTransportService has leaked ServiceConnection com.google.android.gms.http.f@f4c18e9 that was originally bound here
03-31 14:37:34.955: E/ActivityThread(1642): android.app.ServiceConnectionLeaked: Service com.google.android.gms.backup.BackupTransportService has leaked ServiceConnection com.google.android.gms.http.f@f4c18e9 that was originally bound here
03-31 14:37:34.955: E/ActivityThread(1642): at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1072)
03-31 14:37:34.955: E/ActivityThread(1642): at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:966)
03-31 14:37:34.955: E/ActivityThread(1642): at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1768)
03-31 14:37:34.955: E/ActivityThread(1642): at android.app.ContextImpl.bindService(ContextImpl.java:1751)
03-31 14:37:34.955: E/ActivityThread(1642): at android.content.ContextWrapper.bindService(ContextWrapper.java:538)
03-31 14:37:34.955: E/ActivityThread(1642): at com.google.android.gms.http.e.<init>(SourceFile:94)
03-31 14:37:34.955: E/ActivityThread(1642): at com.google.android.gms.http.GoogleHttpClient.<init>(SourceFile:234)
03-31 14:37:34.955: E/ActivityThread(1642): at com.google.android.gms.http.GoogleHttpClient.<init>(SourceFile:196)
03-31 14:37:34.955: E/ActivityThread(1642): at com.google.android.gms.backup.BackupTransportService.onCreate(SourceFile:1172)
03-31 14:37:34.955: E/ActivityThread(1642): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2731)
03-31 14:37:34.955: E/ActivityThread(1642): at android.app.ActivityThread.access$1800(ActivityThread.java:144)
03-31 14:37:34.955: E/ActivityThread(1642): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1361)
03-31 14:37:34.955: E/ActivityThread(1642): at android.os.Handler.dispatchMessage(Handler.java:102)
03-31 14:37:34.955: E/ActivityThread(1642): at android.os.Looper.loop(Looper.java:135)
03-31 14:37:34.955: E/ActivityThread(1642): at android.app.ActivityThread.main(ActivityThread.java:5221)
03-31 14:37:34.955: E/ActivityThread(1642): at java.lang.reflect.Method.invoke(Native Method)
03-31 14:37:34.955: E/ActivityThread(1642): at java.lang.reflect.Method.invoke(Method.java:372)
03-31 14:37:34.955: E/ActivityThread(1642): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-31 14:37:34.955: E/ActivityThread(1642): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
03-31 14:37:34.984: E/StrictMode(1642): null
03-31 14:37:34.984: E/StrictMode(1642): android.app.ServiceConnectionLeaked: Service com.google.android.gms.backup.BackupTransportService has leaked ServiceConnection com.google.android.gms.http.f@f4c18e9 that was originally bound here
03-31 14:37:34.984: E/StrictMode(1642): at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1072)
03-31 14:37:34.984: E/StrictMode(1642): at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:966)
03-31 14:37:34.984: E/StrictMode(1642): at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1768)
03-31 14:37:34.984: E/StrictMode(1642): at android.app.ContextImpl.bindService(ContextImpl.java:1751)
03-31 14:37:34.984: E/StrictMode(1642): at android.content.ContextWrapper.bindService(ContextWrapper.java:538)
03-31 14:37:34.984: E/StrictMode(1642): at com.google.android.gms.http.e.<init>(SourceFile:94)
03-31 14:37:34.984: E/StrictMode(1642): at com.google.android.gms.http.GoogleHttpClient.<init>(SourceFile:234)
03-31 14:37:34.984: E/StrictMode(1642): at com.google.android.gms.http.GoogleHttpClient.<init>(SourceFile:196)
03-31 14:37:34.984: E/StrictMode(1642): at com.google.android.gms.backup.BackupTransportService.onCreate(SourceFile:1172)
03-31 14:37:34.984: E/StrictMode(1642): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2731)
03-31 14:37:34.984: E/StrictMode(1642): at android.app.ActivityThread.access$1800(ActivityThread.java:144)
03-31 14:37:34.984: E/StrictMode(1642): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1361)
03-31 14:37:34.984: E/StrictMode(1642): at android.os.Handler.dispatchMessage(Handler.java:102)
03-31 14:37:34.984: E/StrictMode(1642): at android.os.Looper.loop(Looper.java:135)
03-31 14:37:34.984: E/StrictMode(1642): at android.app.ActivityThread.main(ActivityThread.java:5221)
03-31 14:37:34.984: E/StrictMode(1642): at java.lang.reflect.Method.invoke(Native Method)
03-31 14:37:34.984: E/StrictMode(1642): at java.lang.reflect.Method.invoke(Method.java:372)
03-31 14:37:34.984: E/StrictMode(1642): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-31 14:37:34.984: E/StrictMode(1642): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
03-31 14:37:35.204: E/Backup(1661): [LegacyBackupAccountManager] Fail to get legacy transport context.
03-31 14:37:35.204: E/Backup(1661): android.content.pm.PackageManager$NameNotFoundException: Application package com.google.android.backup not found
03-31 14:37:35.204: E/Backup(1661): at android.app.ContextImpl.createPackageContextAsUser(ContextImpl.java:2139)
03-31 14:37:35.204: E/Backup(1661): at android.app.ContextImpl.createPackageContext(ContextImpl.java:2115)
03-31 14:37:35.204: E/Backup(1661): at android.content.ContextWrapper.createPackageContext(ContextWrapper.java:658)
03-31 14:37:35.204: E/Backup(1661): at com.google.android.gms.backup.am.<init>(SourceFile:47)
03-31 14:37:35.204: E/Backup(1661): at com.google.android.gms.backup.BackupTransportMigratorService.b(SourceFile:162)
03-31 14:37:35.204: E/Backup(1661): at com.google.android.gms.backup.BackupTransportMigratorService.onHandleIntent(SourceFile:80)
03-31 14:37:35.204: E/Backup(1661): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
03-31 14:37:35.204: E/Backup(1661): at android.os.Handler.dispatchMessage(Handler.java:102)
03-31 14:37:35.204: E/Backup(1661): at android.os.Looper.loop(Looper.java:135)
03-31 14:37:35.204: E/Backup(1661): at android.os.HandlerThread.run(HandlerThread.java:61)
03-31 14:37:35.498: E/Backup(1661): [LegacyBackupAccountManager] Fail to get legacy transport context.
03-31 14:37:35.498: E/Backup(1661): android.content.pm.PackageManager$NameNotFoundException: Application package com.google.android.backup not found
03-31 14:37:35.498: E/Backup(1661): at android.app.ContextImpl.createPackageContextAsUser(ContextImpl.java:2139)
03-31 14:37:35.498: E/Backup(1661): at android.app.ContextImpl.createPackageContext(ContextImpl.java:2115)
03-31 14:37:35.498: E/Backup(1661): at android.content.ContextWrapper.createPackageContext(ContextWrapper.java:658)
03-31 14:37:35.498: E/Backup(1661): at com.google.android.gms.backup.am.<init>(SourceFile:47)
03-31 14:37:35.498: E/Backup(1661): at com.google.android.gms.backup.a.a(SourceFile:65)
03-31 14:37:35.498: E/Backup(1661): at com.google.android.gms.backup.c.a(SourceFile:39)
03-31 14:37:35.498: E/Backup(1661): at com.google.android.gms.backup.b.a(SourceFile:67)
03-31 14:37:35.498: E/Backup(1661): at com.google.android.gms.backup.b.a(SourceFile:39)
03-31 14:37:35.498: E/Backup(1661): at com.google.android.gms.backup.BackupAccountNotifierService.onHandleIntent(SourceFile:76)
03-31 14:37:35.498: E/Backup(1661): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
03-31 14:37:35.498: E/Backup(1661): at android.os.Handler.dispatchMessage(Handler.java:102)
03-31 14:37:35.498: E/Backup(1661): at android.os.Looper.loop(Looper.java:135)
03-31 14:37:35.498: E/Backup(1661): at android.os.HandlerThread.run(HandlerThread.java:61)
03-31 14:45:11.498: E/ActivityThread(1642): Service com.google.android.gms.backup.BackupTransportService has leaked ServiceConnection com.google.android.gms.http.f@2ca00e59 that was originally bound here
03-31 14:45:11.498: E/ActivityThread(1642): android.app.ServiceConnectionLeaked: Service com.google.android.gms.backup.BackupTransportService has leaked ServiceConnection com.google.android.gms.http.f@2ca00e59 that was originally bound here
03-31 14:45:11.498: E/ActivityThread(1642): at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1072)
03-31 14:45:11.498: E/ActivityThread(1642): at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:966)
03-31 14:45:11.498: E/ActivityThread(1642): at



Thanks in advance for your help.


Android SqLite Cursor.getgetColumnIndex() Doesn't seem o be working

I'm quite desperate here and can't figure out if there is a bug in my code or if i've done something wrong. My Problem is in reading a database which stores images as Blobs. I have followed tutorials to implement this but something seems broken.


First of i created a databaseHelper class that creates my databases.



@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TBLE_PROFILEIMG + " (" +
FLD_ALLTABLES_UNIQUEPICID + " INTEGER, " +
FLD_ALLTABLES_DELETABLE + " BOOLEAN, " +
FLD_ALLTABLES_PICTURE + " BLOB);");
db.execSQL("CREATE TABLE " + TBLE_EXIMG + " (" +
FLD_EXERCISE_ID + " TEXT, " +
FLD_ALLTABLES_DELETABLE + " BOOLEAN, " +
FLD_ALLTABLES_UNIQUEPICID + " INTEGER, " +
FLD_ALLTABLES_PICTURE + " BLOB);");

}


Then i Created a class to write to the database, There is no problem here and i am sure everything works on spot because i pulled the database from my device and opened it with SQLite Studio. The fields are created correctly and images successfully written as BLOB from an array of bytes.



public List<MyPicture> getProfilePictures() {
Cursor c = readTable(ImgDatabaseHelper.TBLE_PROFILEIMG);
List<MyPicture> bl = new ArrayList<>();
if (c.moveToFirst()) {
while (true) {
int colidx = c.getColumnIndex(ImgDatabaseHelper.FLD_ALLTABLES_PICTURE);
byte[] bb = c.getBlob(colidx);
Bitmap pic = BitmapFactory.decodeByteArray(bb, 0, bb.length);
if (pic != null)
bl.add(
new MyPicture(
pic,
c.getInt(c.getColumnIndex(ImgDatabaseHelper.FLD_ALLTABLES_UNIQUEPICID)),
c.getInt(c.getColumnIndex(ImgDatabaseHelper.FLD_ALLTABLES_DELETABLE)) > 0
)
);

if (c.isLast()) break;
else c.moveToNext();
}
}
return bl;
}


It Can't find the Column:



E/CursorWindow﹕ Failed to read row 0, column 2 from a CursorWindow which has 0 rows, 3 columns.


The Column surely exists because i verified it in sqlite studio. and the column index keeps coming back as null. I am guessing my problem is in the query because the exception says that there are 0 rows when infact i verified that there are 4 rows present. Here is my readTable method:



private Cursor readTable(String table) {
Cursor crs = null;
try {
// Has the same result as the statment under it
// crs = db.query(table, null, null, null, null, null, null, null);
crs = db.rawQuery("SELECT * FROM " + table, null);
}
catch(SQLiteException e) { }
return crs;
}

Selecting multiple tables in SQL

Im new working with SQL. Actually I am working with SQLite and in my DB I have multiple tables. In my case I have 2 tables which should be shown as options. One is shown but the other one I don't know how to access it.


This is what I have now but I want to add another one. So instead "clients" will be "types"


How can I access the other table in the same time?



$sql = "SELECT 'i'.*,
't'.'name' AS 'client_name'
FROM 'items' 'i'
JOIN 'clients' 't'
ON 't'.'id' = 'i'.'client'
ORDER BY 'i'.'date' ASC";
$sql = "SELECT *
FROM 'clients'
ORDER BY 'id'";

How to use QML to import a CSV to s SQLite database?

I've been programming an app that uses two databases, one of which contains contacts that I've exported from outlook.


I would like to import these into a sqlite database using QML/javascript only.


I have created the table and I'm trying to execute the below commands:



function createTable(database)
{
database.transaction(
function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS staff(id INTEGER PRIMARY KEY AUTOINCREMENT, "First Name" TEXT, "Last Name" TEXT)');
tx.executeSql('.mode csv');
tx.executeSql('".import" "./contacts.csv"');
}
)
}


I haven't got to the .import yet so that is secondary. I'm guessing I must be missing some method that I'm not familiar with.


Any help is appreciated.


Filter and display SQLite data by date in listview

I have a SQLite table with date (format: %Y-%m-%d) in one column. Currently the listview is populated with data belonging to all dates. However, I want to populate the listview for a specific date. The specific date need to be provided by the user.


What I did was to get date, month, year in 3 separate editText from the user, add/append the strings. The appended value is then used as a Selection parameter in cursor query. However, on execution I am getting illegalargumentexception. I know that the procedure I followed is probably incorrect. Can someone describe me the right way to populate the listview data by date?


Getting Pointer from Parse.com record in to SQLite table

Since a few days I've been using Parse.com to synchronize data to the cloud. I'm now writing all functions to fetch all data from the cloud and to synchronize it with a local SQLite database.


I fetch all the data from the cloud with a ParseObject like this:



var taskQuery = from TaskTable in ParseObject.GetQuery("Task")
where TaskTable.Get<Boolean>("Deleted") == false
where TaskTable.Get<DateTime>("updatedAt") > SqliteSyncDate
select TaskTable;
IEnumerable<ParseObject> tasks = await taskQuery.FindAsync();


After having it in the ParseObject I loop over it with a foreachbut then I'm having problems. I have a table Task which has a field UserId that I defined as a Pointer to the table Login. I now have to store this Pointer in my SQLite database but I have no clue how to 'parse' and/or save it locally now. My code:



//Loop over every record that is returned from Parse.com
foreach (ParseObject task in tasks)
{
try
{
//Create new record to add to Task
Tasks taskSqlite = new Tasks();
taskSqlite.Id = task.Get<int>("Id");
//This line fails! When I comment it out syncing works, otherwise it doesn't.
taskSqlite.UserId = task.Get<int>("UserId");
taskSqlite.Description = task.Get<string>("Description");
taskname = task.Get<string>("Description");
taskSqlite.Date = task.Get<DateTime?>("Date");
taskSqlite.Done = task.Get<Boolean>("Done");
taskSqlite.DoneBy = task.Get<string>("DoneBy");
taskSqlite.Deleted = task.Get<Boolean>("Deleted");
taskSqlite.LastModified = task.Get<DateTime?>("LastModified");

//And finally insert the record in to the SQLite database.
DATask.InsertTask(taskSqlite);
}
catch
{
Debug.WriteLine("SYNC FAILURE - failed on table Task on the task: " + taskname);
}


If I run this without the try catch I will get the following error:



03-31 16:37:52.676 I/MonoDroid( 4731): UNHANDLED EXCEPTION:
03-31 16:37:52.697 I/MonoDroid( 4731): System.NullReferenceException: Object reference not set to an instance of an object


So how exactly should I convert it or save it into the SQLite database? Would this be the correct way to link records to eachother?


Object calls vs internal database statements

I have an android app and it I want it to display a set of questions dynamically. To help me do this, I have an external database(outside the app) and an internal database(SQLite inside the app). I copy the external to the internal database.


The database contains Surveys, with an x amount of questions.


My question is, is it better to display the questions through frequent statements from the internal database, or make a single statement from the internal database and parse the data into a Survey object and display the questions by talking to the Survey object?


The reason why I ask is because passing an object from Activity to Activity in android isn't easily done.


How to create a SQL database for android?

Hey I want to know how to create a database for android and not a one to be edited by the user, a database that is complete and is in the app apk. Do I use excel or access then add the database to the app folders or what should I do? all I could find on the internet is how to make a database that it's data is added using the app itself. So how do I make a database?


Windows Mobile Cordova - Word Wrap Select Menu Option

I am building a Windows mobile Application through Cordova. I have a Select menu where I have some 8 options which are to be displayed, of which the last option has lengthy text. These values are Static and are coming from Sqlite Database. Now the last option (Other [e.g. Donors;Corpora)is coming out and is not getting displayed completely as show in the picture. enter image description here


How do I word wrap the text there ?


The css I am using is



.disaster {
word-wrap:break-word;
}
.disaster option{
word-wrap:break-word;
}


The Html code I am Using is



<select name="select-disaster" id="select-disaster" class="disaster"></select>


Based upon the id I am getting the select options from the Sqlite database.


Please tell me how to do the Word wrap for this in Windows 8 Mobile Phone ?


how to get sqLite data into Excel sheet

We are developing phoneGap app.We have SqLite db using to save Registration Data.Now We need SqLite db data POST to excel file.Excel file save to my SD card in some location. Please any one tell me.What are required for doing this.I mean any plugins any .js file Please help me.


How to use primary key in Shared Preferences in android?

I am novice to android. I want to use sharedpreferences in my app. I want to use id as primary key so that it is auto incremented whenever I add a new string value. It can be done by using SQLite, but that is very lengthy task. I want to make my app simple.


The insert.xml file is as follows:



package com.example.shiza.dailyquranquote;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;


public class InsertVerse extends ActionBarActivity {
EditText verseContent;
EditText verseId;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_verse);
}
public void saveVerse( View view)
{
verseContent = (EditText)findViewById(R.id.insertVerse);
verseId = (EditText)findViewById(R.id.insertId);


SharedPreferences sharedPreferences = getSharedPreferences("QuranVerse",0);

Editor editor = sharedPreferences.edit();

editor.putInt("id", Integer.parseInt( verseId.getText().toString()));
editor.putString("verse", verseContent.getText().toString());

}

}

How to read and query SQLite database using sqldf in R?

I have a SQLite database pisa06.db created from a data frame. I would like to read variables (columns) from this database file selectively without actually loading into memory. I know I can do it with a data frame already in the workspace. I couldn't figured out how to do it with a database in the disk without reading the whole database.


Let me give you more detail. I have a data frame pisa06. I created a database file pisa06.db in the working directory with



library(sqldf)
drv <- dbDriver("SQLite")
con <- dbConnect(drv, "pisa06.db")
dbWriteTable(con, "pisa06", pisa06)


Now I need to reach this database file and read some variables into a data frame without reading the whole database. I have tried many alternatives. This will not work:



df <- sqldf("select CNT, SCHOOLID from pisa06", drv="SQLite")


How can I use sqldffor this purpose? Is this the best way to do it? Thank you for any help.


Hibernate sqlite SQLITE_BUSY

I am trying to use hibernate with sqlite in multi-threaded application and getting SQLITE_BUSY error:



[SQLITE_BUSY] The database file is locked (database is locked)


Simplified code which reproduces error in 1 thread:



Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(new Object());
session.flush();

Session session2 = sessionFactory.openSession();
session2.beginTransaction();
session2.save(new Object());
session2.getTransaction().commit();


As widely suggested i set pool_size to 1, but it didn't help



<property name="connection.pool_size">1</property>
<property name="hibernate.connection.pool_size">1</property>


packages that i use:



sqlite-jdbc: 3.8.7
hibernate: 4.3.8

Local sql database and heroku postgres database files differ, how to sync again? Ruby on Rails

I am currently doing the Ruby on Rails tutorial by Michael Hartl. Somewhere along the way I messed up my database. In my database file there is only 1 user, by the name of Bob.


Locally in cloud9 IDE, when I do 'rails console' and then do Users.first, I get a user with a name of "Bob".


However when I do 'heroku rails run console' and do Users.first, I get a user with a different name. (I probably changed the name somewhere along the way)


How do I get Heroku to see the correct local database file again? Should I clear the heroku database, then use pg:pull to pull the local sql database to heroku?


I want to develop an android app with internet connectiviyt?how can this be done?

I want to develop an android app with internet connectivity. I need to post regular updates, images and all stuff.How can this type of android app be developed? Do we need to maintain a synch between my sqllite db and server?Please explain me


Repeat sync SQLite database from MYSQL and refresh android UI

I created an android app that have a SQLite database with several tables.And i implemented an IntentService to get data from PHP(MYSQL) site with Volley(JSON). So i can get data from a MYSQL database and update my SQLite database. NOW I WANT TO : 1- repeat Sync action every 5 minutes automatically . 2- refresh android UI(spinner,recyclerView,...) after each Sync data complete.


How to add values in mySQL together with PHP

I need to add values in MySQL and see if its greater than another value then echo the amount of rows.



$result = mysql_query("SELECT created_at,seconds FROM table WHERE created_at + seconds > CURTIME()");
$num_rows = mysql_num_rows($result);
echo $num_rows;

lundi 30 mars 2015

SQLite Subquery Syntax Error when using Multiple Columns

It seems so simple; but I can't get this working.



select ISIN, QuoteTimestamp
from QuoteData
where (ISIN, QuoteTimestamp) IN
(select ISIN, MAX(QuoteTimestamp) QuoteTimestamp
from QuoteData
group by ISIN)


This query gives me a syntax error. If I amend it to only use a single column (remove the MAX(QuoteTimewstamp)) it works.


It seems to be correct, as per the documentation.


Thanks, Al.


how to synchronize between local DB (SQLite) and Parse using objective c

I want to sync data with local database while internet is not available and whenever internet is available i want to parse the data to the local server.I m using SQLite database and I m using json format to parse the data.


Can anyone suggest me how can i do this one?


Thanks!!!!


How to connect database to android eclipse?

I have create database on FireFox SQLite Manager and I want to connect this database to my application eclipse. Please help me and i want to steps to make that


sqlite fts4 can not use offsets funtion when use group by

I have two table: table 1: fts virtual table


docid Long auto increase, content Text, (fts column)


table 2: meta data table


docid Long(foreigner key of table1 docid), username Text, timestamp Long


sql: select table1.docid content, username, MAX(timestamp) as time, offsets(table1) from table1, table2 where content Match "a" AND table1.docid = table2.docid group by username order by timestamp desc limit 3;


this sql will not execute, but i delete "group by username", it can execute. why?


SQLAlchemy core find if row with primary key exists

I would have thought there would be obvious answer to this everywhere but extensive Googling hasn't turned up an obvious answer.


What is the most effective way to find out if a row with a given primary key exists?


I'm using SQLAlchemy core with sqlite on Python 3.


Fetch Skype history

Is there any way to restore last Skype messages from your contacts if you have fresh installed Skype instance?


Is there any SQL-hook for main.db with timestamp updates, so Skype will try to fetch 'unreceived' messages again from my contacts?


Reference another table in SQLite using Web2py/Python

I'm new to Web2py and SQL Databases in general, so forgive me if this is a dumb question.


What I'm trying to do is create a form that pulls relevant data (type, label, IS_NOT_EMPTY(), etc.) from an SQL table's field to populate and configure input elements on the frontend. So far I've successfully been able to do this using the Web2py Manual as an excellent reference.


I've gotten to the point where I'd like to use multiple tables to help categorize sets of data more effectively. Best case scenario would be to have one master table that can be called in my controller file (default.py), that is linked with other relevant (but not always needed) tables in my db.


In the below code you can see that I define the 'category_t' table first, then define the 'new_product' table. I then attempt to reference 'category_t' table within the 'main_category' field on new_product. The 'main_category' field ends up being a multiple select element on the form, which is exactly what I want. I just need to use the field labels from 'category_t' as the multi-select options.


I was using this Links to referencing records instructions from the Web2py Manual, but I believe I'm misinterpreting what it's actually capable of. I desperately need someone to school me on the laws of Web2py and SQLite.



db.define_table(
'category_t',
Field('category1', 'boolean', label='Category 1'),
Field('category2', 'boolean', label='Category 2'),
Field('category3', 'boolean', label='Category 3'),
)

db.define_table(
'new_product',
Field('name', requires=[IS_NOT_EMPTY(), IS_ALPHANUMERIC()], label='Product Name'),
Field('sku', requires=[IS_NOT_EMPTY(), IS_ALPHANUMERIC()], label='SKU'),
Field('build', requires=IS_IN_SET(['Build1','Build2','Build3']), label='Product Type'),
Field('main_category', 'list:reference category_t', label='Category'),
)

SQLiteDataAdapter converts null to 0 - how to prevent that?

Below is a snippet of the code. As you can see, that method returns a table from SQLite database, and adds that table to a DataSet if it doesn't exist yet.



SQLiteConnection connection;
DataSet Set = new DataSet();

DataTable GetTable(string tableName, string command)
{
if (!Set.Tables.Contains(tableName))
{
var adapter = new SQLiteDataAdapter(command, connection);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter);

adapter.FillSchema(Set, SchemaType.Source, tableName);
adapter.Fill(Set, tableName);
adapter.Dispose();
}

return Set.Tables[tableName];
}


To call it, for example



DataTable myTable = GetTable("MyTable", "select * from MyTable);


There are some cells that are of type int/decimal, but their values are null. However when I'm trying to populate myTable, they are conveniently converted to 0's which I DO NOT WANT. How do I go about fixing that? I would like to keep null values as null's.


The SQLite file that I use is SQLite3. Just in case it helps.


Thanks in advance!


Web Server Tutorial (SQLite)

I am currently developing an android application that will connect to the internet to receive data strings. Is there any good tutorial someone can give me or link me to.


Assume that I know nothing about web servers and how to even host one.


How to add Limit to Date_Time in SQLite for Android

The following line is used for query in Android, where orderBy is the parameter



String orderBy = Helper.COLUMN_DATE_TIME +" DESC";


This arranges the table rows in descending order of time. The value of date_time is in the format %Y-%m-%d %H:%M:%S


I would like to introduce LIMIT in the above statement (as in some instances I am only in need of %Y-%m-%d). How can this be done? I mean I am limited by my knowledge and try. Any help would be appreciated


Android how load n TextViews with data from Sqlite query

I have an sqlite db that contain information of some TextViews, like text, background color and id of the changed TextView, because i have a TableView with 60 TextViews. When the user touch one of them, he can change the content of the TextView and the background color. My problem is that when i take back all the saved TextView i put them into a list.


Materia.java is my object



package com.ddz.diarioscolastico;

public class Materia {

private int _id;
private String _nome;
private int _colore;
//private int _giorno;
//private int _ora;

//Empty constructor
public Materia(){

}
//Constructor
public Materia(int id, String nome, int colore){
this._id = id;
this._nome = nome;
this._colore = colore;

}
// constructor
public Materia(String nome, int colore){
this._nome = nome;
this._colore = colore;
}
// getting ID
public int getID(){
return this._id;
}

// setting id
public void setID(int id){
this._id = id;
}

//getting color
public int getColor(){

return this._colore;

}
//setting color
public void setColor(int colore){

this._colore = colore;

}
//getting nome materia
public String getMateria() {

return this._nome;

}
//setting nome materia
public void setMateria(String nome) {

this._nome = nome;

}
}


With the class MySQLiteHelper i manage the database



public class MySQLiteHelper extends SQLiteOpenHelper {

//Database version
private static final int DATABASE_VERSION = 1;
//Database name
private static final String DATABASE_NAME = "materie.db";
//Materie table name
public static final String TABLE_MATERIE = "materie";
//Materie columns table names
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "nome";
public static final String COLUMN_COLOR = "colore";

public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_MATERIE_TABLE = "CREATE TABLE " + TABLE_MATERIE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT,"
+ COLUMN_COLOR + " INTEGER," + ")";
db.execSQL(CREATE_MATERIE_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MATERIE);

// Create tables again
onCreate(db);
}

// Adding new contact
public void addMateria(Materia materia) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(COLUMN_NAME, materia.getMateria()); // Materia Name
values.put(COLUMN_COLOR, materia.getColor()); // Materia color

// Inserting Row
db.insert(TABLE_MATERIE, null, values);
db.close(); // Closing database connection
}

// Getting single contact
public Materia getMateria(int id) {
SQLiteDatabase db = this.getReadableDatabase();

//ELIMINATO COLUMN_DAY e COLUMN_HOUR
Cursor cursor = db.query(TABLE_MATERIE, new String[] { COLUMN_ID,
COLUMN_NAME, COLUMN_COLOR }, COLUMN_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Materia materia = new Materia(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
Integer.parseInt(cursor.getString(2)));
// return contact
return materia;
}

// Getting All Contacts
public List<Materia> getAllMaterie() {
List<Materia> materiaList = new ArrayList<Materia>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_MATERIE;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Materia materia = new Materia();
materia.setID(Integer.parseInt(cursor.getString(0)));
materia.setMateria(cursor.getString(1));
materia.setColor(Integer.parseInt(cursor.getString(2)));
// Adding contact to list
materiaList.add(materia);
} while (cursor.moveToNext());
}

// return contact list
return materiaList;
}

// Getting contacts Count
public int getMateriaCount() {
String countQuery = "SELECT * FROM " + TABLE_MATERIE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}

// Updating single contact
public int updateMateria(Materia materia) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(COLUMN_NAME, materia.getMateria());
values.put(COLUMN_COLOR, materia.getColor());

// updating row
return db.update(TABLE_MATERIE, values, COLUMN_ID + " = ?",
new String[] { String.valueOf(materia.getID()) });
}

// Deleting single contact
public void deleteMateria(Materia materia) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_MATERIE, COLUMN_ID + " = ?",
new String[] { String.valueOf(materia.getID()) });
db.close();
}

}//Close class database


As you can see with the method public List<Materia> getAllMaterie() i take all materie from sqlite and put them into a list.


onCreate of the activity that manage data:



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_orario);

MySQLiteHelper db = new MySQLiteHelper(this);

//Get all materie inside database
List<Materia> materia = db.getAllMaterie();

//Cambio ciclicamente le textview presenti nel database
TextView changedtextview = (TextView)findViewById(materia.);
changedtextview.setText(materia.nome);


}//Fine oncreate


In my Activity i need to take back all the materie inputed into database for change the TextViews that are touched from user. How can i take the single id's in the List materia? Something like:



TextView changedtextview = (TextView)findViewById(materia._id);


But this not work. There is something wrong?


Android APP multilanguage SQLite

I would fully translate my Android app. (this includes the SQLite is displayed on the phone language)


This is like now connect;



private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "quotes.db";
private static final String DB_PATH_SUFFIX = "/databases/";
private static final String TABLE_QUOTES = "quote";
private static final String KEY_ID = "_id";
static Context myContext;

public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myContext = context;
}


I had thought to remove the name string database and pass it the name database using the strings.xml file.


super(context, context.getResources (). getString (R.string.DATABASE_NAME), null, DATABASE_VERSION);


Also look for the query to pass on through strings.xml, but can not find clear documentation.


I would appreciate if I do not guide a little. Many Thanks.


Example the query:



// Select All Query
String selectQuery = "SELECT name, COUNT(author_name ) AS count FROM author LEFT JOIN quote ON name = author_name WHERE name LIKE '%"
+ value + "%' GROUP BY name ORDER BY name ASC";

Generating Achart From SQLite Database

I am trying to display information from my SQLite database in a chart. I am using the AchartEngine for this, but I cannot seem to get the chart to populate from the database. I have hard coded in in the example below to show that the chart draws, but no matter what I try, I cannot seem to get the values to plot on the chart. I am new to android and any help would be great.


Thanks.


Here is my DBAdapter Class:



public class DBAdapter {

// For logging:
private static final String TAG = "DBAdapter";

// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;

public static final String KEY_EXERCISE = "exercise";
public static final String KEY_LAST = "lastCount";
public static final String KEY_HIGH = "highCount";


public static final int COL_EXERCISE = 1;
public static final int COL_LAST = 2;
public static final int COL_HIGH = 3;

public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_EXERCISE,
KEY_LAST, KEY_HIGH };


public static final String DATABASE_NAME = "Exercise.db";
public static final String DATABASE_TABLE = "CounterTable";

public static final int DATABASE_VERSION = 3;

private static final String CREATE_TABLE = "CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_EXERCISE
+ " TEXT NOT NULL, " + KEY_LAST + " TEXT NOT NULL, "
+ KEY_HIGH + " TEXT NOT NULL);";

// Context of application
private DatabaseHelper myDBHelper;
private final Context context;
private SQLiteDatabase db;

public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}

// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}

// Close the database connection.
public void close() {
myDBHelper.close();
}

// Add a new set of values to the database.
public long insertRow(String exercise, int lastCount, int highCount) {

// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_EXERCISE, exercise);
initialValues.put(KEY_LAST, lastCount);
initialValues.put(KEY_HIGH, highCount);

// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}

// Change an existing row to be equal to new data.
public void updateRow(long rowId, String exercise,
int lastCount, int highCount) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_EXERCISE, exercise);
newValues.put(KEY_LAST, lastCount);
newValues.put(KEY_HIGH, highCount);

// Insert it into the database.
db.update(DATABASE_TABLE, newValues, where, null);
}

// Change an existing row to be equal to new data.
public void updateRow(String exercise, int lastCount) {
String where = KEY_EXERCISE + "= \"" + exercise +"\"";
ContentValues newValues = new ContentValues();
newValues.put(KEY_LAST, lastCount);

// Insert it into the database.
db.update(DATABASE_TABLE, newValues, where, null);
}

// Change an existing row to be equal to new data.
public void updateRow(String exercise, int lastCount, int highCount) {
String where = KEY_EXERCISE + "= \"" + exercise +"\"";
ContentValues newValues = new ContentValues();
newValues.put(KEY_LAST, lastCount);
newValues.put(KEY_HIGH, highCount);

// Insert it into the database.
db.update(DATABASE_TABLE, newValues, where, null);
}

// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}

public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}

// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}

// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}

public Cursor getRow(String exercise) {
String where = KEY_EXERCISE + "= \"" + exercise +"\"";
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}


/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");

// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

// Recreate new database:
onCreate(_db);
}
}


}


Here is my ChartActivity:



public class BarChartActivity extends Circuit {

private Button BackButton;
private View mChart;
private String[] exercise = new Circuit().exercises;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw_bar_chart);

BackButton = (Button) this.findViewById(R.id.backButton);

// Set up quit button function
BackButton.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {

Intent intent = new Intent(getApplicationContext(), ChartMenu.class);
startActivity(intent);

}
});


////////////////////////////////////////////****Problem Here****/////////////////////////////////////////////////////////////////////////////



int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };

// What do i put in here to get the values to read from the database?
int[] Last = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
int[] Highest = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



// Creating an XYSeries for Last
XYSeries LastSeries = new XYSeries("Last");
// Creating an XYSeries for Highest
XYSeries HighestSeries = new XYSeries("Highest");
// Adding data to Last and Highest Series
for (int i = 0; i < x.length; i++) {
LastSeries.add(i, Last[i]);
HighestSeries.add(i, Highest[i]);
}

// Creating a dataset to hold each series
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
// Adding Last Series to the dataset
dataset.addSeries(LastSeries);
// Adding Highest Series to dataset
dataset.addSeries(HighestSeries);

// Creating a XYMultipleSeriesRenderer to customize the whole chart
XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setChartTitle("Last vs Highest Chart");
multiRenderer.setXTitle("Exercises");
multiRenderer.setYTitle("Reps");
multiRenderer.setAxesColor(Color.BLACK);
multiRenderer.setLabelsColor(Color.BLACK);
multiRenderer.setMarginsColor(Color.WHITE);
multiRenderer.setBarSpacing(0.5);
multiRenderer.setYLabelsPadding(10);
multiRenderer.setMargins(new int[] { 5, 15, 5, 5 });
multiRenderer.setXLabelsAngle(300);
multiRenderer.setXLabelsPadding(20);
for (int i = 0; i < exercise.length - 1; i++) {
multiRenderer.addXTextLabel(i, exercise[i]);
}

// Creating XYSeriesRenderer to customize highestSeries
XYSeriesRenderer highestRenderer = new XYSeriesRenderer();
highestRenderer.setDisplayChartValues(true);
highestRenderer.setChartValuesSpacing((float) 2.5);

// Creating XYSeriesRenderer to customize lastSeries
XYSeriesRenderer lastRenderer = new XYSeriesRenderer();
lastRenderer.setColor(Color.RED);
lastRenderer.setDisplayChartValues(true);
lastRenderer.setChartValuesSpacing((float) 2.5);

// Adding LastRenderer and HighestRenderer to multipleRenderer
// Note: The order of adding dataseries to dataset and renderers to
// multipleRenderer
// should be same
multiRenderer.addSeriesRenderer(lastRenderer);
multiRenderer.addSeriesRenderer(highestRenderer);

// this part is used to display graph on the xml
LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart);
// remove any views before u paint the chart
chartContainer.removeAllViews();
// drawing bar chart
mChart = ChartFactory.getBarChartView(BarChartActivity.this, dataset,
multiRenderer, null);
// adding the view to the linearlayout
chartContainer.addView(mChart);

db.close();
}
}


}


I'm already using a simple cursor adapter to read from the db in another class to display the db in a listView:



public class LogView extends Activity {

private Button BackButton;

DBAdapter myDb;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db_list);

openDB();
populateListViewFromDB();
//registerListClickCallback();
}

@Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}

private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}

private void closeDB() {
myDb.close();
}

public void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();

// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);

// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[] { DBAdapter.KEY_ROWID, DBAdapter.KEY_EXERCISE,
DBAdapter.KEY_LAST, DBAdapter.KEY_HIGH,
DBAdapter.KEY_LAST };
int[] toViewIDs = new int[] { R.id.textView0, R.id.textView2, R.id.textView1,
R.id.textView3 };

// Create adapter to may columns of the DB onto elements in the UI.
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.item_layout, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);

// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.list);
myList.setAdapter(myCursorAdapter);

BackButton = (Button) this.findViewById(R.id.backButton);

// Set up quit button function
BackButton.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {

Intent intent = new Intent(getApplicationContext(), StartScreen.class); startActivity(intent);

}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.log_view, menu);
return true;
}


}


Any help would be great, I'm really stuck. Thanks