Sync several DATA from Android SQLLite to MariaDB - android

i look for an easy way to sync my in SQLLite stored Data to MariaDB SQL Database.
WebService is no problem, but i have no clue to get several Data sync at once.
I had an DBAdapter with this, the id is store in sharedpreferences:
public projekt getprojekt(int id){
// 2. build projekt query
Cursor cursor =
db.query(DATABASE_TABLE_P, // a. table
TABLE_P_COLUMNS_ALL, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build projekt object
projekt projekt = new projekt();
projekt.setId(Integer.parseInt(cursor.getString(0)));
projekt.setKostenstelle(cursor.getString(1));
projekt.setAG(cursor.getString(2));
....
// 5. return projekt
return projekt;
}
and this:
// Get Room List
public ArrayList<HashMap<String, String>> GetRaum(int pid){
ArrayList<HashMap<String, String>> raumList = new ArrayList<>();
String query = "SELECT * FROM "+ DATABASE_TABLE_R + " where pid = '"+ pid +"' order by "+KEY_R_BEZEICHNUNG+" asc";
Cursor cursor = db.rawQuery(query,null);
while (cursor.moveToNext()){
HashMap<String,String> raum = new HashMap<>();
raum.put("id",cursor.getString(cursor.getColumnIndex(KEY_M_ID)));
raum.put("bezeichnung",cursor.getString(cursor.getColumnIndex(KEY_M_BEZEICHNUNG)));
raumList.add(raum);
}
return raumList;
}
Bit how i get several "Rooms" selected to send it via POST/JSON to WebService?
My current function to send Data is not finished ... just getting the projekt_id from sharedpreferences.
public void postData() throws JSONException {
final SharedPreferences sharedPreferences = this.getSharedPreferences("de.dasal.dguvv3", Context.MODE_PRIVATE);
final Integer projektidsp = sharedPreferences.getInt("projekt_id", 0);
final projekt projekt = db.getprojekt(projektidsp);
}
If you need further Informations, please let me know.
Its my first Question on stackoverflow.

Related

Sqlite updating a record

This is my first time meddling with sqlite on android.
Followed a tutorial and created a SQliteHelper Class, there is this method inside:
// Updating single profile
public int updateProfile(Profile profile) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("cpf", profile.getCpf()); // get cpf
values.put("nome", profile.getNome()); // get nome
values.put("phone", profile.getPhone()); // get nome
// 3. updating row
int i = db.update(TABLE_PROFILES, //table
values, // column/value
KEY_ID+" = ?", // selections
new String[] { String.valueOf(profile.getId()) }); //selection args
// 4. close
db.close();
return i;
}
However, I have no idea how to use it..
I know that in order to get the profile I do the following:
MySQLiteHelper db = new MySQLiteHelper(view.getContext());
db.updateProfile(db.getProfile(0));
But how do I actually update it?
That code updates the profile with an specific id in this part:
// 3. updating row
int i = db.update(TABLE_PROFILES, //table
values, // column/value
KEY_ID+" = ?", // selections
new String[] { String.valueOf(profile.getId()) }); //selection args
So, this id comes from the Profile object you have just pased to the function.
You should do something like:
// get a profile
MySQLiteHelper db = new MySQLiteHelper(view.getContext());
Profile p = db.getProfile(0);
// change something
p.setPhone(55598789);
// update profile p
updateProfile(p);

Android - Database/cursor wont fill

I got a redicioulous error.
My cursor wont fill with database entries.
The code i have right now is:
public HashMap<Integer, Team> getTeamsBasic(int leagueId) {
System.out.println("TEST!!!" + leagueId);
SQLiteDatabase db = dbHelper.getReadableDatabase();
HashMap<Integer, Team> teams = null;
System.out.println("TEST3!");
String query = "SELECT * FROM Teams WHERE leagueId = ?";
Cursor c = db.rawQuery(query, new String[] { Integer.toString(leagueId)});
System.out.println("TEST4!");
teams = new HashMap<Integer, Team>();
System.out.println("BOOL: " + c.moveToFirst());
if (c.moveToFirst()) {
System.out.println("TEST5!");
while (c.isAfterLast() == false) {
Team team = new Team();
System.out.println("TEST!6");
team.setId(c.getInt(c.getColumnIndex("id")));
team.setName(c.getString(c.getColumnIndex("name")));
team.setStadium(c.getString(c.getColumnIndex("stadium")));
System.out.println("TES2T!");
teams.put(team.getId(), team);
c.moveToNext();
}
c.close();
System.out.println("TEAMSIZE: " + teams.size());
}
return teams;}
The problem is, I KNOW FOR SURE my database.db is filled with the correct items.
As i have downloaded my DB from my phone, and checked it with the same query as my script does.
Except my script gets no output while me doing the same thing in DB Browser for SQLite i get a ton of output:
https://gyazo.com/2a14458f50fd5a836c55a383d65d0d65
Its the exact same query i use when doing it in android as doing it manually.
The leagueId = 1.
Also the output of the BOOL: = FALSE :(
Whats going (wr)on(g)?

SQLite: Fetching data from one table based on 2 differeet ID values into 2nd table

I have two tables named List and Task.
List table is composed by two columns: ListID and NAME
Task table is composed by: TaskId,TaskListId,Name,Notes,Completed and Hidden
There are 3 list ID which creates 3 tabs named Personal,Business and History using TabManager
What I need is if I delete a task from personal or business then it is hidden by setting Hidden=1. Then I want to show that in my History tab. How to achieve this.
How to write query for this in SQLite.? I need a query something like below
Select * from Task where (TaskListID=1 or 2 // this is the part giving me problem as TaskListId decides which task belongs to which tab like 1=personal,2=business ) AND hidden==1;
following is the method refreshTaskList() used to display data for current tab.
public void refreshTaskList() {
// get task list for current tab from database
Context context = getActivity().getApplicationContext();
TaskListDB db = new TaskListDB(context);
//ArrayList<Task> tasks=new ArrayList<Task>();
if(Objects.equals(currentTabTag, "History"))
{
ArrayList<Task> tasks=db.getHistory(currentTabTag);
TaskListAdapter adapter = new TaskListAdapter(context, tasks);
taskListView.setAdapter(adapter);
}else
{
ArrayList<Task>tasks2=db.getTasks(currentTabTag);
TaskListAdapter adapter = new TaskListAdapter(context, tasks2);
taskListView.setAdapter(adapter);
}
Also following are the getTasks and getHistory methods used to pull tasks from database for current Tab.
public ArrayList<Task> getTasks(String listName) {
String where =
TASK_LIST_ID + "= ? AND " +
TASK_HIDDEN + "!='1'";
long listID = getList(listName).getId();
String[] whereArgs = {Long.toString(listID)};
this.openReadableDB();
Cursor cursor = db.query(TASK_TABLE, null,
where, whereArgs,
null, null, null);
ArrayList<Task> tasks = new ArrayList<Task>();
while (cursor.moveToNext()) {
tasks.add(getTaskFromCursor(cursor));
}
if (cursor != null)
cursor.close();
this.closeDB();
return tasks;
}
public ArrayList<Task> getHistory(String listName)
{
String where =
TASK_LIST_ID + "= ? AND " +
TASK_HIDDEN + "=='1'";
long listID = getList(listName).getId();
String[] whereArgs = {Long.toString(listID)};
this.openReadableDB();
Cursor cursor = db.query(TASK_TABLE, null,
where, whereArgs,
null, null, null);
Log.v(TAG,"Value of cursor is-" +cursor);
ArrayList<Task> tasks = new ArrayList<Task>();
while (cursor.moveToNext()) {
tasks.add(getTaskFromCursor(cursor));
}
if (cursor != null)
cursor.close();
this.closeDB();
return tasks;
}
What I think is that the TASK_LIST_ID acts as a foreign key which decides which task belongs to which tab in DB. So what I need is a such query where I can get the tasks from both tabs namely Personal and Business and put them in History if their Hidden value is set to 1 .
If the 1 or 2 part is giving you hard time, then here you go:
SELECT * FROM task WHERE TaskListID=1 OR TaskListID=2 AND HIDDEN=1

How to pass multiple values to query dynamically in android?

In my project I have to select multiple values and pass it to a query. i.e page1 contains checkboxes. I am storing the selected checkbox id's into an array.
I am shuffling that array and getting the values randomly. Now I need to pass these random values to a query. Using IN operator in database I can pass the values
statically but how can I pass the values dynamcially to the query.
For ex:(Passing values statically)
SELECT * FROM Persons WHERE person_id IN ('21','22')
In the above query the id's 21 and 22 are know previously and so we are passing statically but I want to send the values to query dynamically.
Page1:
public static ArrayList<String> chksublist = new ArrayList<String>();
Page2:
Collections.shuffle(chksublist );
SELECT * FROM Persons WHERE person_id IN ('21','22')
In the above line I want to send the random values which are in chksublist array.
String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ")";
But shuffling the chksublist before sending it to your SQL query has no impact on the result set you get from SQL. It will not randomly permute your results. Remove Collections.shuffle(chksublist); and use
String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ") ORDER BY RANDOM()";
see how values are dynamicaly passed
// Getting single contact
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
// here new String[] { String.valueOf(id) } value is added dynamicaly which is passed to the function
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
You can generate your query like this
int values[]; //it contains your generated values like 21,22....
String query="SELECT * FROM Persons WHERE person_id IN (";
for(int i=0;i<values.length;i++){
query=query+"'"+values[i]+"'";
if(i<values.length-1){
query=query+","; //No , after last values
}
}
query+=")";
finally pass this query.
Try it
cursor = database.query(tablename,
new String[] {"TopName"}, "id IN(?,?)", new String[]{"2","3"}, null, null, null);
using raw query
String query = "SELECT * FROM Persons WHERE person_id IN ("+parameter1+","+parameter2+")";
db.rawQuery(query);

android sqlite query optimisation

I have an SQLite db with about 400 000 entries. To query the db I am using the following method:
public double lookUpBigramFrequency(String bigram) throws SQLException {
SQLiteDatabase db = dbh.getReadableDatabase();
double frequency = 0;
bigram = bigram.toLowerCase();
String select = "SELECT frequency FROM bigrams WHERE bigram = '"
+ bigram + "'";
Cursor mCursor = db.rawQuery(select, null);
if (mCursor != null) {
if (mCursor.moveToFirst()) {
frequency = Double.parseDouble(mCursor.getString(0));
} else {
frequency = 0;
}
}
return frequency;
}
but it takes about 0.5 sec to retrieve a single entry and having few queries, it builds up and the method is executing for 10 secs. How to speeed it up?
Firstly, use an INDEX
http://www.sqlite.org/lang_createindex.html
in your case that will be something like:
CREATE INDEX idx_bigram ON bigrams (bigram)
Secondly, use '?' instead of literal query. It helps sqlite for caching requests:
String select = "SELECT frequency FROM bigrams WHERE bigram = ?";
Cursor mCursor = db.rawQuery(select, new String[]{ bigram });
Thirdly, I trust query is more efficient than rawQuery:
mCursor = dq.query("bigrams", new String[] { "frequency" }, "bigram = ?",
new String[]{ bigram }, null, null, null, null);
Fourthly, you can query several values at once (not compatible with point 2):
SELECT frequency FROM bigrams WHERE bigrams IN ('1', '2', '3')
Fifthly, you don't need to open your database every time. You should consider leaving it open.
Edit
After seeing this question IN clause and placeholders it appears you can combine 2 and 4 after all (not sure it is useful, though)
Always use transaction mechanism when you want to do lots of database operations
public static void doLotDBOperations() {
try {
// Code to Open Database
// Start transaction
sqlDb.beginTransaction();
// Code to Execute all queries
sqlDb.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
// End all transaction
sqlDb.endTransaction();
// Code to Close Database
}
}

Categories

Resources