samedi 31 janvier 2015

Item not deleting from SQlite Database

In my app I have multiple markers that are added to the map and saved in SQLite, but now i want to delete a specific marker when tapping on that marker and select "delete marker" So what I have done is this:


In my LocationsDB.class



@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + DATABASE_TABLE + " ( " +
FIELD_ROW_ID + " integer primary key autoincrement , " +
FIELD_LNG + " double , " +
FIELD_LAT + " double , " +
FIELD_ZOOM + " text , " +
FIELD_TITLE + " text , " +
FIELD_SNIPPET + " text , " +
" ) ";

db.execSQL(sql);
}

public long insert(ContentValues contentValues){
long rowID = mDB.insert(DATABASE_TABLE, null, contentValues);
return rowID;
}

public int del(int id){
int cnt = mDB.delete(DATABASE_TABLE, FIELD_ROW_ID+"="+id, null);
return cnt;
}


Then in my LocationsContentProvider.class:



@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
return 0;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int cnt = 0;
cnt = mLocationsDB.del(cnt);
return cnt;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

if(uriMatcher.match(uri)==LOCATIONS){
return mLocationsDB.getAllLocations();
}
return null;
}

@Override
public String getType(Uri uri) {
return null;
}
}


And then finally in my MainActivity.class:



public void onClick(DialogInterface arg0, int arg1) {
marker.remove();
LocationDeleteTask deleteTask = new LocationDeleteTask();
deleteTask.execute();
}
})

....

@Override
public void onLoaderReset(Loader<Cursor> arg0) {
}
class LocationInsertTask extends AsyncTask<ContentValues, Void, Void>{
@Override
protected Void doInBackground(ContentValues... contentValues) {
getContentResolver().insert(LocationsContentProvider.CONTENT_URI, contentValues[0]);
return null;
}
}

private class LocationDeleteTask extends AsyncTask<Void, Void, Void>{

@Override
protected Void doInBackground(Void... params) {
getContentResolver().delete(LocationsContentProvider.CONTENT_URI, null, null);
return null;


This initially works when selecting "delete marker" but when returning to the activity the marker then returns and doesn't get deleted?


Am not sure what i am doing wrong, so hoping someone could help me please?


AutoCompleteView load data from database

In my android application I have a database of around 1000 rows of data in one table. I have an auto complete text view when user enters a key it hast to drop-down appropriate item from the db table how can I do this.


database fetching code



public Map<String, String> getSimilarStems(String stem) {
Map<String, String> results = new LinkedHashMap<String, String>();

Cursor res = db.rawQuery("SELECT word, _id FROM words_en WHERE stems LIKE '%"+stem+" %' OR stems LIKE '"+stem+"' ORDER BY LENGTH(word) LIMIT 10", null);

while(res.moveToNext()) {
String id = res.getString(res.getColumnIndex("_id"));
String word = res.getString(res.getColumnIndex("word"));
results.put(id, word);
}
return results;
}


please anyone help me to bind the data from the database with the AutoCompleteView


create sqlite db programmatically in a custom framework iOS

I am creating a custom framework. I also want to add a sqlite database programatically into the custom framework and access it. I was wondering if it is possible to add db in a framework instead of the application resources folder. If not is there a work around, bc I don't want the sqlite db to be in the application. Must be in the framework.


Thank you for your help.


Android SQLite: Spinner + select sql methods

I have a Spinner which is showing SQLite data. For that I am using this select method:



public List<String> getAllProductsName(int id)
{

String buildSQL = "SELECT nome FROM " + DatabaseHelper.Produtos.TABELA + " WHERE id =" + id;


List<String> nomes = new ArrayList<String>();

SQLiteDatabase db = this.getDatabase();

Cursor cursor = database.rawQuery(buildSQL, null);

if (cursor.moveToFirst()) {
do {
nomes.add(cursor.getString(0));
} while (cursor.moveToNext());
}

return nomes;
}


The thing is, I am getting only the names but I need the ID as well. I know i could use "SELECT nome, _id FROM ", but how would I return that? Could i possibly return 2 lists (one with IDS and the other one with the Names) in the same method?


Or maybe I should create a new method that show the Names only (when i give the ID as a parameter)? Please help! thanks in advance! :)


Retrieve images from SQLite database and display on ImageView

I have an Activity1 which I can take pictures with device camera and convert to bitmap to display on ImageView, compress to save on a bundle to display on seconds activity2


code activity 1



//declare
private ImageView img_1
img_1 = (ImageView) this.findViewById(R.id.img_1);

//code
img_1.buildDrawingCache();
Bitmap image = img_1.getDrawingCache();

ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] food = stream.toByteArray();

Bundle extras = new Bundle();

//intent img1
Intent intent = new Intent(this, activity2.class);
intent.putExtras(extras);
intent.putExtra("picture", food);
startActivity(intent);

//method take picture
//Button img1
public void img1_takePicture (View view)
{
num = 1;
contadorImg = 1;
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

File imagesFolder = new File(
Environment.getExternalStorageDirectory(), "proyect");
imagesFolder.mkdirs();

File image = new File(imagesFolder, "temp1.png");
Uri uriSavedImage = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(cameraIntent, 1);
}

//method onActivityResult
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if (num == 1)
{
if (requestCode == 1 && resultCode == RESULT_OK)
{
//convert bitmap
Bitmap bMap = BitmapFactory.decodeFile(
Environment.getExternalStorageDirectory() +
"/proyect/" + "temp1.png");
//show bitmap
img_1.setImageBitmap(bMap);
}
}


second Activity2


I retrieve bundle with bitmap and show on another ImageView to later save that image on Byte array [] and save on SQLite Database.



//code
//declare
private ImageView img_1_confir;
public BBDD database;
private byte[] img = null;
img_1_confir = (ImageView) findViewById(R.id.img_1_confir);

//retrieve img1, convert to byte array and save on BBDD
Bundle extras = getIntent().getExtras();

byte[] food = extras.getByteArray("picture");
Bitmap fo = BitmapFactory.decodeByteArray(food, 0, food.length);

img_1_confir.setImageBitmap(fo);

//button send
Bitmap bitmap = ((BitmapDrawable) img_1_confir.getDrawable()).getBitmap();

// convert to byte array and save on BBDD
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
img = bos.toByteArray();

//insert
database = new BBDD(this, "BBDD", null, 1);
SQLiteDatabase db = database.getWritableDatabase();

ContentValues registro = new ContentValues();

registro.put("imgone", img);

if (db.insert("database", null, registro) != -1)
{
Toast.makeText(this, "Registro insert", Toast.LENGTH_LONG)
.show();
db.close();
}


Activity Database BBDD



public class BBDD extends SQLiteOpenHelper
{
private static final String KEY_ID = "id";

String crear = "CREATE TABLE infotra(KEY_ID INTEGER PRIMARY KEY," +
"imgone blob) ";

public BBDD (Context contexto, String nombre, CursorFactory factory,
int version)
{
super(contexto, nombre, factory, version);
}

public void onCreate (SQLiteDatabase db)
{
db.execSQL(crear);

}

public void onUpgrade (SQLiteDatabase db, int versionAnt, int versionNue)
{
db.execSQL(crear);
}


NOW MY PROBLEM I have another Activity (activity3). That activity have a ListView with CustomAdapter, when I click on one position on that ListView I need get that byte array from SQLite database, convert to Bitmap and display on another ImageView.


THATS WORKS BUT… CODE ACTIVITY3



//DECLARE
private byte[] img1 =null;
ListView listView;
BBDD database;
private ImageView img_1_confir;
listView = (ListView) findViewById(R.id.listView);
img_1_confir=(ImageView)findViewById(R.id.img_1_confir);
//code
//listview clic
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick (AdapterView<?> parnet, android.view.View view,
int position, long id)
{
database = new BBDD(Activity3.this, "BBDD", null, 1);
SQLiteDatabase db2 = database.getReadableDatabase();
if (db2 != null)
{
//retrieve image1
String[] col={"imgone"};
Cursor cursor1=db2.query("database", col, null, null, null, null, null);

if(cursor1!=null){
cursor1.moveToFirst();
do{
img1=cursor1.getBlob(cursor1.getColumnIndex("imgone"));
}while(cursor1.moveToNext());
}
Bitmap b1=BitmapFactory.decodeByteArray(img1, 0, img1.length);

img_1_confir.setImageBitmap(b1);
}


MY FINAL PROBLEM


Thats Works but if i take another pic and and I keep in a new row in the database (there are two rows then), obviously another item appears on Activity3's ListView but if I clic any of the items always appears last saved image….What is the problem? Why only appears last saved?


SQLITE Select results into a string

I am looking for a method to return the results of an SQLite query as a single string for use in an internal trigger.


Something like Python's 'somestring'.join() method.



Table: foo
id | name
1 | "foo"
2 | "bar"
3 | "bro"


Then a select statement:



MAGIC_STRING_CONCAT_FUNCTION(SELECT id FROM foo,",");


To return "1,2,3"


sqlite "like" syntax didn't bring any results

I try to read from the sqlitDB with the following query:



public ArrayList<ReminderNote> getAllRegexItems(String author) {
ArrayList<ReminderNote> results = new ArrayList<>();

Cursor cursor = this.getReadableDatabase().query(
REMINDER_NOTE_TABLE,
new String[]{KEY_ID, KEY_NOTE, KEY_AUTHOR}, Strings.isEmpty(author) ? null : KEY_AUTHOR + " = ?",
Strings.isEmpty(author) ? null : new String[]{"%" + author + "%"}, null, null, null);


is it OK to use the % like i did?


If author is null or empty I want all the results to be fetched.


Unfortunately I get empty results set even though I added such entity beforehand.


and I can see non-empty results set when I execute:



Cursor cursor = this.getReadableDatabase().query(
REMINDER_NOTE_TABLE,
new String[]{KEY_ID, KEY_NOTE, KEY_AUTHOR}, null, null, null, null, null);

Is there any way to exclude results of a query based on its own results?

Say I have a normal SELECT call like (well, this is really simplified for the question):



SELECT * FROM table WHERE column_b = "X" and column_c = "Y"


but I also want to exclude the results where column_a (the primary key) matches column_k of any other matched results. I think I can do it something like (I haven't tested this because it's not the way I want to do it)



SELECT * FROM table WHERE column_b = "X" AND column_c = "Y"
AND column_a NOT IN
(SELECT column_k FROM table WHERE column_b = "X" AND column_c = "Y")


Being a big advocate of DRY programming, I don't like that this method pretty much repeats the entire SELECT call, if it even works. Is there a better way to do this?


Database directory issue

Our app has been rejected with this indications by Apple:


"Please verify that only the content that the user creates using your app, e.g., documents, new files, edits, etc. is backed up by iCloud as required by the iOS Data Storage Guidelines. Also, check that any temporary files used by your app are only stored in the /tmp directory; please remember to remove or delete the files stored in this location when it is determined they are no longer needed.


Data that can be recreated but must persist for proper functioning of your app - or because users expect it to be available for offline use - should be marked with the "do not back up" attribute. For NSURL objects, add the NSURLIsExcludedFromBackupKey attribute to prevent the corresponding file from being backed up. For CFURLRef objects, use the corresponding kCRUFLIsExcludedFromBackupKey attribute."


We are surprised because our database is in the Library root folder (not in Caches), and no content is stored in the Documents folder. So, why they quote iCloud and Data Storage GuideLines related to Documents folder?


Many thanks for your help.


SQLite select statement is not working when a column contains the '?' or the 'x' character

I noticed that whenever I try to execute an sqlite query on a column that contains strings in which the '?' (due to encoding errors) or the 'x' character is contained, the matching fails. Does anyone know why? I suspect the second case has something to do with the relative hexadecimal symbol. This holds for either sqlite version 3.7.9 and 3.8.6. Thanks in advance


hot to get last created id from sqlite data base using javascript?

$('#CreateCustomer').submit(function () { if ($('#CreateCustomer').parsley('validate')) {



var name = $('#pname').val();
var city = $('#pcity').val();
var address = $('#paddress').val();
var mail = $('#pmail').val();
var phone1 = $('#pphone1').val();
var phone2 = $('#pphone2').val();
db.transaction(function (tx) {
tx.executeSql(InsertPerson, [name, mail, city, address, phone1, phone2], onError);
});
}
ResetForm();
$('#close').click();
location.href = "view.html?id=" + id;
return false;

"!="/NOT perhaps not working properly in SQLite

I have a table with about a hundred rows. It has a column is_gallery that contains either 1, 0, or NULL. If I do...



SELECT * WHERE is_gallery != 1


or



SELECT * WHERE NOT (is_gallery = 1)


it excludes the rows where is_gallery is null. I can manage to get a proper response if I do



SELECT * WHERE (is_gallery = 0 OR is_gallery is null)


But shouldn't the "!=" or NOT work? Isn't there a way to just return the rows where is_gallery doesn't equal 1 without testing for every other possibility?


How can I set a UITableView's cell text to database cell's content in Swift?

I am creating an iOS Pokémon database application using Swift, for my A2 computing coursework. Before this project, I have not used Swift, so I am teaching myself using relevant examples which I can hopefully copy and paste from.


I am using Xcode 6.1.1 and the SQLite.swift library from Stephen Celis.


One such test is producing a UITableView which can read from my pre-existing, pre-populated database.


I've managed to get the UITableView to create all the cells - and set the detailTextLabel to the indexPath (plus 1, so it starts at 1 and ends at 721 instead of starting at 0 and ending at 720). So I have 721 cells in the table just fine.


However, I can't seem to get the textLabel for each cell to display the correct data. Instead, it displays "SQLite.Expression" for each cell.


Above the ViewController class in the ViewController.swift file, I have



let db = Database("/Users/rhysmorgan/Documents/Coding/DatabaseLoadTest/Pokémon Database.sqlite", readonly: true)
let pokemonTable = db["Pokémon"]
let name = Expression<String>("PokéName")
let gen = Expression<Int>("Generation")


and in the main tableView function, I have



func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cellIdentifier = "Cell"
let rowno: Int = indexPath.row + 1
let formatter = NSNumberFormatter(); formatter.minimumIntegerDigits = 3
let formattedrowno = formatter.stringFromNumber(rowno)
let pokemonname = pokemonTable[name]


let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell

cell.textLabel?.text = "\(pokemonname)"
cell.detailTextLabel?.text = "\(formattedrowno!)"

return cell
}


Is anybody able to help me? With thanks in advance!


populate listview from cursor+sqlite + CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0

I know there are multiple threads regarding this issue; but i'm not being able to solve CursorIndexOutOfBoundsException. I'm trying to populate my query using cursor and fetch the results into a listview.But whenever the second activity(for creating the listview) is called, app crashes. in logcat it says "CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0" I'm attaching code segments for better understanding. DatabaseHandler.java



public class DatabaseHandler extends SQLiteAssetHelper {

// for our logs
public static final String TAG = "DatabaseHandler.java";

// database version
private static final int DATABASE_VERSION = 1;

// database name
protected static final String DB_NAME = "med2";

public static String DB_PATH;

// table details
public String tableName = "allopathmedicine";

public String _id = "_id";

public String fieldObjectName = "medicinename";

public String medtype = "medicinetype";

public String companyname = "companyname";

public String medgroup = "medicinegroup";

public String medfor ="medicinefor";

public String medid = "registrationid";

public String p;

private SQLiteDatabase database;

private Context context;

public long id2;

// constructor
public DatabaseHandler(Context context) throws IOException {
super(context, DB_NAME, null, DATABASE_VERSION);
this.context=context;
this.database= getReadableDatabase();
}

/*
* Read records related to the search term
*/
public MyObject[] read(String searchTerm) {
// select query
String sql = "";
sql += "SELECT * FROM " + tableName;
sql += " WHERE " + fieldObjectName + " LIKE '" + searchTerm + "%'";
sql += " ORDER BY " + _id + " DESC";
sql += " LIMIT 0,15";

SQLiteDatabase db = this.getWritableDatabase();

// execute the query
Cursor cursor = db.rawQuery(sql, null);

int recCount = cursor.getCount();

MyObject[] ObjectItemData = new MyObject[recCount];
int x = 0;

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {

String objectName = cursor.getString(cursor.getColumnIndex(fieldObjectName));
id2 = cursor.getInt(cursor.getColumnIndexOrThrow(_id));
Log.e(TAG, "objectName: " + objectName);

MyObject myObject = new MyObject(objectName);

ObjectItemData[x] = myObject;

x++;

} while (cursor.moveToNext());
}
cursor.close();
db.close();
p= ObjectItemData.toString();
return ObjectItemData;
}

public Cursor get() throws IOException
{
return this.Getmedicine(id2);
}
public Cursor Getmedicine(long id2) throws SQLException {
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCursor =
db.query(true, tableName, new String[] {medid,_id,
medfor, medtype,fieldObjectName}, _id + " = " + id2, null,
null, null, null, null);
String rid = mCursor.getString(mCursor.getColumnIndex(medid));
mCursor.moveToFirst();
if (mCursor != null) {
mCursor.moveToFirst();
}
mCursor.close();
db.close();
return mCursor;
}

/*public ArrayList<Medicineinfo> getmedDetails(String ObjectItemData) throws SQLException {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Medicineinfo> getmedDetails = new ArrayList<Medicineinfo>();
Cursor cursor =
db.query(true,tableName, new String[] {
fieldObjectName,
medtype,
companyname,
medgroup},
fieldObjectName + "=?" ,
new String[] {ObjectItemData},
null, null, null , null);
if (cursor.moveToFirst()) {
do {
Medicineinfo Medicineinfo= new Medicineinfo();
Medicineinfo.setMedfor(cursor.getString(cursor.getColumnIndexOrThrow(medfor)));
Medicineinfo.setMedid (cursor.getString(cursor.getColumnIndex(medid)));
//Medicineinfo.comName( cursor.getString(cursor.getColumnIndex(companyname)));
Medicineinfo.setMedgroup(cursor.getString(cursor.getColumnIndex(medgroup)));
Medicineinfo.setMedtype(cursor.getString(cursor.getColumnIndex(medtype)));
getmedDetails.add(Medicineinfo);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return getmedDetails;
}*/

}


Detailinformation.java



public class Detailinformation extends ListActivity {
private Cursor mcursor;
SimpleCursorAdapter adapter;

// for database operations
DatabaseHandler databaseH;

@Override
protected void onCreate(Bundle savedInstanceState) throws SQLException {

super.onCreate(savedInstanceState);
setContentView(R.layout.details);


// get data from cursor
try {
databaseH = new DatabaseHandler(Detailinformation.this);

// put sample data to database
mcursor = databaseH.get();
mcursor.moveToFirst();

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
databaseH.get(),
new String[] { "_id", "medid" },
new int[] { android.R.id.text1, android.R.id.text2 });
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListView lv = (ListView) findViewById(android.R.id.list);
lv.setAdapter(adapter);
}

//get data from arraylist


protected void onDestroy() {
super.onDestroy();
mcursor.close();

}
}


Logcat:



01-31 23:39:50.942: E/SQLiteLog(2629): (14) cannot open file at line 30046 of [9491ba7d73]
01-31 23:39:50.942: E/SQLiteLog(2629): (14) os_unix.c:30046: (2) open(/data/data/com.com.mity.medicalinformationbd/databases/med2) -
01-31 23:39:50.948: I/art(2629): Background sticky concurrent mark sweep GC freed 1806(102KB) AllocSpace objects, 0(0B) LOS objects, 33% free, 412KB/623KB, paused 1.226ms total 135.625ms
01-31 23:39:50.995: E/SQLiteDatabase(2629): Failed to open database '/data/data/com.com.mity.medicalinformationbd/databases/med2'.
01-31 23:39:50.995: E/SQLiteDatabase(2629): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.returnDatabase(SQLiteAssetHelper.java:363)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.createOrOpenDatabase(SQLiteAssetHelper.java:344)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:178)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:257)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at com.mity.medicalinformationbd.DatabaseHandler.<init>(DatabaseHandler.java:56)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at com.mity.medicalinformationbd.MainActivity.onCreate(MainActivity.java:43)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.app.Activity.performCreate(Activity.java:5933)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.app.ActivityThread.access$800(ActivityThread.java:144)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.os.Handler.dispatchMessage(Handler.java:102)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.os.Looper.loop(Looper.java:135)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at android.app.ActivityThread.main(ActivityThread.java:5221)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at java.lang.reflect.Method.invoke(Native Method)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at java.lang.reflect.Method.invoke(Method.java:372)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
01-31 23:39:50.995: E/SQLiteDatabase(2629): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
01-31 23:39:50.995: W/SQLiteAssetHelper(2629): could not open database med2 - unknown error (code 14): Could not open database
01-31 23:39:50.995: W/SQLiteAssetHelper(2629): copying database from assets...
01-31 23:39:51.102: W/SQLiteAssetHelper(2629): extracting file: 'med2.db'...
01-31 23:39:51.632: W/SQLiteAssetHelper(2629): database copy complete
01-31 23:39:51.667: I/art(2629): Background partial concurrent mark sweep GC freed 506(88KB) AllocSpace objects, 0(0B) LOS objects, 55% free, 411KB/923KB, paused 8.723ms total 35.226ms
01-31 23:39:51.691: I/SQLiteAssetHelper(2629): successfully opened database med2
01-31 23:39:52.624: D/gralloc_goldfish(2629): Emulator without GPU emulation detected.
01-31 23:48:16.207: I/Choreographer(2629): Skipped 130 frames! The application may be doing too much work on its main thread.
01-31 23:48:17.672: E/CustomAutoCompleteTextChangedListener.java(2629): User input: a
01-31 23:48:17.949: E/DatabaseHandler.java(2629): objectName: Anestic Cream
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Alconil Mouthwash
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Albamax DS
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Analac
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Atolip 10
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Avloxin 500
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Avloxin
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Avloxin 250
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Avlotrin
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Avlotrin
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Avlotrin
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Avlosef 500
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Avlosef
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Avlosef DS 250
01-31 23:48:17.950: E/DatabaseHandler.java(2629): objectName: Avlosef 500 mg
01-31 23:48:18.366: I/Choreographer(2629): Skipped 36 frames! The application may be doing too much work on its main thread.
01-31 23:48:20.109: I/Choreographer(2629): Skipped 45 frames! The application may be doing too much work on its main thread.
01-31 23:48:20.340: E/CustomAutoCompleteTextChangedListener.java(2629): User input: com.mity.medicalinformationbd.MyObject@26b3e612
01-31 23:48:20.410: I/SQLiteAssetHelper(2629): successfully opened database med2
01-31 23:48:20.555: E/CustomAutoCompleteTextChangedListener.java(2629): User input: Anestic Cream
01-31 23:48:20.575: I/SQLiteAssetHelper(2629): successfully opened database med2
01-31 23:48:20.619: E/DatabaseHandler.java(2629): objectName: Anestic Cream
01-31 23:48:20.766: I/Choreographer(2629): Skipped 150 frames! The application may be doing too much work on its main thread.
01-31 23:48:21.846: I/SQLiteAssetHelper(2629): successfully opened database med2
01-31 23:48:22.099: D/AndroidRuntime(2629): Shutting down VM
01-31 23:48:22.099: D/AndroidRuntime(2629): --------- beginning of crash
01-31 23:48:22.309: E/AndroidRuntime(2629): FATAL EXCEPTION: main
01-31 23:48:22.309: E/AndroidRuntime(2629): Process: com.com.mity.medicalinformationbd, PID: 2629
01-31 23:48:22.309: E/AndroidRuntime(2629): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.com.mity.medicalinformationbd/com.mity.medicalinformationbd.Detailinformation}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.app.ActivityThread.access$800(ActivityThread.java:144)
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.os.Handler.dispatchMessage(Handler.java:102)
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.os.Looper.loop(Looper.java:135)
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.app.ActivityThread.main(ActivityThread.java:5221)
01-31 23:48:22.309: E/AndroidRuntime(2629): at java.lang.reflect.Method.invoke(Native Method)
01-31 23:48:22.309: E/AndroidRuntime(2629): at java.lang.reflect.Method.invoke(Method.java:372)
01-31 23:48:22.309: E/AndroidRuntime(2629): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
01-31 23:48:22.309: E/AndroidRuntime(2629): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
01-31 23:48:22.309: E/AndroidRuntime(2629): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
01-31 23:48:22.309: E/AndroidRuntime(2629): at com.mity.medicalinformationbd.DatabaseHandler.Getmedicine(DatabaseHandler.java:122)
01-31 23:48:22.309: E/AndroidRuntime(2629): at com.mity.medicalinformationbd.DatabaseHandler.get(DatabaseHandler.java:113)
01-31 23:48:22.309: E/AndroidRuntime(2629): at com.mity.medicalinformationbd.Detailinformation.onCreate(Detailinformation.java:56)
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.app.Activity.performCreate(Activity.java:5933)
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
01-31 23:48:22.309: E/AndroidRuntime(2629): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
01-31 23:48:22.309: E/AndroidRuntime(2629): ... 10 more
01-31 23:48:22.370: I/art(2629): Background sticky concurrent mark sweep GC freed 2136(154KB) AllocSpace objects, 0(0B) LOS objects, 24% free, 692KB/923KB, paused 1.806ms total 213.658ms
01-31 23:48:25.600: I/Process(2629): Sending signal. PID: 2629 SIG: 9

Delphi SQlite login procedure crash

been trying to figure out why the following login authentication procedure doesn't work. I have a simple database table holding pupilID and password (in tblPupil) It seems to connect ok upon compilation i.e. that is procedure Connection, but when i run procedure Login...the program seems to crash. In fact, i get no error messages which could illuminate me further! Could this be a database driver problem? (Using Delphi7, SQLite Database with DevartSQLiteDirect driver)



Procedure TForm1.Connection;
begin
SQLConnection1.Params.Add('Database=C:\SQLite\PupilDatabase');
try
// Establish the connection.
SQLConnection1.Connected := true;
label4.Caption := 'OK!';
except
on E: EDatabaseError do
ShowMessage('Exception raised with message' + E.Message);
end;
end;

Procedure TForm1.UserLogin;
var QueryPass : string;
Lcount : String;
cont : boolean;
begin
cont := false;
if InputID.Text = '' then
ShowMessage('Invalid Pupil ID')
else begin
cont := True;
While cont = True do
begin
// A random query
QueryPass := 'SELECT password FROM TblPupil Where pupilID = +InputID.Text+';';
try
// Assign the query to the object SQLQuery1.
SQLQuery1.SQL.Text := QueryPass;
SQLQuery1.open;
except
on E: Exception do
ShowMessage('Exception raised with message: ' + E.Message);
end;
SQLQuery1.First;
Lcount := SQLQuery1.FieldValues['password'];
if Lcount = InputPass.text then
begin
Form1.Hide;
Form16.show;
end
else
begin
ShowMessage('Wrong');
cont := false;
end;
Form1.Hide;
Form16.show;
end;
end;
end;

Node.js and SQLite3

I am want to create web server that will return data for my mobile app. I use Node.js for server and SQLite3 for database. I created method that must return data from sql, but I don't know how to do it correctly. As I know all methods from SQLite lib are async so I have no idea how to do sync request for DB. I tried this way:



app.get('/getAllLeagues',function (req, res) {
console.log("get")
var obj = db.all("SELECT name FROM Leagues")
})


But seems that obj is still the same as db object


How to create a dynamic listview with data from SQLite?

I want to program simple organizer with Notes. I have a SQLite database with some data as shown below:



_id | time | date | text
1 | 9:45 | 12.01| blabla
2 | 21:01| 13.01| albalb
...| ... | ... | ...


Also I have a class Note:



public class Note {
private int id;
private String time;
private String date;
private String text;
public Note(final int id, final String time, final String date, final String text){
setId(id);
setTime(time);
setDate(date);
setText(text);
}
public int getId(){
return id;
}
public String getTime(){
return time;
}
public String getDate(){
return date;
}
public String getText(){
return text;
}

void setId(final int id){
this.id = id;
}
void setTime(final String time){
this.time = time;
}
void setDate(final String date){
this.date = date;
}
void setText(final String text){
this.text = text;
}
}


And NotesManager:



public class NotesManager {
private static final String TABLE_NAME = "NotesListTable";
private static final String KEY_TIME = "time";
private static final String KEY_DATE = "date";
private static final String KEY_TEXT = "text";
private static final String KEY_ID = "_id";

private final SQLiteDatabase db;
public NotesManager(SQLiteDatabase db){
this.db = db;
}
public void save(final ContentValues cv){
db.insert(TABLE_NAME, null, cv);
}
public void delete(final int id){
db.delete(TABLE_NAME, KEY_ID + "=" + id, null);
}
public Note getNoteById(final int id){
Cursor mCursor = db.query(TABLE_NAME, null, KEY_ID + "=" + id, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return new Note(mCursor.getInt(mCursor.getColumnIndex(KEY_ID)),
mCursor.getString(mCursor.getColumnIndex(KEY_TIME)),
mCursor.getString(mCursor.getColumnIndex(KEY_DATE)),
mCursor.getString(mCursor.getColumnIndex(KEY_TEXT)));
}
public Cursor getAllDataFromDB(){
return db.query(TABLE_NAME, null, null, null, null, null, null);
}
public String[] getKeysArray(){
return new String[] {KEY_ID, KEY_TIME, KEY_DATE, KEY_TEXT};
}
}


I have a fragment with ListView: It has been generated by Android Studio, nut I made some changes, added SimpleCursorAdapter



public class NotesListFragment extends Fragment implements AbsListView.OnItemClickListener {

private static final String ARG_SECTION_NUMBER = "section_number";
private int mSectionNumber = 0;
private OnFragmentInteractionListener mListener;
private AbsListView mListView;
private SimpleCursorAdapter scAdapter;
private Cursor cursor;
ImageButton deleteButton;
NotesManager notesManager = new NotesManager(OrganizerApp.db);

public static NoesListFragment newInstance(int param1) {
NoesListFragment fragment = new NotesListFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, param1);
fragment.setArguments(args);
return fragment;
}

public NotesListFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mSectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
}
cursor = NotesManager.getAllDataFromDB();
//TODO: startManagingCursor(cursor)

//mAdapter = new ArrayAdapter<NotesListContent.NotesItem>(getActivity(),
// android.R.layout.simple_list_item_1, android.R.id.text1, NotesListContent.ITEMS);
scAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.note_list_rowlayout,
cursor,
notesManager.getKeysArray(),
new int[]{R.id.note_list_rowlayout_item1,
R.id.note_list_rowlayout_item2,
R.id.note_list_rowlayout_item3,
R.id.note_list_rowlayout_item4 });
deleteButton = (ImageButton) getView().
findViewById(R.id.note_list_rowlayout_deleteButton);
deleteButton.setOnClickListener(onClickDeleteButton);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_note, container, false);

// Set the adapter
mListView = (AbsListView) view.findViewById(android.R.id.list);
mListView.setAdapter(scAdapter);
//((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);

// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);

return view;
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mSectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
mListener = (OnFragmentInteractionListener) activity;
((MainActivity) activity).onSectionAttached(mSectionNumber);
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}


@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
// mListener.onFragmentInteraction(NotesListContent.ITEMS.get(position).id);
}
}

public void setEmptyText(CharSequence emptyText) { // If list is empty.
View emptyView = mListView.getEmptyView();

if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}

public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}

View.OnClickListener onClickDeleteButton = new View.OnClickListener() {
@Override
public void onClick(View v) {

}
};

}


Android studio also generated NotesListContent.java:



public class NotesListContent {

public static List<Note> ITEMS = new ArrayList<Note>();

//public static Map<String, Note> ITEM_MAP = new HashMap<String, Note>();

private static void addItem(Note item) {
ITEMS.add(item);
//ITEM_MAP.put(item.id, item);
}



/**
* A dummy item representing a piece of content.

public static class NoteItem {
public String id;
public String content;

public NoteItem(String id, String content) {
this.id = id;
this.content = content;
}

@Override
public String toString() {
return content;
}
}*/
}


So my solution works, but I think that it is bad. 1. For what I need a NotesListContent.java? How can I use it? 2. How can I use ListView without deprecated simpleCursorAdapter? 3. How to delete and add items without refresh all ListView? 4. Especially this code seems to be very unconvenient:



scAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.note_list_rowlayout,
cursor,
notesManager.getKeysArray(),
new int[]{R.id.note_list_rowlayout_item1,
R.id.note_list_rowlayout_item2,
R.id.note_list_rowlayout_item3,
R.id.note_list_rowlayout_item4 });

android sqlite doesn' support arabic

I have a sqlite database on my android app and it works fine, but when I try to insert arabic language it shows squares shape like this [] [] [] [] [] I inserted the data on database using a txt file in the assets folder like this:



INSERT INTO user_table (id, name) VALUES (1,'احمد');


I tried saving the txt file in utf8 coding but the app crashes.


How to export data from GAE Datastore to sqlite or sql statement?

I have a table in my Datastore and i need to convertit in sql statement to put in my Sqlite Android DB. Are there any solutions? I surfed the web, but i couldn't found a solution.


Thanks


SQLite as an Elmah source

I'm trying to get SQLite working with Elmah, but it keeps complaining about the attached version.


I've read numerous blogs on the topic but none of the recommended approaches has worked for me thus far.


Elmah.MVC has been installed, as the latest version found in NUGET, then installed the SQLite core framework has been attached, as per the current version in NUGET as well.


From what I can gather, it's in the way that NUGET appends the SQLite entries into the web.config file, but I cannot see a difference.


My packages.config (entries left out for readability):



<?xml version="1.0" encoding="utf-8"?>
<packages>
.....
<package id="elmah.corelibrary" version="1.2.1" targetFramework="net45" />
<package id="Elmah.MVC" version="2.1.1" targetFramework="net45" />
<package id="System.Data.SQLite" version="1.0.94.1" targetFramework="net45" />
<package id="System.Data.SQLite.Core" version="1.0.94.0" targetFramework="net45" />
<package id="System.Data.SQLite.EF6" version="1.0.94.0" targetFramework="net45" />
<package id="System.Data.SQLite.Linq" version="1.0.94.1" targetFramework="net45" />
.....
</packages>


Elmah has been implemented as a View / Controller rather than the standard .axd version that comes predefined, so when I browse http://localhost:3812/Elmah/ the following stack trace gets thrown:



Could not load file or assembly 'System.Data.SQLite, Version=1.0.61.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'System.Data.SQLite, Version=1.0.61.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)


And Pre-bind state information



=== Pre-bind state information ===
LOG: DisplayName = System.Data.SQLite, Version=1.0.61.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139
(Fully-specified)
LOG: Appbase = file:///C:/Users/Admin/Documents/Visual Studio 2015/Projects/TestMvc/Site/TestMvc.WebSite/
LOG: Initial PrivatePath = C:\Users\Admin\Documents\Visual Studio 2015\Projects\TestMvc\Site\TestMvc.WebSite\bin
Calling assembly : Elmah, Version=1.2.14318.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\Admin\Documents\Visual Studio 2015\Projects\TestMvc\Site\TestMvc\web.config
LOG: Using host configuration file: C:\Users\Admin\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: System.Data.SQLite, Version=1.0.61.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139
LOG: Attempting download of new URL file:///C:/Users/Admin/AppData/Local/Temp/Temporary ASP.NET Files/root/65395abf/3be698df/System.Data.SQLite.DLL.
LOG: Attempting download of new URL file:///C:/Users/Admin/AppData/Local/Temp/Temporary ASP.NET Files/root/65395abf/3be698df/System.Data.SQLite/System.Data.SQLite.DLL.
LOG: Attempting download of new URL file:///C:/Users/Admin/Documents/Visual Studio 2015/Projects/TestMvc\Site\TestMvc/bin/System.Data.SQLite.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Build Number
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.


I do not believe this to be an issue with Visual Studio 2015 CTP, nor with the latest version of the both Elmah.MVC or SQLite or the build attributes (Any CPU vs x86/x64) as SQLite works fine when doing basic CRUD against the database (not shown in this question).


Any assistance would be greatly appreciated.


Why can't my image be inserted to the database? It only shows a couple of text in the field of the table

I have a program that will that a picture from the camera and save it to the database but the data shows up when I browse the blob is "[B@22e1ae38" or random letters and numbers and I don't know what is the error.


This is my OnCreate function





@Override
protected void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.addstudentsform);
db=openOrCreateDatabase("ClassManager",MODE_WORLD_READABLE, null);

viewImage = (ImageView)findViewById(R.id.CamPicture);
viewImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "StudPic.png");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}

});
}



This is my onActivity Results:





@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
if(resultCode==RESULT_OK)
{
if (requestCode == 1)
{

File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles())
{
if (temp.getName().equals("StudPic.png"))
{
f = temp;
break;
}
}

try
{
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
viewImage.setImageBitmap(bitmap);

String path = Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "Default";
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".png");

try
{

ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
StudImage = bos.toByteArray();
f.delete();

}

catch (Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}

try
{
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, outFile);
outFile.flush();
outFile.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}

catch (Exception e)
{
e.printStackTrace();
}

}
}
}



This is the my CreateScreen where I insert the picture in the database as StudPic which is a blob sql type:





public void CreateScreen (View view)
{

EditText FirstNameText = (EditText)findViewById(R.id.FirstNameText);
EditText StudentIDText = (EditText)findViewById(R.id.StudentIDText);
EditText LastNameText = (EditText)findViewById(R.id.LastNameText);
EditText ContactNumberText = (EditText)findViewById(R.id.ContactNumberText);
EditText EmailAddressText = (EditText)findViewById(R.id.EmailAddressText);

StudentID = Integer.parseInt(StudentIDText.getText().toString());
FirstName = FirstNameText.getText().toString();
LastName = LastNameText.getText().toString();
ContactNumber = Integer.parseInt(ContactNumberText.getText().toString());
EmailAddress = EmailAddressText.getText().toString();

db.execSQL("INSERT INTO MasterStudents (StudPic, StudentID, FirstName, LastName, ContactNumber, EmailAddress) " +
"VALUES ('" + StudImage + "','" + StudentID + "','" + FirstName + "','" + LastName + "','" + ContactNumber + "','" + EmailAddress + "');");

Toast toast = Toast.makeText(getApplicationContext(), "Student Added", Toast.LENGTH_SHORT);
toast.show();
finish();

}



vendredi 30 janvier 2015

Android: Get random record in SQLite

I fetch records in my SQLite database like this.



spellId = extra.getString("spellId");
DBase db = new DBase(this);
db.open();
String[] data = db.getRecord(Integer.parseInt(spellId));
db.close();


And I'm wondering if I can get random data like this without using raw queries and cursor? Help, anyone? Thanks in advance! :)


Best way to fetch data from SQLite database in Android

I'm making an application which uses weather API so that when person enters zipcode, it shows the detailed weather conditions of a particular area. If my zipcode is valid, then I save my zipcode so that when I start my application next time, I have list of all zipcodes which I saved(All zipcodes populate in listview). I use SQLite database to save my zipcode


Presently, I'm using AsyncTask to query my database, get all the rows and show it in listview. But I feel that it is not the best way to query the database and obtain result. Can any one tell me the best and most efficient strategy which should be used to query SQLite database and show result in listview. I think I need to use loaders.


Thanks


How to restore database from backup agent saved path android

I am using this code for saving database, using BackupAgent class



public class MyBackupAgent extends BackupAgentHelper {

String DATABASE_NAME = "mydb";
String DATABASE_FILE_NAME = "mydb.db";
@Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);

FileBackupHelper dbs = new FileBackupHelper(this, DATABASE_FILE_NAME);
addHelper("dbs", dbs);
}

@Override
public File getFilesDir() {
File path = getDatabasePath(DATABASE_FILE_NAME);
return path.getParentFile();
}


}


Now after that i want to know how to restore database? Please help me about this, Thanks in advance


ExpendableListView send Bundle OnChildClickListener

I try to send bundle on My ExpendableListView using OnChildClickListener. I try to use it like I use setOnItemClickListener. But it always crashed. Can any one lend me a help? Because I am new on Android Developer.


this is may main class



package com.skripsi.olfi.kamusbahasasumbawa;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.SearchView;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends ActionBarActivity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener{

private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<Kelompok> kelompokList = new ArrayList<Kelompok>();
private ArrayList<Kata> kataSumList, kataIndList;
private ArrayAdapter<Kata> adapter;
private DatabaseManager dbManager;

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

dbManager = DatabaseManager.getInstance(this);

SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) findViewById(R.id.search);
search.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.expandableList);



// display the list
displayList();
// expand all Groups
expandAll();


}




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

// method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++) {
myList.expandGroup(i);
}
}

// method to expand all groups
private void displayList() {

// display the list
loadSomeData();


// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(MainActivity.this, kelompokList);
// attach the adapter to the list
myList.setAdapter(listAdapter);



myList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Bundle b = new Bundle();
b.putString("id", String.valueOf(adapter.getItem(groupPosition).getId()));
b.putString("kata", adapter.getItem(groupPosition).getKata());
b.putString("arti", adapter.getItem(groupPosition).getArti());
b.putString("kalimat", adapter.getItem(groupPosition).getKalimat());
Intent intent = new Intent(MainActivity.this, LihatTerjemahan.class);
intent.putExtras(b);
startActivity(intent);
return false;
}
});


}

private void loadSomeData() {

kataSumList = dbManager.getAllSum();
kataIndList = dbManager.getAllInd();

Kelompok kelompok = new Kelompok("Bahasa Sumbawa", kataSumList);
kelompokList.add(kelompok);
kelompok = new Kelompok("Bahasa Indonesia", kataIndList);
kelompokList.add(kelompok);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@Override
public boolean onClose() {
listAdapter.filterData("");
expandAll();
return false;
}

@Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
listAdapter.filterData(query);
expandAll();
return false;
}

@Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
listAdapter.filterData(newText);
expandAll();
return false;
}


}


this is my database class



package com.skripsi.olfi.kamusbahasasumbawa;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

import java.util.ArrayList;

/**
* Created by Olfi on 30/01/2015.
*/
public class DatabaseManager extends SQLiteAssetHelper {

private static final String DB_NAME = "db_kamus_android";
private static final int DB_VER = 1;



private static DatabaseManager dbInstance;
private static SQLiteDatabase db;

DatabaseManager(Context context){
super(context, DB_NAME, null, DB_VER);
}

public static DatabaseManager getInstance(Context context){
if (dbInstance ==null){
dbInstance = new DatabaseManager(context);
db = dbInstance.getWritableDatabase();
}
return dbInstance;
}

@Override
public synchronized void close(){
super.close();
if (dbInstance!=null){
dbInstance.close();
}
}

public ArrayList<Kata> getAllSum(){
ArrayList<Kata> listSumbawa = new ArrayList<Kata>();
Cursor cursor = db.rawQuery("SELECT id, sumbawa as kata , arti_indonesia as arti, kalimat, favorit FROM kamus", null);
if (cursor!=null) {
if (cursor.moveToFirst()) do {
Kata kamus = new Kata();
kamus.setId(Integer.parseInt(cursor.getString(0)));
kamus.setKata(cursor.getString(1));
kamus.setArti(cursor.getString(2));
kamus.setKalimat(cursor.getString(3));
kamus.setFav(Integer.parseInt(cursor.getString(4)));
listSumbawa.add(kamus);
} while (cursor.moveToNext());
}
return listSumbawa;
}

public ArrayList<Kata> getAllInd(){
ArrayList<Kata> listIndonesia = new ArrayList<Kata>();
Cursor cursor = db.rawQuery("SELECT id, indonesia as kata , arti_sumbawa as arti, kalimat, favorit_indonesia FROM kamus", null);
if (cursor!=null) {
if (cursor.moveToFirst()) do {
Kata kamus = new Kata();
kamus.setId(Integer.parseInt(cursor.getString(0)));
kamus.setKata(cursor.getString(1));
kamus.setArti(cursor.getString(2));
kamus.setKalimat(cursor.getString(3));
kamus.setFav(Integer.parseInt(cursor.getString(4)));
listIndonesia.add(kamus);
} while (cursor.moveToNext());
}
return listIndonesia;
}


}


this is my ListAdapterClass:



package com.skripsi.olfi.kamusbahasasumbawa;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;

public class MyListAdapter extends BaseExpandableListAdapter {

private Context context;
private ArrayList<Kelompok> kelompokList;
private ArrayList<Kelompok> originalList;

public MyListAdapter(Context context, ArrayList<Kelompok> continentList) {
this.context = context;
this.kelompokList = new ArrayList<Kelompok>();
this.kelompokList.addAll(continentList);
this.originalList = new ArrayList<Kelompok>();
this.originalList.addAll(continentList);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
ArrayList<Kata> kataList = kelompokList.get(groupPosition).getListKata();
return kataList.get(childPosition);
}

@Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}

@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub

Kata kata = (Kata) getChild(groupPosition, childPosition);
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child_row, null);
}

TextView txtkata = (TextView) convertView.findViewById(R.id.kata);
TextView arti = (TextView) convertView.findViewById(R.id.arti);
TextView kalimat = (TextView) convertView.findViewById(R.id.kalimat);
txtkata.setText(kata.getKata().trim());
arti.setText(kata.getArti().trim());
kalimat.setText((kata.getKalimat().trim()));

return convertView;
}

@Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
ArrayList<Kata> kataList = kelompokList.get(groupPosition).getListKata();
return kataList.size();
}

@Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return kelompokList.get(groupPosition);
}

@Override
public int getGroupCount() {
// TODO Auto-generated method stub
return kelompokList.size();
}

@Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Kelompok kelompok = (Kelompok) getGroup(groupPosition);
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.group_row, null);
}

TextView heading = (TextView) convertView.findViewById(R.id.heading);
heading.setText(kelompok.getKlp().trim());

return convertView;
}

@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}

public void filterData(String query)
{
query = query.toLowerCase();
Log.v("MyListAdapter", String.valueOf(kelompokList.size()));
kelompokList.clear();

if(query.isEmpty())
{
kelompokList.addAll(originalList);
} else {
for(Kelompok kelompok: originalList)
{
ArrayList<Kata> kataList = kelompok.getListKata();
ArrayList<Kata> newList = new ArrayList<Kata>();
for(Kata kata: kataList)
{
if(kata.getKata().toLowerCase().contains(query) || kata.getArti().toLowerCase().contains(query) || kata.getKalimat().toLowerCase().contains(query))
{
newList.add(kata);
}
}
if(newList.size() > 0)
{
Kelompok nKelompok = new Kelompok(kelompok.getKlp(), newList);
kelompokList.add(nKelompok);
}
}
}

Log.v("MyListAdapter", String.valueOf(kelompokList.size()));
notifyDataSetChanged();
}
}


this is my destination class:



package com.skripsi.olfi.kamusbahasasumbawa;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class LihatTerjemahan extends ActionBarActivity {
private TextView teksKata, teksArti, teksKalimat;
private DatabaseManager dbManager;
int id_kata,is_favorit;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lihat_terjemahan);
teksKata = (TextView) findViewById(R.id.teksKata);
teksArti = (TextView) findViewById(R.id.teksArti);
teksKalimat = (TextView) findViewById(R.id.teksKalimat);
dbManager = DatabaseManager.getInstance(this);

Bundle b = getIntent().getExtras();
if (b != null){
id_kata = Integer.valueOf(b.getString("id"));
teksKata.setText(b.getString("kata"));
teksArti.setText(b.getString("arti"));
teksKalimat.setText(b.getString("kalimat"));
/*
is_favorit=dbManager.getFavorit(String.valueOf(id_kata));
if(st_favorit==1){
bfavor.setText("Hapus Favorite");
}else{
bfavor.setText("Tambah Favorite");

}
*/

}

}


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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Update trigger in SQL after salary of employee has been changed - this records it to another table

I have a table like this:



empid | name | salary
1 | Jack | 25000
2 | Mary | 30000
3 | Jane | 40000
4 | Lary | 50000


I want to create a sql trigger that records the salary update into another seperate table accumlating whatever increase or decrease in the salary column of the employee table. Say if there was a single update for one specific salary column then it records this change however if there were mutiple changes to a salary column then it records all of it together into one column as well. All of this is recorded into a seperate table.


Why do I get "InvalidOperationException: No current row" with this code?

I'm trying to retrieve a row from a table using the GetInventoryRecordForUPC() method below. I can retrieve the row fine in LINQPad by entering "SELECT invName, line_id, ref_no, upc_code, description, department, vendor_id, upc_pack_size, pack_size, id, unit_cost, unit_list, unit_qty, new_item FROM Inventory WHERE upc_code = '76145513'" (the value passed in "upc" is "76145513") in my test scenario.


But when the method below runs, the app crashes, and the log file contains:



System.InvalidOperationException: No current row
at System.Data.SQLite.SQLiteDataReader.CheckValidRow()
at System.Data.SQLite.SQLiteDataReader.VerifyType(Int32 i, DbType typ)
at System.Data.SQLite.SQLiteDataReader.GetString(Int32 i)
at HHS.TestHHSDBUtils.GetInventoryRecordForUPC(String upc)


The method has the table's create statement commented out to show the names and data types of the columns.



public Inventory GetInventoryRecordForUPC(String upc)
{
ExceptionLoggingService.Instance.WriteLog("Reached
TestHHSDBUtils.GetInventoryRecordForUPC");
Inventory inv = new Inventory();
using (SQLiteConnection conn = new
SQLiteConnection(HHSUtils.GetDBConnection()))
{
conn.Open();
const string qry = "SELECT invName, line_id, ref_no, upc_code,
description, department, vendor_id, upc_pack_size, pack_size, id, unit_cost,
unit_list, unit_qty, new_item FROM Inventory WHERE upc_code = @UPCCode";
//CREATE TABLE Inventory(invName TEXT, line_id INTEGER, ref_no
TEXT, upc_code TEXT, description TEXT, department REAL, vendor_id TEXT,
upc_pack_size INTEGER, pack_size INTEGER, id TEXT, unit_cost REAL, unit_list
REAL, unit_qty REAL, new_item INTEGER, siteNum TEXT, Created TEXT, Modified
TEXT)";

using (SQLiteCommand cmd = new SQLiteCommand(qry, conn))
{
cmd.Parameters.Add(new SQLiteParameter("UPCCode", upc));
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
inv.invName = rdr.GetString(0);
inv.line_id = rdr.GetInt32(1);
inv.ref_no = rdr.GetString(2);
inv.upc_code = rdr.GetString(3);
inv.description = rdr.GetString(4);
inv.department = rdr.GetFloat(5);
inv.vendor_id = rdr.GetString(6);
inv.upc_pack_size = rdr.GetInt32(7);
inv.pack_size = rdr.GetInt32(8);
inv.id = rdr.GetString(9);
inv.unit_cost = rdr.GetFloat(10);
inv.unit_list = rdr.GetFloat(11);
inv.unit_qty = rdr.GetFloat(12);
inv.new_item = rdr.GetInt32(13);
}
}
return inv;
}
}


The Inventory class is declared this way:



public class Inventory
{
public String invName { get; set; }
public int line_id { get; set; }
public String ref_no { get; set; }
public String upc_code { get; set; }
public String description { get; set; }
public double department { get; set; }
public String vendor_id { get; set; }
public int upc_pack_size { get; set; }
public int pack_size { get; set; }
public String id { get; set; } // id, here?
public double unit_cost { get; set; } // REAL in SQLite
public double unit_list { get; set; } // REAL in SQLite
public double unit_qty { get; set; } // REAL in SQLite
public int new_item { get; set; }
// Create Table code adds TEXT siteNum, Created and Modified columns
}


Why in John Steinbeck's pet poodle would this cause a "InvalidOperationException: No current row"?!?


DataReader never enters Read()

Using Prism 5 (if that matters), I'm trying to read a table into a class but when I run the program the SQLiteDataReader Read() is never executed (or so I think since its Breakpoint is never hit).


Within my solution I have a ModuleA with a ViewModel class with a method that will update Bindings in the View:



public void ShowGeneral()
{
Personnel personnel = new Personnel();
personnel = PersonnelDAL.GetPersonnelRecord(Human);
pName = personnel.PersonName + " Esquire";
pAge = personnel.PersonAge;
}


PersonnelDAL.GetPersonnelRecord() is in a seperate Module. (This Module has References to SQLite).



public static Personnel GetPersonnelRecord(int id)
{
SQLiteConnection myDBconnection = new SQLiteConnection(SQLiteDAL.dbConnectionString);
Personnel personnel = new Personnel();

try
{
myDBconnection.Open();
string strQuery = "SELECT Person.*, Personnel.*," +
" FROM Person, Personnel WHERE Person.PersonPersonnelID = Personnel.PersonnelID AND Person.PersonID = @PersonID";
SQLiteCommand query = new SQLiteCommand(strQuery, myDBconnection);
query.Parameters.Add(new SQLiteParameter("@PersonID") { Value = id });
// A Breakpoint set here is hit
SQLiteDataReader myReader = query.ExecuteReader();

// A Breakpoint set here is never hit
while (myReader.Read())
{
personnel.PersonID = myReader.GetInt32(0);
personnel.PersonName = myReader.GetInt32(1);
personnel.PersonAge = myReader.GetInt32(3);

// etc


As a result the View displays no value for Age and only Esquire for name.


Why is myreader.Read() never executed?


TypeError: Cannot read property 'openDatabase' of undefined

I want to work with sqlite with cordova framework for the first time. As I've read on a tutorial I should use ngcordova like this:



var db = null;
app.controller('mainCtrl', function ($scope, $ionicSideMenuDelegate) {
$scope.toggleLeft = function () {
$ionicSideMenuDelegate.toggleLeft();
}
$scope.toggleRight = function () {
$ionicSideMenuDelegate.toggleRight();
}
})
.controller('home_ctrl', function ($scope, $cordovaSQLite) {
db = $cordovaSQLite.openDB({name: "my.db"});
//db = $window.opendb({name: "my.db"});
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS people(id integer primary key, firstname text, lastname text)")
})
;


When I run this code an error says:



TypeError: Cannot read property 'openDatabase' of undefined


In some articles like this: How do I use the ngCordova sqlite service and the Cordova-SQLitePlugin with Ionic Framework? recommends to use commands like this: ionic start myApp sidemenu

I don't know what is it, I just use cordova command like: cordova run android or cordova create my_project

What should I do to run my create a table from my cordova project?


Python: How can I create a "global object"?

I have a problem with the following code. As you can see I set up an sqlite3 database in the function setup_session(), though when I try to run it it throws an exception because the object cursor which I created in setup_session() is only available inside the function.



import sqlite3

def setup_session():
db = sqlite3.connect("data.db")
cursor = db.cursor()


setup_session()

cursor.execute("CREATE TABLE subjects (subject text)")


How can I change it so that cursor is also available from outside the function?


android application with huge database

Let me explain how my application is supposed to work:


Application will ship with a sqlite database in its assets folder which will be copied into databases folder later and it has some content in it(categories, sub categories, products and news) which they all have image. Then after download user can update the content via internet and the application store the new content in database so the application can perform offline.


So my question is, after a while this content will increase in size, is it gonna cause my application to crash? Lets say I release the application with 1 MB database and after 2 years of work the database size goes up around 120 MB. Is it gonna make the application to crash?


Also the other concern is that currently I'm storing the images in database and I load'em from there. Is it a good approach? Because I don't want user to be able to clear the cache or delete the images because later on updating the content it has to download those deleted images again and it will consume traffic imo.


please remember that the Application should be able to load content offline


What are the steps of making an Android app for streaming episodes of a podcast's back catalogue?

As a programming beginner, I'm looking for a project to expand my skills and I would really like to program an Android app for my favorite podcast. I'd like it to have all the past episodes available for streaming. This way, the user has access to the entire catalogue without having to download all the episodes and take up a lot of storage space on their device.


I'm guessing the process involves scraping an RSS feed and importing the entries into an SQL database... I'd really appreciate a high-level overview so I can get the pseudocode down. If a tutorial exists online, I'd be over the moon! Thanks for reading and going easy on a beginner.


Building a distributed bittorrent-SQL database

I have an idea for a distributed SQL database using the bittorrent protocol for pulling and writing its data.


For the sake of argument, lets say this is a messaging application, where thousands of users run a program that contains a messaging window, and an input box for them to write messages.


Each message written does a INSERT to their own sqlite DB.


How it could be done



  • Download a .torrent file that essentially contains the schema/DDL for creating the DB, and create it on the local machines.

  • Anytime a 'write' action is done(like a user wants to send a message), that INSERT line(which is kinda like a delta) does two things:

    • Writes to their own internal DB

    • Creates a .torrent file out of that line, named something like, messaging-[my-ip]-[UTC_timestamp].torrent, and posts it to a tracker



  • Everyone running the app is continually scanning the tracker for files of this certain name(and possibly after a certain date), downloads the .torrent and hosts it, and runs the INSERT commands on their local DB.


What you'd then have is a ton of delta-files, all P2P hosted for redundancy, updating local .sqlite DBs on a lot of machines.


Some issues I'm having




  • How do I scrape for torrents of a certain file-name? I've read through the http bittorrent tracker spec, but you seem to only be able to query files based on their specific info name. Is there no way to query for a group of files, or based on file name?




  • How do I download a .torrent file from a tracker? Will I need to host the files on a centralized server, or can I use the tracker to download the files in some way? And if I have to host the .torrent files myself...



    • Wouldn't this defeat the purpose of a decentralized DB, since if my website goes down, the application would stop getting updates?




Thanks for the help in advance.


Using SQLite for F# on iOS

I'm trying to use SQLite with F# on iOS device.


I tried to use SQLProvider. It worked fine with Mac app development, but I got build error when trying to use it on iOS device. It works fine with the simulation mode, but even in that case, I can't use the SQLClient functions so I had to run in demo mode. I posted a question on this issue (Using F# FSharp.Data.SqlProvider on iOS).


How can I use SQLite on iOS device with F#?



  • How to use SQLProvider on iOS device with F#?

  • I see that the C# Tasky app uses ADO.NET, then, how to use ADO.NET on F#?

  • What other options are available?


Display taken image from camera in image view and add it to database - Android Studio

I created a form that will save information to my database including an image. I have inserted the image in a Imageview to view it after taking the picture via camera. How do I insert the image retrived by the imageview to my SQL Query?


This is my onCreate Function:





String FirstName, LastName, EmailAddress;
Integer StudentID, ContactNumber;
SQLiteDatabase db;
ImageView viewImage, StudPic;

@Override
protected void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.addstudentsform);
db=openOrCreateDatabase("ClassManager",MODE_WORLD_READABLE, null);

db.execSQL("CREATE TABLE IF NOT EXISTS MasterStudents (StudPic BLOB, StudentID INTEGER NOT NULL UNIQUE, FirstName VARCHAR," +
"LastName VARCHAR, ContactNumber INTEGER, EmailAddress VARCHAR);");

viewImage = (ImageView)findViewById(R.id.CamPicture);
viewImage.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "StudPic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}

});
}



This is onActivityResult Function that previews the image taken from the camera:





@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
if(resultCode==RESULT_OK)
{
if (requestCode == 1)
{
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("StudPic.jpg")) {
f = temp;
break;
}
}

try
{
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
viewImage.setImageBitmap(bitmap);

String path = Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "Default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");

try
{
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}

catch (Exception e)
{
e.printStackTrace();
}
}
}
}



This is the CreateScreen Function that inserts the text in the database. How do I do it with the Image in the Image view?





public void CreateScreen (View view)
{

EditText FirstNameText = (EditText)findViewById(R.id.FirstNameText);
EditText StudentIDText = (EditText)findViewById(R.id.StudentIDText);
EditText LastNameText = (EditText)findViewById(R.id.LastNameText);
EditText ContactNumberText = (EditText)findViewById(R.id.ContactNumberText);
EditText EmailAddressText = (EditText)findViewById(R.id.EmailAddressText);

StudentID = Integer.parseInt(StudentIDText.getText().toString());
FirstName = FirstNameText.getText().toString();
LastName = LastNameText.getText().toString();
ContactNumber = Integer.parseInt(ContactNumberText.getText().toString());
EmailAddress = EmailAddressText.getText().toString();

db.execSQL("INSERT INTO MasterStudents (StudPic, StudentID, FirstName, LastName, ContactNumber, EmailAddress) " +
"VALUES ('" + StudentID + "','" + FirstName + "','" + LastName + "','" + ContactNumber + "','" + EmailAddress + "');");

Toast toast = Toast.makeText(getApplicationContext(), "Student Added", Toast.LENGTH_SHORT);
toast.show();
finish();

}



NOTE: The StudPic field name is the BLOB in the sql query that i want to insert the image from the imageView in the onActivityResult Function


Any help that is explained with //comments and clarity is highly appreciated