dimanche 1 mars 2015

Whats the easiest way to empty and save a Core Data Table in Swift?

So I have a entity, which I am treating as a simple Database Table in iOS8 XCODE and SWIFT. I want to delete every entry in the table. Permanently. So when I start up the app again they do not reload.This is my code.



func deleteAllItems(){
println("All Items are being DELETED")
var count:Int = 0

while (HBCContactList.count > 0){
let AppDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let MOContext: NSManagedObjectContext = AppDel.managedObjectContext!
MOContext.deleteObject(HBCContactList[0] as NSManagedObject)
HBCContactList.removeAtIndex(0)
var error:NSError? = nil
if !MOContext.save(&error){
abort()
}
tableView.reloadData()
}


It looks like it loads. When its finished on the screen there is nothing in UITableView and all is good. However If I write code to return me the entity via a fetch statement and do a count on the number of records. It still says there is over 150 results.


Thoughts? Am I even in the right ball park?


Confusion regarding wrapping my varargs argument

When compiling my class which is a table in my ActiveAndroid ORM database I get this error:


Warning:(33, 50) non-varargs call of varargs method with inexact argument type for last parameter; cast to Object for a varargs call cast to Object[] for a non-varargs call and to suppress this warning


Here is the method which this refers to:



public static ChildMedicine getChildMedicine(Child child, Medicine medicine)
{
return new Select()
.from(ChildMedicine.class)
.where("Child = ? AND Medicine = ?", new Long[]{child.getId(), medicine.getId()})
.executeSingle();
}


I want to return all the ChildMedicine objects from my ActiveAndroid ORM database table where the Child column equals the Long Id for the passed in child argument and the Medicine column equals the Long Id for the passed in medicine argument.


I am suggested to wrap the wrap vararg arguments with explicit array creation like this:



public static ChildMedicine getChildMedicine(Child child, Medicine medicine)
{
return new Select()
.from(ChildMedicine.class)
.where("Child = ? AND Medicine = ?", new Object[]{new Long[]{child.getId(), medicine.getId()}})
.executeSingle();
}


However, will this not cause my Select() method not to work correctly as I now have an array of two Long arrays instead of a Long array of two Longs in the where part of the method?


I am a bit confused!


Any help is much appreciated...


Thanks, Sam


erlang-sqlite3 sqlite3:table_info error

I tried to extract table info from sqlite database using sqlite3:table_info/2 function and got an error message.



{ok,Pid} = sqlite3:open(db3).

Sql = <<"CREATE TABLE test (
id INTEGER PRIMARY KEY,
ts TEXT default (timestamp('now')),
key TEXT,
val TEXT
);">>.
sqlite3:sql_exec(db3,Sql).


Check table list:



sqlite3:list_tables(db3).
[test]


Try to get table info:



sqlite3:table_info(db3,test).


And now error message:




`=ERROR REPORT==== 1-Mar-2015::19:37:46 ===
** Generic server db3 terminating
** Last message in was {table_info,test}
** When Server state == {state,#Port,
[{file,"../tmp/db3.sqlite"}],
{dict,0,16,16,8,80,48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],
[],[],[]},
{{[],[],[],[],[],[],[],[],[],[],[],[],[],
[],[],[]}}}}
** Reason for termination ==
** {function_clause,[{sqlite3,build_constraints,
[["INTEGER","PRIMARY","KEY"]],
[{file,"src/sqlite3.erl"},{line,1169}]},
{sqlite3,build_table_info,2,
[{file,"src/sqlite3.erl"},{line,1166}]},
{sqlite3,handle_call,3,
[{file,"src/sqlite3.erl"},{line,833}]},
{gen_server,try_handle_call,4,
[{file,"gen_server.erl"},{line,607}]},
{gen_server,handle_msg,5,
[{file,"gen_server.erl"},{line,639}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,237}]}]}
** exception exit: function_clause
in function sqlite3:build_constraints/1
called as sqlite3:build_constraints(["INTEGER","PRIMARY","KEY"])
in call from sqlite3:build_table_info/2 (src/sqlite3.erl, line 1166)
in call from sqlite3:handle_call/3 (src/sqlite3.erl, line 833)
in call from gen_server:try_handle_call/4 (gen_server.erl, line 607)
in call from gen_server:handle_msg/5 (gen_server.erl, line 639)
in call from proc_lib:init_p_do_apply/3 (proc_lib.erl, line 237)


Any ideas?


JSON Data In Database Work

Can anyone please guide me out how to work on JSON data insert,update & delete work. I have not that much of idea how to work on .


I have done only insert data when i am getting data from server,but how to update data by checking database & server,if data is present or not. Along with how to delete that particular data if the data is not in server.



for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.getJSONObject(i);
// Saajan databse

$id = c.getString("$id");
ID = c.getString("ID");
Name = c.getString("ContactUserName");
Service = c.getString("Service");
CreatedOn = c.getString("CreatedOn");

SimpleDateFormat inputFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat outputFormat = new SimpleDateFormat(
"dd MMM yyyy hh:mm a");
String sourceDateStr = outputFormat
.format(inputFormat.parse(CreatedOn));

Date sourceDate = outputFormat.parse(sourceDateStr);

Country = c.getString("Country");
CompanyName = c.getString("CompanyName");
AssignedTo = c.getString("AssignedTo");
ProfilePicUrl = c.getString("ProfilePicUrl");

sfadb.insertList($id, ID, Service, Name, CreatedOn,
CompanyName, Country, AssignedTo,
ProfilePicUrl);

timeSegments = CreatedOn.split("T");

String[] s1 = timeZoneOffset.split(":");

sourceTimeZoneOffset = "GMT" + s1[0] + s1[1];
TimeZone destTimeZone = cc.getTimeZone();

Failed to read row 0, column 6 from a CursorWindow - Android Eclipse

I'm trying to put another item in the questions, but when I do so, an error appears and said about couldn't read row 0 col 6 from CursorWindow I don't know what the problem is, it just forces the app to exit. Thanks.



public class CityAverageDbhelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "CityAverageDbhelper";
// tasks table name
private static final String TABLE_QUEST = "quest";
// tasks Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_QUES = "question";
private static final String KEY_ANSWER = "answer"; //correct option
private static final String KEY_OPTA= "opta"; //option a
private static final String KEY_OPTB= "optb"; //option b
private static final String KEY_OPTC= "optc"; //option c
private static final String KEY_OPTD= "optd"; //option d
private SQLiteDatabase dbase;


public CityAverageDbhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
dbase=db;


String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
+KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT, "+KEY_OPTD+" TEXT)";


db.execSQL(sql);
addQuestions();
//db.close();
}
private void addQuestions()
{

Question q1=new Question("What is JP?","Jalur Pesawat", "Jack sParrow","asjdbajksd", "Jasa Programmer", "Jasa Programmer");
this.addQuestion(q1);
Question q2=new Question("where the JP place?", "Monas, Jakarta", "Gelondong, Bangun Tapan, bantul","asdasd", "Gelondong, Bangun Tapan, bandul", "Gelondong, Bangun Tapan, bantul");
this.addQuestion(q2);
Question q3=new Question("who is CEO of the JP?","Usman and Jack", "Jack and Rully","asdasdasd","Rully and Usman", "Rully and Usman" );
this.addQuestion(q3);
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
// Create tables again
onCreate(db);
}
// Adding new question
public void addQuestion(Question quest) {
//SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION());
values.put(KEY_ANSWER, quest.getANSWER());
values.put(KEY_OPTA, quest.getOPTA());
values.put(KEY_OPTB, quest.getOPTB());
values.put(KEY_OPTC, quest.getOPTC());
values.put(KEY_OPTD, quest.getOPTD());
// Inserting Row
dbase.insert(TABLE_QUEST, null, values);
}
public List<Question> getAllQuestions() {
List<Question> quesList = new ArrayList<Question>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUEST;
dbase=this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Question quest = new Question();
quest.setID(cursor.getInt(0));
quest.setQUESTION(cursor.getString(1));
quest.setANSWER(cursor.getString(2));
quest.setOPTA(cursor.getString(3));
quest.setOPTB(cursor.getString(4));
quest.setOPTC(cursor.getString(5));
quest.setOPTD(cursor.getString(6));
quesList.add(quest);
} while (cursor.moveToNext());

}
// return quest list
return quesList;

}
public int rowcount()
{
int row=0;
String selectQuery = "SELECT * FROM " + TABLE_QUEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
row=cursor.getCount();

return row;
}
}


The QuizActivity



public class CityAverageQuestion extends ActionBarActivity {

int min = 1;
int max = 49;

Random r = new Random();
int qid = r.nextInt(max - min + 1) + min;

List<Question> quesList;
int score=0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc, rdd;
Button butNext;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.cityaveragequestion);


CityAverageDbhelper db=new CityAverageDbhelper(this);
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView)findViewById(R.id.textView2);
rda=(RadioButton)findViewById(R.id.radio1);
rdb=(RadioButton)findViewById(R.id.radio2);
rdc=(RadioButton)findViewById(R.id.radio3);
rdd=(RadioButton)findViewById(R.id.radio5);
butNext=(Button)findViewById(R.id.button1);

setQuestionView();
//butNext.setOnClickListener(new View.OnClickListener() {
//}
}
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());


if(currentQ.getANSWER().equals(answer.getText()))
{

currentQ=quesList.get(qid);
setQuestionView();
Toast.makeText(getBaseContext(), "Correct Answer !!", Toast.LENGTH_LONG).show();
}


else{
Toast.makeText(getBaseContext(), "Wrong Answer !!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(CityAverageQuestion.this, CityAverage.class);
startActivity(intent);
finish();
}
}



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


private void setQuestionView()
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
rdd.setText(currentQ.getOPTD());
qid++;

}
}


here is the logcat



03-02 01:22:11.687: E/CursorWindow(18317): Failed to read row 0, column 6 from a CursorWindow which has 3 rows, 6 columns.

03-02 01:22:11.688: D/AndroidRuntime(18317): Shutting down VM

03-02 01:22:11.688: W/dalvikvm(18317): threadid=1: thread exiting with uncaught exception (group=0x4199ec98)

03-02 01:22:11.688: W/dalvikvm(18317): threadid=1: uncaught exception occurred

03-02 01:22:11.688: W/System.err(18317): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quizexplorer/com.example.quizexplorer.CityAverageQuestion}: java.lang.IllegalStateException: Couldn't read row 0, col 6 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

03-02 01:22:11.688: W/System.err(18317): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)

03-02 01:22:11.688: W/System.err(18317): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)

03-02 01:22:11.689: W/System.err(18317): at android.app.ActivityThread.access$800(ActivityThread.java:151)

03-02 01:22:11.689: W/System.err(18317): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)

03-02 01:22:11.689: W/System.err(18317): at android.os.Handler.dispatchMessage(Handler.java:110)

03-02 01:22:11.689: W/System.err(18317): at android.os.Looper.loop(Looper.java:193)

03-02 01:22:11.689: W/System.err(18317): at android.app.ActivityThread.main(ActivityThread.java:5292)

03-02 01:22:11.689: W/System.err(18317): at java.lang.reflect.Method.invokeNative(Native Method)

03-02 01:22:11.689: W/System.err(18317): at java.lang.reflect.Method.invoke(Method.java:515)

03-02 01:22:11.689: W/System.err(18317): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)

03-02 01:22:11.689: W/System.err(18317): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)

03-02 01:22:11.689: W/System.err(18317): at dalvik.system.NativeStart.main(Native Method)

03-02 01:22:11.689: W/System.err(18317): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 6 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

03-02 01:22:11.690: W/System.err(18317): at android.database.CursorWindow.nativeGetString(Native Method)

03-02 01:22:11.690: W/System.err(18317): at android.database.CursorWindow.getString(CursorWindow.java:434)

03-02 01:22:11.690: W/System.err(18317): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:62)

03-02 01:22:11.690: W/System.err(18317): at com.example.quizexplorer.CityAverageDbhelper.getAllQuestions(CityAverageDbhelper.java:247)

03-02 01:22:11.690: W/System.err(18317): at com.example.quizexplorer.CityAverageQuestion.onCreate(CityAverageQuestion.java:46)

03-02 01:22:11.690: W/System.err(18317): at android.app.Activity.performCreate(Activity.java:5264)

03-02 01:22:11.690: W/System.err(18317): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)

03-02 01:22:11.690: W/System.err(18317): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)

03-02 01:22:11.691: W/System.err(18317): ... 11 more

SQLite to MySql replication an android using symmetricDS

I want to replicate my data in mysql from android sqlite database and any changes made in mysql should be reflected in sqlite. I have made the following app.There is only one activity. This is the code



public class Activity1 extends Activity {

EditText fname,lname,tele,addrs,dates,pins;
Spinner states;
Button addData,modifyData,viewData,deleteData,clearData;
SQLiteDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {

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


fname = (EditText) findViewById(R.id.editText);
lname = (EditText) findViewById(R.id.editText2);
tele = (EditText) findViewById(R.id.editText3);
addrs = (EditText) findViewById(R.id.editText4);
dates = (EditText) findViewById(R.id.editText5);
pins = (EditText) findViewById(R.id.editText6);

addData =(Button) findViewById(R.id.button);
modifyData =(Button) findViewById(R.id.button3);
viewData =(Button) findViewById(R.id.button5);
deleteData =(Button) findViewById(R.id.button2);
clearData =(Button) findViewById(R.id.button4);

states =(Spinner) findViewById(R.id.spinner);

db=openOrCreateDatabase("UserDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS user(fname VARCHAR,lname VARCHAR,tele VARCHAR,addr VARCHAR,state VARCHAR,pin VARCHAR,dob VARCHAR);");


deleteData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(fname.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter first name");
return;
}
Cursor c=db.rawQuery("SELECT * FROM user WHERE fname='"+fname.getText()+"'", null);
if(c.moveToFirst())
{

db.execSQL("DELETE FROM user WHERE fname='"+fname.getText()+"'");
showMessage("Success", "Data Deleted");
}
else
{
showMessage("Error", "Invalid Name");
}
clearText();
}
});



addData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(fname.getText().toString().trim().length()==0||
lname.getText().toString().trim().length()==0||
tele.getText().toString().trim().length()==0 || addrs.getText().toString().trim().length()==0
|| dates.getText().toString().trim().length()==0 ||
pins.getText().toString().trim().length()==0)

{
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO user VALUES('"+fname.getText()+"','"+lname.getText()+"','"+tele.getText()+"','"+addrs.getText()+"','"+states.getSelectedItem().toString()+"','"+pins.getText()+"'" +
",'"+dates.getText()+"');");
showMessage("Success", "Record added");
clearText();

}
});
modifyData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(fname.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter first name");
return;
}
Cursor c=db.rawQuery("SELECT * FROM user WHERE fname='"+fname.getText()+"'", null);
if(c.moveToFirst())
{

db.execSQL("UPDATE user SET lname='"+lname.getText()+"',tele='"+tele.getText()+"',addrs='"+addrs.getText()+"',state='"+states.getSelectedItem().toString()+"',pin='"+pins.getText()+"',dob='"+dates.getText()+"' WHERE fname='"+fname.getText()+"');");
showMessage("Success", "Data Modified");
}
else
{
showMessage("Error", "Invalid Name");
}
clearText();
}
});

viewData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Cursor c = db.rawQuery("SELECT * FROM user", null);
if (c.getCount() == 0) {
showMessage("Error", "No data found");
return;
}
StringBuffer buffer = new StringBuffer();
while (c.moveToNext()) {
buffer.append("First Name: " + c.getString(0) + "\n");
buffer.append("Last Name: " + c.getString(1) + "\n");
buffer.append("Telephone: " + c.getString(2) + "\n");
buffer.append("Address: " + c.getString(3) + "\n");
buffer.append("State: " + c.getString(4) + "\n");
buffer.append("Pincode: " + c.getString(5) + "\n");
buffer.append("date of birth: " + c.getString(6) + "\n\n\n");
}
showMessage("User Data", buffer.toString());
}
});
clearData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
clearText();
}
});
}


This is the code snippet of symmetricDS services I got from this tutorial



final String HELPER_KEY = "NotePadHelperKey";
// Register the database helper, so it can be shared with the SymmetricService
SQLiteOpenHelperRegistry.register(HELPER_KEY, mOpenHelper);Intent intent = new Intent(getContext(), SymmetricService.class);// Notify the service of the database helper key
intent.putExtra(SymmetricService.INTENTKEY_SQLITEOPENHELPER_REGISTRY_KEY, HELPER_KEY);
intent.putExtra(SymmetricService.INTENTKEY_REGISTRATION_URL, "http://ift.tt/1BtzTFC");
intent.putExtra(SymmetricService.INTENTKEY_EXTERNAL_ID, "android-simulator");
intent.putExtra(SymmetricService.INTENTKEY_NODE_GROUP_ID, "client");
intent.putExtra(SymmetricService.INTENTKEY_START_IN_BACKGROUND, true);Properties properties = new Properties();
// initial load existing notes from the Client to the Server
properties.setProperty(ParameterConstants.AUTO_RELOAD_REVERSE_ENABLED, "true");
intent.putExtra(SymmetricService.INTENTKEY_PROPERTIES, properties);getContext().startService(intent);


In tutorial its mentioned that the code snippet is to be added in onCreate What are the changes I should make to make the application work?


Windows Phone 8 optimized insertion into sqlite table from json array

My Windows Phone 8 app is downloading a list of items from a server in json format:



{"error":false,"lists":[{"code":1,"name":"item 1"},{"code":2,"name":"item 2"}, ... ,{"code":100000,"name":"item 100000"}]}


As should be noticed, my app is downloading 100.000 items.


Then my app decodes the json and iterates each item (of 100.000) in order to insert it into the mobile app sqlite database:



JObject content = JObject.Parse(result);
string jsonLists = content.GetValue("lists").ToString().Trim();
JArray jarrTAR = JArray.Parse(jsonLists);

foreach (JObject content2 in jarrTAR.Children<JObject>())
{
string code = content2.GetValue("code").ToString().Trim();
string name = content2.GetValue("name").ToString().Trim();
...
using (var db = new SQLiteConnection(MainPage.DBPath))
{
db.RunInTransaction(() =>
{
db.Insert(new Table1()
{
Code = code,
Name = name,
...
});
});
}
}


This works, but it takes more than 10 minutes inserting the 100.000 items into the sqlite database.


I think this approach (insert items one by one into the table) may be acceptable for a few items downloading, but what should be the recommended strategy for inserting the items when the amount of them are about 100.000?


Is there any way for inserting the total items in one query in order to optimize the insertion time?


Excuse me my bad English.