How to retrieve database row in a soap web service? - android

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..

Related

SQLiteCommandBuilder returns error Dynamic SQL generation is not supported against a SelectCommand that does not return any base table information

can you please help me.
I have created a table and now I want to generate the Update command with SQLiteCommandBuilder.
But the Commandbuilder fails with
Dynamic SQL generation is not supported against a SelectCommand that does not return any base table information.
Im at a loss here, The Table has a primary key, and the Fill is working, giving me a Table with the 2 Fields. Its just the Commandbuilder thats failing me.
string extStorage = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
string ProjectPath = Path.Combine(extStorage, "DBTEST");
string dbFile = Path.Combine(ProjectPath, "TEST.DB");
if (!Directory.Exists(ProjectPath)) {
Directory.CreateDirectory(ProjectPath);
}
if (File.Exists(dbFile)) {
File.Delete(dbFile);
}
SqliteConnection.CreateFile(dbFile);
string my_Connection = string.Format("Data Source={0};Version=3;", dbFile);
try {
SqliteConnection my_DB_Con = new SqliteConnection(my_Connection);
my_DB_Con.Open();
SqliteCommand cmdCreate = new SqliteCommand("Create Table [T_RESULT] ( [LFDNR] int PRIMARY KEY not null, [TTT1] text);", my_DB_Con);
cmdCreate.ExecuteNonQuery();
SqliteCommand cmd = new SqliteCommand("select * from [T_RESULT]", my_DB_Con);
SqliteDataAdapter my_adapter = new SqliteDataAdapter(cmd);
DataSet ds = new DataSet();
my_adapter.Fill(ds, "T_RESULT");
SqliteCommandBuilder bld = new SqliteCommandBuilder(my_adapter);
my_adapter.Fill(ds);
my_adapter.UpdateCommand = bld.GetUpdateCommand(true);
string text = my_adapter.UpdateCommand.CommandText;
} catch (Exception exc) {
string t = exc.Message;
}
The Code throws at GetUpdateCommand.
The same Code works on Windows.
Can anyone help me here please.

too much time in reading sms from database and storing it in to text file

I'm reading sms record from database and write them into text file. But it takes too much time 3 to 4 mins to read n write 3500 records. If records are much more than that it takes plenty of time which is not appreciable. My code is:
final Cursor cur1 = c.getContentResolver().query(Uri.parse("content://sms/"), null, null, null, "date ASC");
final int size = cur1.getCount();
final int sleeptimer = size;
final SMS [] sms = new SMS[size];
final String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + "account.txt";
FileWriter fw = null;
try {
fw = new FileWriter(baseDir);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final BufferedWriter writer = new BufferedWriter(fw);
Thread myThread = new Thread()
{
public void run()
{
try
{
int currentwait = 0;
int j=0;
while(currentwait < sleeptimer)
{
sleep(200);
currentwait+=200;
for(int i = 0 ; i < 200 ; i++)
{
if(!cur1.moveToNext())
{
break;
}
ContactInfo p = new ContactInfo();
String content = cur1.getString(cur1.getColumnIndex("body"));
String number = cur1.getString(cur1.getColumnIndex("address"));
long date = cur1.getLong(cur1.getColumnIndex("date"));
String protocol = cur1.getString(cur1.getColumnIndex("protocol"));
String name = p.getName(number, c);
String type = null;
Calendar cal=Calendar.getInstance();
cal.clear();
cal.setTimeInMillis(date);
String date_time=String.format("%1$te %1$tB %1$tY,%1$tI:%1$tM:%1$tS %1$Tp",cal);
if( protocol == null )
{
type = "Outbox";
}
else
type = "Inbox";
try{
writer.write("Type: " + type);
writer.newLine();
writer.write("Name: " + number+"<"+name+">");
writer.newLine();
writer.write("Date: " + date_time);
writer.newLine();
writer.write("Content: " + content);
writer.newLine();
writer.newLine();
} catch (IOException e) {
Log.i("INFO", e.getMessage().toString());
}
//Log.i("INFO", content+" "+j);
sms[j] = new SMS(type , name , number , date_time , content );
j++;
}
}
}
catch(Exception e)
{
}
finally{
try{
writer.flush();
writer.close();
}
catch (Exception e) {
}
uploadtoserver(baseDir);
}
}
};
myThread.start();
any idea to improve it ???thanks :)))
Just remove this line:
sleep(200);
Call setMaxSqlCacheSize to increase the cache size. Default is 10. Try setting 20 first and see whether the time reduces to half..
Or/And
You can execute this sqlite query before performing any operation on db and see if that improves the speed. Changing the temp store to memory should improve the read write speed..
PRAGMA temp_store = 2; /* 0 | DEFAULT | 1 | FILE | 2 | MEMORY; */
When temp_store is MEMORY (2) temporary tables and indices are kept in as if they were pure in-memory databases memory
Also
PRAGMA page_size = bytes;
Query or set the page size of the database. The page size must be a power of two between 512 and 65536 inclusive.
Probably you can pass these statements either to execSQL(String sql) or to query(). Try and let me know how it works.
Check out other PRAGMAs that Sqlite supports: http://www.sqlite.org/
Update:
From documentation of query API:
For best performance, the caller should follow these guidelines:
Provide an explicit projection, to prevent reading data from storage that aren't going to be used.
Use question mark parameter markers such as 'phone=?' instead of explicit values in the selection parameter, so that queries that differ only by those values will be recognized as the same for caching purposes.

ORMLite select some columns using predicates

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

app not showing data when opend it for the second time

i am looking to make game of questions and answers.i had taken a textview and 4 radio group buttons.and i am fetching data from the external data file from the assets folder.when i installs the app into the emulater it works fine.when i reopens the app in the emulater it is just showing question not showing any text in the radio buttons.here is my code in the data base file
public String makeatext(String My_database_table,int i) {
SQLiteDatabase myDB = getDatabase();
String results = new String();
try {
String firstColumn = "questions";
// final String KEY_ROWID = "id";
// Cursor c = myDB.rawQuery("SELECT questions FROM " +
// My_database_table+ ";",null);
Cursor c = myDB.query(true, My_database_table,
new String[] { firstColumn },null, null, null, null, null,
null);
int iquestion = c.getColumnIndex(firstColumn);
if(c.moveToPosition(i)){
results = c.getString(iquestion)+"\n";
}
//while (c.moveToPosition(1)) {
//String firstName = c.getString(iquestion);
//results =(" "+ firstName + " ");
//}
return results;
} catch (Exception e) {
Log.e("ERROR","ERROR in Make test file :"+e.toString());
e.printStackTrace();
// TODO: handle exception
}
return results;
}
and in the Activity file i am just calling it as
String shoow = myDb.makeatext("question", Qno);
showQuestion.setText(shoow);
and on the top of the oncreate methode i initilized the data base asprivate final DataBaseHelper myDb = new DataBaseHelper(this);
can any one say me why this is happenig.do i need to write the for loop in the activity file also or shall i take a cursor in the activity class .
plz help me out
thanks in advance
for radio buttons the code in the database file is as follows as i have 4 buttons the code for 4 buttons will be as same as this
public String makeExtra1(String My_database_table ,int positions) {
String results = new String();
try {
String secondColumn = "Extra1";
Cursor c = myDataBase.query(true, My_database_table,
new String[] { secondColumn }, null, null, null, null, null,
null);
int iExtra1 = c.getColumnIndex(secondColumn);
if(c.moveToPosition(positions)){
results = results+c.getString(iExtra1)+"\n";
}
return results;
} catch (Exception e) {
Log.e("ERROR","ERROR in Make test file :"+e.toString());
e.printStackTrace();
// TODO: handle exception
}
return results;}
and in the Activity file
String showextra1 = myDb.makeExtra1("question", Qno);
r0.setText(showextra1);
i repeted this thing for 4 times as changing the makeExtra2,3,4 and in the assinged to r1,r2,r3 as above.
You should call Cursor.close() after reading data from it. Better to do it finally{} block.
If you want to raise only one answer per query - fill where param of myDataBase.query().
The unreachable code error is because you are writing finally{} block after return results;
Move this line after the finally{} block, eclipse will not give you any error.
Also do use myDB.close(); in this finally block.

to get resultset from pre-complie statement in android

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.

Categories

Resources