I have ORMLite database with some fields. I want to select titles from the table where id == id which I get from webservice. I do like that:
try {
Dao<ProcessStatus,Integer> dao = db.getStatusDao();
Log.i("status",dao.queryForAll().toString());
QueryBuilder<ProcessStatus,Integer> query = dao.queryBuilder();
Where where = query.where();
String a = null;
for(Order r:LoginActivity.orders) {
//LoginActivity.orders - array of my objects which I get from webservice
Log.i("database",query.selectRaw("select title from process_status").
where().rawComparison(ProcessStatus.STATUS_ID, "=",
r.getProcess_status().getProccessStatusId()).toString());
}
Log.i("sr",a);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I tried like this but I get only sets of my id, not titles. I tried like this:
Log.i("database", query.selectColumns(ProcessStatus.STATUS_TITLE).where().
eq(ProcessStatus.STATUS_ID, r.getProcess_status().getProccessStatusId())
.toString());
but I have the same result. How should I get data from database?
For selecting an specific field from the table, you could do something like this:
String result = "";
try {
GenericRawResults<String[]> rawResults = yourDAO.queryRaw("select " +
ProcessStatus.STATUS_TITLE +" from YourTable where "+
ProcessStatus.STATUS_ID + " = " +
r.getProcess_status().getProccessStatusId());
List<String[]> results = rawResults.getResults();
// This will select the first result (the first and maybe only row returned)
String[] resultArray = results.get(0);
//This will select the first field in the result which should be the ID
result = resultArray[0];
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps.
It's hard to properly answer this question without seeing all of the classes of the processStatusId field and others. However I think you are doing too much raw method and may not be properly escaping your values and the like.
I would recommend that you use the IN SQL statement instead of what you are doing in the loop. Something like:
List<String> ids = new ArrayList<String>();
for(Order r : LoginActivity.orders) {
ids.add(r.getProcess_status().getProccessStatusId());
}
QueryBuilder<ProcessStatus, Integer> qb = dao.queryBuilder();
Where where = qb.where();
where.in(ProcessStatus.STATUS_ID, ids);
qb.selectColumns(ProcessStatus.STATUS_TITLE);
Now that you have built your query, either you can retrieve your ProcessStatus objects or you can get the titles themselves using dao.queryForRaw(...):
List<ProcessStatus> results = qb.query();
// or use the prepareStatementString method to get raw results
GenericRawResults<String[]> results = dao.queryRaw(qb.prepareStatementString());
// each raw result would have a String[] with 1 element for the title
Related
I am developing a mobile application in android.The application gets data from a database(in SQL Server) using a soap web service(in java). Now i have been stuck into a problem and it is as follows- the android application retrieves a row (all the columns) from the database and sets the column values to the respective text fields but i don't know what to do in the web service. Please help me
My Code for the web method is-
#WebMethod(operationName = "DiseaseInfoGC")
public String DiseaseInfo4( #WebParam(name = "crop_name") String crop,
#WebParam(name = "spread_mode") String spread_mode,
#WebParam(name = "path_cong_env") String path_cong_env) {
query_disease = new String();
try {
DBConnect.databaseconnect();
Statement stmt_disease = DBConnect.connect.createStatement();
query_disease = "Select * from Disease where crop_name='" + crop + "' and Disease_SpreadMode='"+spread_mode+"' "
+ "and Disease_PathCongEnv='" + path_cong_env + "'";
System.out.println(query_disease);
ResultSet rslt_disease = stmt_disease.executeQuery(query_disease);
System.out.println(query_disease);
executemyquery(rslt_disease);
System.out.println(query_disease);
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (SQLException ex) {
System.out.println(ex.getMessage());;
} catch (NullPointerException ex) {
System.out.println(ex.getMessage());
}
return disease_name;
}
And the executequery() is-
private void executemyquery(ResultSet rslt_disease) throws SQLException {
while (rslt_disease.next()) {
disease_name = rslt_disease.getString("Disease_EngName");
System.out.println("Name Of the Disease: "+disease_name);
path_name = rslt_disease.getString("Disease_PathScName");
System.out.println("Name of the Pathogen: "+path_name);
path_geo_dis = rslt_disease.getString("Disease_PathGeoDist");
System.out.println("Pathogen Scientific name: "+path_geo_dis);
path_life_cycle = rslt_disease.getString("Disease_PathLCycle");
System.out.println("Life Cycle of the Pathogen: "+path_life_cycle);
disease_symptoms = rslt_disease.getString("Disease_Symptom");
System.out.println("Disease Symptoms: "+disease_symptoms);
disease_controls = rslt_disease.getString("Disease_Control");
System.out.println("Disease control mechanism: "+disease_controls);
prevention = rslt_disease.getString("Disease_Prevention");
System.out.println("Disease prevention Mechanism: "+prevention);
spread_mode = rslt_disease.getString("Disease_SpreadMode");
System.out.println("Spread mode of the disease: "+spread_mode);
primary_source = rslt_disease.getString("Disease_PSource");
System.out.println("Primary Source: "+primary_source);
secondary_source = rslt_disease.getString("Disease_SSource");
System.out.println("Secondary Source: "+secondary_source);
path_a_host = rslt_disease.getString("Disease_PathAHost");
System.out.println("Pathogen host"+path_a_host);
path_cong_env = rslt_disease.getString("Disease_PathCongEnv");
System.out.println("Pathogen Congenial Envoronment"+path_cong_env);
occur_period = rslt_disease.getString("Disease_OccurancePd");
System.out.println("Disease occuring period: "+occur_period);
}
I have just stored the column values in the string. I know that it is useless use string here. But i have no idea how to store the column values from the database in the web method so that i can use them in the android application.Hope you can understand my question. Please guide me..
I wasn't sure how to frame the question title, but, here is what i am trying to do.
Using Parse.com
I have a table - Surveys and it has a column with Array datatype. I have a JSONArray stored in this column. The JSONArray has 3 JSONObjects. I have to loop through the 3 JSONObjects, get a field with key "type" and use the value (for example "type_dob") of this key, to query a separate table again. I need this to be done in a row, for example once the result for first key is retrieved, then i have to perform the query for second key.
How can i achieve this?
Sample JSON: Questions: [{"type":"type_dob","id":"I27y16N5gX"},{"type":"type_text","id":"jGAujtNNZc"},{"type":"type_radio","id":"cCDlrrJYKI"}]
My present code:
public void getDataFromServer() {
ParseUser user = ParseUser.getCurrentUser();
if (user != null) {
showProgressDialog("Getting Survey details...");
int survey_count = user.getInt(Const.Parse_User.SURVEY_COUNT);
Log.d(Const.DEBUG, "Survey Count: " + survey_count);
String current_survey = "survey_" + (survey_count + 1);
Log.d(Const.DEBUG, "Current Survey: " + current_survey);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Surveys");
query.whereEqualTo(Const.Parse_SURVEYS.SURVEY_ID, current_survey);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
dismissProgressDialog();
if (e != null) {
Log.d(Const.DEBUG, "Exception while getting data from Parse - Surveys table");
} else {
if (list.size() > 0) {
ParseObject object = list.get(0);
try {
String questions_array = object.getJSONArray(Const.Parse_SURVEYS.QUESTIONS).toString();
Log.d(Const.DEBUG, "Questions: " + questions_array);
JSONArray array = object.getJSONArray(Const.Parse_SURVEYS.QUESTIONS);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String type = jsonObject.get("type").toString();
//I should write the query for getting data from table matching the String type. //If i do a findInBackground query for each of the key, then its done in a background thread
//and the for loop exists even before the result for first key comes back.
//How can i handle this?
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
});
}
}
Let me know if you need anything else?
I think you are moving slightly in a unfortunate direction with your db design.
As far as I can tell from you question, the better approach for you would be to store an Array of pointers. For instance, having a data class in Parse.com called 'Question', which stores a type and whatever other properties you need.
Now assume you have an Array instead in your 'Surveys' class. Then your code gets rather simple:
ParseQuery<ParseObject> query = ParseQuery.getQuery("Surveys");
query.whereEqualTo(Const.Parse_SURVEYS.SURVEY_ID, current_survey);
query.include(Const.Parse_SURVEYS.QUESTIONS); // <- IMPORTANT
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
ParseObject object = list.get(0);
// get all Question objects
List<ParseObject> array = object.getList(Const.Parse_SURVEYS.QUESTIONS);
// no need to fetch, the data is here
for (ParseObject question: array) {
String type = question.getString("type");
String question = question.getString("question");
List<String> answerOptions = question.getList("options")
...
}
}
}
If for some reason you cannot transition to this design, then I believe you want to look into Bolts https://github.com/BoltsFramework/Bolts-Android. With this you get the same async abilities as Promises does in javascript. This means that you can que up a range of background jobs and return only when all are completed.
Though Bolts will aid you, it will not avoid exiting your for-loop before it has completed. This is however just a matter of design, meaning that as long as you are aware of the flow of our program, you can design it accordingly. For instance delaying the dismiss of a progress dialog until all background tasks has completed (or failed).
I however suggest that you look into the documentation about the query.include() capabilities together with pointer arrays.
i fetched data like this way from data parse table.
ParseQuery<ParseObject> query = ParseQuery.getQuery("Surveys");
query.whereEqualTo(Const.Parse_SURVEYS.SURVEY_ID, current_survey);
query.include(Const.Parse_SURVEYS.QUESTIONS); // <- IMPORTANT
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
ParseObject object = list.get(0);
// first initilization Jsonobject Array list.
List<JSONObject> jsobj = new ArrayList<JSONObject>();
jsobj = object.getList(Const.Parse_SURVEYS.QUESTIONS);
// no need to fetch, the data is here
for (int i = 0; i < jsobj.size(); i++) {
Log.e("in the For loop ", ": : ::111111 : " + jsobj.get(i));
JSONObject arr1 = new JSONObject((Map) jsobj.get(i)); // jsobj.get(i);
Log.e("in the For loop ", ": : ::111111 : " + arr1);
try {
Log.e("in the For loop ",
": : ::111111 : " + arr1.getString("name"));
// hear u want to store data in Custom Array list.
// other wise u store in single String value
String type = arr1.getString("type");
String question = arr1.getString("question");
String options = arr1.getString("options");
// this is my custom getter setter class
GetIngredients ai = new GetIngredients();
ai.setName(arr1.getString("type"));
ai.setQty(arr1.getString("question"));
ai.setUnit(arr1.getString("options")) ;
// this is my custom array
arr_Ingredients.add(ai);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("in the For loop ", ": : :: : " + jsobj.get(i));
}
}
in my parse data base column type is "Array".
I want to save weekdays in database, so i thought to store it by assigning int value to each day. i.e
1 -> Selected, 0 -> Not Selected.
Monday = 0/1
Tuesday = 0/1
.
.
.
.
.
Sunday = 0/1.
But this will make 7 columns in DB. So I was thinking if anyone can help me with this if I should store it in a single array and retrieve the values for further use. I was reading some examples over internet but didn't get it in a easy way.
To insert 7 values in one column you can use comma separator like this
where Total_Score_P1 is an string array
//string array
String[] Total_Score = new String[] { p1e1,p1e2,p1e3,p1e4,p1e5,p1e6 };
// Convderting it into a single string
String result_ScoreP1 = ("" + Arrays.asList(Total_Score_P1)).
replaceAll("(^.|.$)", " ").replace(", ", " , " );
result_ScoreP1 will be
// output of this
result_ScoreP1 = "p1e1,p1e2,p1e3,p1e4,p1e5,p1e6";
insert it as a single string in database and
when retrieve it in again break in parts like
// a string array list
// query fired
public ArrayList<String> rulTable(String id) {
// TODO Auto-generated method stub
ArrayList<String> Ruleob = new ArrayList<String>();
Cursor c_rule;
try
{
c_rule = db.query(NameTable, new String[]{
columns1
},
Rule_COurseID + "=" + id ,
null, null,
null, null, null);
c_rule.moveToFirst();
// if there is data available after the cursor's pointer, add
// it to the ArrayList that will be returned by the method.
if (!c_rule.isAfterLast())
{
do
{
Ruleob.add(c_rule.getString(0));
}
while (c_rule.moveToNext());
}
// let java know that you are through with the cursor.
c_rule.close();
}
catch(Exception e)
{
}
return Ruleob;
}
//list to get elements
ArrayList<String> ListOne = new ArrayList<String>();
ArrayList<String> row ;
try{
// received values
row = db.TheTable(id);
String r1 = row .get(0);
}
catch(Exception e)
{
}
StringTokenizer st2 = new StringTokenizer(r1, "||");
while(st2.hasMoreTokens()) {
String Desc = st2.nextToken();
System.out.println(Desc+ "\t" );
ListOne.add(Desc);
//
}
You can use a binary integer 1= selected 0 =Not Selected (1111111) (0000000)
total seven days so index 0=mon, 1=tues, 2=wed, 3=thurs, 4=friday, 5=sat, 6=sunday..and so on..
here 1111111 means all day selected, 0000000 all day not selected, 0001000 only thursday is selected.
I have also discovered a way i.e. convert your so called values to a JSON Array and then store the complete JSON String to an entity/field in Database.
It helps in serving the values easily and effectivly.
Create another table with a column for each day, boolean value. Make an association to this table by integer id (use a foreign key) This is the relational way of solving the problem.
I have created complied statement given below. Now my question is how to get resultset of the query.
Here is my code:
DataBaseHelper dbHelper=new DataBaseHelper(context);
dbHelper.createDataBase();
dbHelper.openDataBase();
SQLiteDatabase db = dbHelper.getWritableDatabase();
SQLiteStatement st=db.compileStatement("select taskid from task where taskdate=?");
st.bindString(1,"2011/09/05");
st.execute();
This works without any error. But I want the result set of the given query. Please help..
The result set isn't available, at least for now, in sqlite. It all depends on exactly what information you want from the ResultSet or ResultSetMetaData, etc, but there are other means of obtaining almost the same information.
You can get detailed information about the columns in a table with the following, used as if it were a SELECT, and the information about the columns will be presented:
pragma table_info(myTable) ;
See http://www.sqlite.org/pragma.html#pragma_table_info for more information.
If you want the information concerning a specific SELECT, you can get information from the resulting Cursor. See http://developer.android.com/reference/android/database/Cursor.html
For example, if you want the type of data for a column, you can use the getType() method in the newer versions of Android, or use a series of "get" functions to determine at least what type is readable, with this horrible code:
Cursor curs = db.rawQuery(sqlStr, null);
int numberOfColumns = curs.getColumnCount();
String []colNames = new String[numberOfColumns];
String []colTypes = new String[numberOfColumns];
for(int iCol=1; iCol<=numberOfColumns; iCol++) {
colNames[iCol-1] = curs.getColumnName(iCol-1);
colTypes[iCol-1] = null; //curs.getType(iCol);
}
while(curs.moveToNext()) {
// this code assumes that the first row has the same data types
// as the rest of the rows
for(int iCol=1; iCol<=numberOfColumns; iCol++) {
String colName = colNames[iCol-1];
String colType = colTypes[iCol-1];
if(colType==null) {
// determine column type
try {
curs.getString(iCol-1);
colType = colTypes[iCol-1] = "text";
} catch (Exception ignore) {
try {
curs.getLong(iCol-1);
colType = colTypes[iCol-1] = "integer";
} catch (Exception ignore1) {
try {
curs.getFloat(iCol-1);
colType = colTypes[iCol-1] = "real";
} catch (Exception ignore2) {
try {
curs.getBlob(iCol-1);
colType = colTypes[iCol-1] = "blob";
} catch (Exception ignore3) {
colType = colTypes[iCol-1] = "other";
}
}
}
}
}
if("text".equals(colType)) {
... curs.getString(iCol-1);
} else
if("real".equals(colType)) {
... curs.getDouble(iCol-1);
} else
if("integer".equals(colType)) {
... curs.getInt(iCol-1);
} else { // unknown type
... colType+"-"+curs.getString(iCol-1);
}
}
}
Other information is available in a similar manner, depending on your need.
So I want to save an ordered set of double values, and I want to be able to insert, retrieve or delete any value from this easily. As of such, I'm using a an ArrayList, where I define a class called Doubles to store the double values.
How do I store this arraylist in a record in an SQLite database? I mean...what should the columns type be? Can it be done?
You cannot insert ArrayList directly into Sqlite. Instead, you could use JSONObject (org.json.JSONObject) to insert the ArrayList. Please check below snippet, you can try something like below....
To insert,
JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(items));
String arrayList = json.toString();
Insert the string into db.
To Read,
Read the string from db as String,
JSONObject json = new JSONObject(stringreadfromsqlite);
ArrayList items = json.optJSONArray("uniqueArrays");
To Insert :
ArrayList<String> inputArray=new ArrayList<String>();
Add Values to inputArray
Gson gson = new Gson();
String inputString= gson.toJson(inputArray);
System.out.println("inputString= " + inputString);
Use "inputString" to save the value of ArrayList<String> in SQLite Database
To retreive:
Get the String from the SQLiteDatabse what you saved and changed into ArrayList type like below:
outputarray is a String which is get from SQLiteDatabase for this example.
Type type = new TypeToken<ArrayList<String>>() {}.getType();
ArrayList<String> finalOutputString = gson.fromJson(outputarray, type);
In my case it was ArrayList of POJO classes Note
private String mNoteTitle;
private int mFingerIndex;
private Point mNoteCoordinates;
public Note(String noteTitle, int fingerIndex, Point noteCoordinates) {
this.mNoteTitle = noteTitle;
this.mFingerIndex = fingerIndex;
this.mNoteCoordinates = noteCoordinates;
}
As manual says JSONObject supports only following types: Object: a JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL, or null. May not be NaNs or infinities. So, I should break my Note class into supported objects.
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
for(Note note: chordShape.getNotes()){
JSONObject singleNoteJsonObject = new JSONObject();
try {
singleNoteJsonObject.put(SHAPE_NOTE_TITLE, note.getNoteTitle());
singleNoteJsonObject.put(SHAPE_NOTE_FINGER_INDEX, note.getFingerIndex());
singleNoteJsonObject.put(SHAPE_NOTE_X, note.getNoteCoordinates().x);
singleNoteJsonObject.put(SHAPE_NOTE_Y, note.getNoteCoordinates().y);
} catch (JSONException e){
e.printStackTrace();
}
jsonArray.put(singleNoteJsonObject);
}
Pack created array into JSONObject.
try {
json.put(SHAPE_NOTES, jsonArray);
Log.i(TAG, json.toString());
} catch (JSONException e){
e.printStackTrace();
}
Create String.
String notesList = json.toString();
Put created String in ContentValues, cause in my case it's Android app
if(notesList.length() > 0){
contentValues.put(DatabaseHelper.SHAPE_NOTES_LIST, notesList);
}
And when i should read values from SQLite database.
ArrayList<Note> notes = new ArrayList<>();
while(cursor.moveToNext()){
JSONObject jsonNotes = null;
try {
jsonNotes = new JSONObject(cursor.getString(cursor.getColumnIndex(DatabaseHelper.SHAPE_NOTES_LIST)));
} catch (JSONException e){
e.printStackTrace();
}
if(jsonNotes != null){
Log.i(TAG, jsonNotes.toString());
JSONArray jsonArray = jsonNotes.optJSONArray(SHAPE_NOTES);
for(int i = 0; i < jsonArray.length(); i++){
Note note = null;
JSONObject arrayObject = null;
try {
arrayObject = jsonArray.getJSONObject(i);
} catch (JSONException e){
e.printStackTrace();
}
if(arrayObject != null){
try {
note = new Note(
arrayObject.getString(SHAPE_NOTE_TITLE),
arrayObject.getInt(SHAPE_NOTE_FINGER_INDEX),
new Point(
arrayObject.getInt(SHAPE_NOTE_X),
arrayObject.getInt(SHAPE_NOTE_Y)
)
);
} catch (JSONException e){
e.printStackTrace();
}
}
if(note != null){
notes.add(note);
}
}
}
}
cursor.close();
I suggest going through all 3 Notepad tutorials you want to store the values your storing to a database table. you don't store the actual array directly into the database just the data. but you shouldn't actually need to use an array at all instead of adding a new item to the array instead call your db insert method
I've needed to do something similar in my application, where I have a custom class (Foo, Bar, etc.) and I have an ArrayList of foo, bar, etc. that I persist to SQL. My knowledge of SQL isn't strong, but I'll explain my approach here in case it helps.
My understanding is that to store any kind of object, you need to define a particular table for that object type, where the table has separate columns representing the primitive types within that object. Furthermore, to persist and retrieve an ArrayList of those objects, you'll use one table row per ArrayList entry, and iterate over in a loop to store and retrieve.
There are ArrayLists of several custom classes in my application that I wanted to persist to DB. So, to make things tidy (well, to me at least -- I'm still a relatively new Java / Android programmer, so take this with a pinch of salt) I decided to implement a kind of "SQL Serializable Interface" that my DB-persistable objects must implement. Each object (Foo, Bar, etc.) that can be persisted to DB must implement:
A public static final TABLE_NAME string, the name of the SQL DB table used for this object type.
A public static final TABLE_CREATE_STRING, a complete SQL instruction to create the table for this object.
A constructor method to populate its member variables from a ContentValues object.
A 'get' method to populate a ContentValues from its member variables.
So, say I have ArrayLists of objects Foo and Bar. When the DB is first created, within my DB helper class I call Foo.TABLE_CREATE_STRING, Bar.TABLE_CREATE_STRING, etc. to create the tables for those objects.
To populate my ArrayList, I use something like:
cursor = dbh.retrieve(Foo.TABLE_NAME);
if(!cursor.moveToFirst()){
return false
}
do{
DatabaseUtils.cursorRowToContentValues(cursor, vales);
FooArrayList.add( new Foo(values) );
} while( cursor.moveToNext() );
Create a dbHelper class which has an inner class and pretty much whatever the notepad tutorial says. The class must be having an insertion method somthing like this :-
public long insertRows(ContentValues values, String tableName) {
long val = myDatabase.insert(tableName, null, values);
return val;
}
This method will then add values into the table row.
After that you can call this method from your main activity and since you are using cursor i believe you will call the method in a for loop
for(i=0;list.length();i++) // or may be its list.size :P
{
// Call the method here
}
and keep adding value in the database by calling the method in for loop