ORMLite not update with the same count of object - android

I try to make simple test. I have json response from REST API with ~250 objects shops and the same response in file but first shop has different name. First step is load JSON file with ~250 shops and save in local db using ORMLite. Next step is connect with API and get the same response. New json response is parse and UPDATE exist elements in database. What is result?
Now I go to simple Activity with ListView and call getShopsAll(). This method return old data before update. Why?
This is method to save shop in database:
public void createShop(final ArrayList<ModelSklep> list) throws Exception {
getDaoShop().callBatchTasks(new Callable<Void>() {
#Override
public Void call() {
for(ModelSklep item : list) {
createShop(item);
if(item.getHoursList().size() > 0) {
createHours(item.getHoursList());
}
}
return null;
}
});
}
Method createshop:
public boolean createShop(ModelSklep item) {
try {
getDaoShop().createOrUpdate(item);
return true;
} catch (SQLException e) {
return false;
}
}
Method getShopAll:
public ArrayList<ModelSklep> getShopAll() {
try {
return (ArrayList<ModelSklep>) getDaoShop().queryBuilder().orderByRaw(
"nazwaPelna COLLATE LOCALIZED ASC").query();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
Object is updating. But getShopAll() return old data object.
Clear cache after update doesn't work.
Help. I don't know how resolve this problem.
[Edit]
public Dao<ModelSklep, Integer> getDaoShop() {
if(modelShopDao == null) {
try {
modelShopDao = getDao(ModelSklep.class);
modelShopDao.setObjectCache(true);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return modelShopDao;
}

Related

how I can Use two table in a time with Xamarin Android

I have one connection for each table in a database like the below, How Can I use Two Table in a time?? My Main trouble is how connect to Two Table in a time to use them. Please somebody tell me about that
part of My code is:
public bool createDataBase()
{
try
{
using (var connection = new
SQLiteConnection(System.IO.Path.Combine(folder, "Plans.db")))
{
connection.CreateTable<Plan>();
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public bool createDataBase2()
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "PlanDoned.db")))
{
connection.CreateTable<Plan>();
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public bool insertIntoTablePlanDoned(Plan plan)
{
try
{
using (var connection = new
SQLiteConnection(System.IO.Path.Combine(folder, "PlanDoned.db")))
{
//connection.Query<Plan>("UPDATE Plan SET PlanName=?,PlanDate=?,PlanDesc=? where Id=?", plan.PlanName, plan.PlanDate, plan.PlanDesc, plan.Id);
//return true;
connection.Query<Plan>("insert into PlanDoned select * from Plans where Id=?", plan.Id);
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
use ATTACH DATABASE 'Database2Path' As 'Database2Name';
Then use both Database1 and Database2 in the same query i.e.:
INSERT INTO Database2Name.Table SELECT Column1, Column2 FROM Database1.Table

Upload Parse Object with RxJava

I would like to wrap a synchronous method from parse.com mainly ParseObject.save() into a RxJava wrapper. I have come up with the below:
public Observable<Void> uploadFix(final ParseObject parseObject) {
return Observable.defer(new Func0<Observable<Void>>() {
#Override
public Observable<Void> call() {
try {
return Observable.just(fix.save());
} catch (ParseException e) {
return Observable.error(e);
}
}
});
}
This is giving me an error: Observable cannot be applied to void.
Basically is there any way to wrap this call with RxJava and get notified if the save is successful?
fix.save() returns void so you can't use it as an argument to Observable.just(). You can return a boolean instead.
public Observable<Boolean> uploadFix(final ParseObject parseObject) {
return Observable.defer(new Func0<Observable<Boolean>>() {
#Override
public Observable<Boolean> call() {
try {
fix.save();
return Observable.just(true);
} catch (ParseException e) {
return Observable.error(e);
}
}
});
}
you could also use a Completable. It is used when you don't except a return-value. If RxJava for Android will bump-up to version 2, you can not use Observabl anymore, because null values are not allowed anymore.
Please look at my example. I am using RxJava2-RC5 for testing. Test should complete within 2 seconds + overhead.
#org.junit.Test
public void name() throws Exception {
Completable completable = Completable.fromAction(() -> doWorkSync());
TestObserver<Void> test = completable.test();
test.assertComplete();
}
private void doWorkSync() {
// simulate work
try {
Thread.sleep(2_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

pass boolean from handler to function

I am trying to develop a function that gives my android application a test to see if the data on the phone matches that on the server.
I have every part of the function working fine apart from I want the message to come back from the server to the handler then I want the handler to return false or true and pass the value to function which returns a boolean.
A point in the right direction would be greatly appreciated.
here is the android code so far.
public boolean isTripUpladedToServer(int tripId)
{
if(isServiceRunning()&&tripId==currentTripId){return false;}
SQLiteDatabase db;
db=this.openOrCreateDatabase(DATABASE_NAME, SQLiteDatabase.OPEN_READWRITE, null);
String Qu="SELECT COUNT(tripid) from TRIP_DATA WHERE TRIPID="+tripId+";";
Cursor c= db.rawQuery(Qu, null);
int count=0;
if(c!=null &&c.moveToFirst())
{
count=c.getInt(0);
}
JSONArray parcel =new JSONArray();
JSONObject header =new JSONObject();
JSONObject message =new JSONObject();
try {
header.put("tablename", "isTripUploaded");
header.put("userid", userid);
parcel.put(header);
message.put("count", count);
message.put("tripid", tripId);
parcel.put(message);
Log.i(tag, parcel.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Handler inner=new Handler()
{
#Override
public void handleMessage(Message msg)
{
try {
JSONObject ret=new JSONObject(msg.obj.toString());
Log.i(tag,ret.toString());
// I want the function to return the boolean value that the server has sent to phone.
} catch (JSONException e) {
e.printStackTrace();
}
}
};
new uploadero(inner).execute(parcel);
//the below return value is here to prevent the error, ideally I want to remove it
return false;
}
If I have approached this in the wrong way please say, thanks in advance Mark
Use a class variable for the boolean and use a getter in the handler to get it.

Android ORMLite slow create object

I am using ormLite to store data on device.
I can not understand why but when I store about 100 objects some of them stores too long time, up to second.
Here is the code
from DatabaseManager:
public class DatabaseManager
public void addSomeObject(SomeObject object) {
try {
getHelper().getSomeObjectDao().create(object);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class DatabaseHelper extends OrmLiteSqliteOpenHelper
public Dao<SomeObject, Integer> getSomeObjectDao() {
if (null == someObjectDao) {
try {
someObjectDao = getDao(SomeObject.class);
} catch (Exception e) {
e.printStackTrace();
}
}
return someObjectDao;
}
Any ideas to avoid this situations?
Thanks to Gray!
Solution is, as mentioned Gray, using callBatchTasks method:
public void updateListOfObjects (final List <Object> list) {
try {
getHelper().getObjectDao().callBatchTasks(new Callable<Object> (){
#Override
public Object call() throws Exception {
for (Object obj : list){
getHelper().getObjectDao().createOrUpdate(obj);
}
return null;
}
});
} catch (Exception e) {
Log.d(TAG, "updateListOfObjects. Exception " + e.toString());
}
}
Using this way, my objects (two types of objects, 1st type - about 100 items, 2nd type - about 150 items) store in 1.7 sec.
See the ORMLite documentation.

Android ORMLite - ForeignCollection child has null foreign field

I'm currently stuck with the following situation;
Basically I've got a Work class, which has a ForeignCollection of WorkTasks.
I'd like to simply receive all WorkTasks, linked to Work object.
If I query for all WorkTasks, I do get a list of results but with 'work = null'. So it can't make any link to the correct Work object.
Resulting in no results with querying for the work_id and an empty list in Work itself.
I've seen examples and questions about this countless of times but apparently im missing out on something.
Below is the code that im using which is relevant;
The DatabaseHelper;
#Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
applicantDao = DaoManager.createDao(connectionSource, Applicant.class);
educationDao = DaoManager.createDao(connectionSource, Education.class);
workDao = DaoManager.createDao(connectionSource, Work.class);
workTaskDao = DaoManager.createDao(getConnectionSource(), WorkTask.class);
onlinePersonDao = DaoManager.createDao(connectionSource, OnlinePerson.class);
institutionDao = DaoManager.createDao(connectionSource, Institution.class);
lessonDao = DaoManager.createDao(connectionSource, Lesson.class);
TableUtils.createTable(connectionSource, Applicant.class);
TableUtils.createTable(connectionSource, Education.class);
TableUtils.createTable(connectionSource, Work.class);
TableUtils.createTable(connectionSource, Institution.class);
TableUtils.createTable(connectionSource, Lesson.class);
TableUtils.createTable(connectionSource, OnlinePerson.class);
TableUtils.createTable(connectionSource, Reference.class);
TableUtils.createTable(connectionSource, WorkTask.class);
[....]
public Dao<WorkTask, Integer> getWorkTaskDao() {
if (null == workTaskDao) {
try {
workTaskDao = getDao(WorkTask.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return workTaskDao;
}
The database manager:
public List<Experience> getAllWork() {
List<Experience> exp = null;
try {
exp = getHelper().getWorkDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return exp;
}
public List<WorkTask> getAllWorkTask() {
List<WorkTask> workTask = null;
try {
workTask = getHelper().getWorkTaskDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return workTask;
}
public List<WorkTask> getWorkTaskByWorkId(int workId) {
List<WorkTask> workTasks = null;
try {
workTasks = getHelper().getWorkTaskDao().queryForEq("work_id", workId);
} catch (SQLException e) {
e.printStackTrace();
}
return workTasks;
}
public void addWork(Collection<Work> jobs) {
try {
for (Experience work : jobs) {
Work w = (Work) work;
// Add nested child first
this.addInstitution(w.institution);
this.addWorkTask(w.tasks);
getHelper().getWorkDao().createOrUpdate(w);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addWorkTask(Collection<WorkTask> worktasks) {
try {
for (WorkTask wt : worktasks) {
getHelper().getWorkTaskDao().createOrUpdate(wt);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
The list from the work model (gets a pre-filled id from an abstract parent):
#ForeignCollectionField(eager = true)
#SerializedName("tasks")
public Collection<WorkTask> tasks;
public ArrayList<WorkTask> getTasks(){
ArrayList<WorkTask> taskList = new ArrayList<WorkTask>();
Iterator iterator = tasks.iterator();
while(iterator.hasNext()){
WorkTask task = (WorkTask) iterator.next();
taskList.add(task);
}
return taskList;
}
The WorkTask :
public class WorkTask {
/**
* Auto-incremented id for the ORMLite-SQLite database
*/
#DatabaseField(generatedId = true)
public int id;
/**
* Foreign field id for the ORMLite-SQLite database
*/
#DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true, columnName = "work_id")
public Work work;
And finally all the things that are failing me:
ArrayList<WorkTask> tasks_iterated = work.getTasks();
ArrayList<WorkTask> tasks_id = (ArrayList<WorkTask>) DatabaseManager.getInstance()
.getWorkTaskByWorkId(work.id);
ArrayList<WorkTask> tasks = (ArrayList<WorkTask>) DatabaseManager.getInstance().getAllWorkTask();
This eventually leaves me with:
tasks_iterated = empty
tasks_id = empty
tasks = a full list of my tasks but all with the attribute 'work = null' so I can't place them to the correct Work object.
Fixed it by changing my adding method to:
public void addWorkTask(Collection<WorkTask> worktasks, Work work) {
try {
for (WorkTask wt : worktasks) {
wt.work = work;
getHelper().getWorkTaskDao().createOrUpdate(wt);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Not sure if it's the only way to do this though. Seems a bit weird i'd have to do this manually.

Categories

Resources