Related
My job is to maintain an application that is essentially a database for another application. the application uses ORM GreenDao.
Here is StorageUtil.getResults method which processes queries:
public static JSONArray getResults(Database database, String query) {
Cursor cursor = database.rawQuery(query, null);
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
if (cursor.getString(i) != null) {
if (isJSONValid(cursor.getString(i))) {
try {
JSONObject object = new JSONObject(cursor.getString(i));
rowObject.put(cursor.getColumnName(i), object);
}catch (JSONException e){
Logger.error(e);
}
} else {
rowObject.put(cursor.getColumnName(i), cursor.getString(i));
}
} else {
rowObject.put(cursor.getColumnName(i), "");
}
} catch (Exception e) {
Logger.error(e);
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
return resultSet;
}
Here is code of one of my entities:
#Entity(nameInDb = "UI_SV_FIAS")
#Storage(description = "FIAS", table = "UI_SV_FIAS")
public class Fias {
#Id
public String LINK;
#Property(nameInDb = "F_Street")
public String F_Street;
#Property(nameInDb = "C_Full_Address")
#Index
public String C_Full_Address;
#Property(nameInDb = "C_House_Number")
public String C_House_Number;
#Property(nameInDb = "C_Building_Number")
public String C_Building_Number;
public Fias() {
}
#Generated(hash = 1534843169)
public Fias(String LINK, String F_Street, String C_Full_Address,
String C_House_Number, String C_Building_Number) {
this.LINK = LINK;
this.F_Street = F_Street;
this.C_Full_Address = C_Full_Address;
this.C_House_Number = C_House_Number;
this.C_Building_Number = C_Building_Number;
}
Problem: the table has about 2,500,000 rows and when I get a query, for example, like this one:
http://localhost:8888/table?name=UI_SV_FIAS&query=select * from UI_SV_FIAS where C_Full_Address LIKE '%Чеченская%' ORDER BY C_House_Number, C_Full_Address limit 10
my app returns results in more then 10 seconds. But what I need is less then 3 seconds for such query.
Does anyone have an idea how can I get that?
Try this:
public static JSONArray getResults(Database database, String query) {
Cursor cursor = database.rawQuery(query, null);
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
String columnName = cursor.getColumnName(i);
if (columnName != null) {
try {
String columnValue = cursor.getString(i);
if (columnValue != null) {
if (isJSONValid(columnValue)) {
try {
JSONObject object = new JSONObject(columnValue);
rowObject.put(columnName, object);
}catch (JSONException e){
Logger.error(e);
}
} else {
rowObject.put(columnName, columnValue);
}
} else {
rowObject.put(columnName, "");
}
} catch (Exception e) {
Logger.error(e);
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
return resultSet;
}
JSON is only displaying the last object '100 g' of "serving_description" in the JSON Formatted Data, See below. instead of all of the "serving_description" objects.
The Array is serving
If you look at the JSON Formatted Data below you will see that there are multiple "serving_description" 's.
I am trying to get the "serving_description" of all of the the available options to display instead of the last object in which it is displaying. How do I display all of the "serving_descriptions"?
I believe the error lies in, but I can be wrong, that is why I am asking :
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object.getString("serving_description");
Log.v("FATSEC", "" + shit);
ret = shit + "";
}
Class, AsyncTask
#Override
public void onClick(View v) {
new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... arg0) {
search = (EditText) findViewById(R.id.editText1);
String SEARCH = search.getText().toString();
JSONObject food = getFood(SEARCH);
Log.v("FATSEC", "TEST");
String ret = "";
try {
JSONArray foodName = food.getJSONObject("food")
.getJSONObject("servings")
.getJSONArray("serving");
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object
.getString("serving_description");
Log.v("FATSEC", "" + shit);
ret = shit + "";
}
} catch (JSONException e) {
e.printStackTrace();
}
return ret;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// ans.setText("# of Servings: " + result);
ans.setText("Servings: " + result);
}
}.execute();
}
});
Formatted JSON DATA
{
"servings":{
"serving":[
{
"vitamin_a":"0",
"calcium":"2",
"serving_description":"1 cup cooked",
"vitamin_c":"0",
"carbohydrate":"44.08",
"metric_serving_unit":"g",
"fat":"0.44",
"sodium":"577",
"polyunsaturated_fat":"0.119",
"fiber":"0.6",
"cholesterol":"0",
"iron":"10",
"serving_id":"16834",
"protein":"4.20",
"monounsaturated_fat":"0.138",
"potassium":"55",
"number_of_units":"1.000",
"calories":"204",
"measurement_description":"cup, cooked",
"saturated_fat":"0.120",
"metric_serving_amount":"158.000",
"sugar":"0.08",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=16834&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"6",
"serving_description":"1 cup, dry, yields",
"vitamin_c":"0",
"carbohydrate":"159.03",
"metric_serving_unit":"g",
"fat":"1.60",
"sodium":"2080",
"polyunsaturated_fat":"0.429",
"fiber":"2.3",
"cholesterol":"0",
"iron":"38",
"serving_id":"15284",
"protein":"15.16",
"monounsaturated_fat":"0.497",
"potassium":"200",
"number_of_units":"1.000",
"calories":"735",
"measurement_description":"cup, dry, yields",
"saturated_fat":"0.432",
"metric_serving_amount":"570.000",
"sugar":"0.29",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=15284&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"1 oz, dry, yields",
"vitamin_c":"0",
"carbohydrate":"24.27",
"metric_serving_unit":"g",
"fat":"0.24",
"sodium":"318",
"polyunsaturated_fat":"0.065",
"fiber":"0.3",
"cholesterol":"0",
"iron":"6",
"serving_id":"18252",
"protein":"2.31",
"monounsaturated_fat":"0.076",
"potassium":"30",
"number_of_units":"1.000",
"calories":"112",
"measurement_description":"oz, dry, yields",
"saturated_fat":"0.066",
"metric_serving_amount":"87.000",
"sugar":"0.04",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=18252&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"1 serving (105 g)",
"vitamin_c":"0",
"carbohydrate":"29.30",
"metric_serving_unit":"g",
"fat":"0.29",
"sodium":"383",
"polyunsaturated_fat":"0.079",
"fiber":"0.4",
"cholesterol":"0",
"iron":"7",
"serving_id":"17592",
"protein":"2.79",
"monounsaturated_fat":"0.092",
"potassium":"37",
"number_of_units":"1.000",
"calories":"135",
"measurement_description":"serving (105g)",
"saturated_fat":"0.080",
"metric_serving_amount":"105.000",
"sugar":"0.05",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=17592&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"100 g",
"vitamin_c":"0",
"carbohydrate":"27.90",
"metric_serving_unit":"g",
"fat":"0.28",
"sodium":"365",
"polyunsaturated_fat":"0.075",
"fiber":"0.4",
"cholesterol":"0",
"iron":"7",
"serving_id":"53181",
"protein":"2.66",
"monounsaturated_fat":"0.087",
"potassium":"35",
"number_of_units":"100.000",
"calories":"129",
"measurement_description":"g",
"saturated_fat":"0.076",
"metric_serving_amount":"100.000",
"sugar":"0.05",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=53181&portionamount=100.000"
}
]
},
"food_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular",
"food_type":"Generic",
"food_name":"White Rice",
"food_id":"4501"
}
Use + to append all serving_description value in ret as:
ret += shit + "\n\n";
Each iteration of the loop overrides the value of ret so that you are never able to accumulate them. For this reason, when you return it has the last value you stored there and none of the previous values that were wiped out. Consider using a StringBuilder.
StringBuilder builder = new StringBuilder();
...
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object.getString("serving_description");
Log.v("FATSEC", "" + shit);
builder.append(shit).append("\n");
}
...
return builder.toString();
I am having a problem with the above task in my android application. I am accepting user input from the EditText widget in the form of String. I accepting numbers from the user so I have to parse them to integers so they can be compared with another array of integers. I have the line:
String message = editText.getText().toString()
then to try and parse the String to an int I have the code line:
int userNumbers = Integer.parseInt(message).
However when I attempt to compare the array userArray with the array numbers I am getting the error that "Incompatible operand types String and Integer.
Can anyone see where my problem is or how I can solve it? Here's my code:
Thanks in advance.
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = ".com.example.lotterychecker.MESSAGE";
static boolean bonus = false;
static boolean jackpot = false;
static int lottCount = 0;
Button check;
Integer [] numbers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//link to the intended web site and get the lottery numbers while the app is opening
try {
Document doc = Jsoup.connect("http://www.national-lottery.co.uk/player/p/drawHistory.do").userAgent("Mozilla").get();
Elements elements = doc.getElementsByClass("drawhistory");
Element table = elements.first();
Element tbody = table.getElementsByTag("tbody").first();
Element firstLottoRow = tbody.getElementsByClass("lottorow").first();
Element dateElement = firstLottoRow.child(0);
System.out.println(dateElement.text());
Element gameElement = firstLottoRow.child(1);
System.out.println(gameElement.text());
Element noElement = firstLottoRow.child(2);
System.out.println(noElement.text());
String [] split = noElement.text().split(" - ");
// set up an array to store numbers from the latest draw on the lottery web page
Integer [] numbers = new Integer [split.length];
int i = 0;
for (String strNo : split) {
numbers [i] = Integer.valueOf(strNo);
i++;
}
for (Integer no : numbers) {
System.out.println(no);
}
Element bonusElement = firstLottoRow.child(3);
Integer bonusBall = Integer.valueOf(bonusElement.text());
System.out.println("Bonus ball: " + bonusBall);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//called when the user clicks the send button
public void checkNumbers(View view) {
final int SIZE =6;
String [] userArray = new String[SIZE];
//create an intent to display the numbers
Intent intent = new Intent(this, DisplayNumbersActivity.class);
EditText editText = (EditText) findViewById(R.id.enter_numbers);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message );
startActivity(intent);
//parse string message to an int for user numbers
try{
int userNumbers = Integer.parseInt(message); //is this right?
}//try
catch (NumberFormatException e)
{
System.out.println("Not a number" + e.getMessage());
}
Toast.makeText(MainActivity.this, "Here are your numbers", Toast.LENGTH_LONG).show();
for (int count =0; count < SIZE; count ++)
{
if (check.isPressed())
{
userArray[count] = editText.getText().toString();
}
}//for
//compare the two arrays of integers
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (userArray[loop] == numbers[loopOther]) //how do I parse this?
{
lottCount++;
}else if (userArray[loop] == bonus)
{
bonus = true;
}
}//for
}//for main
You have this
Integer [] numbers; // numbers is an integer array
You have string array
String [] userArray = new String[SIZE]; // userArray is a string array
You compare like below
if (userArray[loop] == numbers[loopOther])
So you get the error Incompatible operand types String and Integer.
try
if (Integer.parseInt(userArray[loop]) == numbers[loopOther])
Enclosing the above with try catch block
String message = editText.getText().toString();
try{
int userNumbers = Integer.parseInt(message);
//is this right? yes
}
catch (NumberFormatException e)
{
e.printStacktrace();
}
Change String to Int here:
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (Integer.valueOf(userArray[loop]) == numbers[loopOther]) //how do I parse this?
{
lottCount++;
}else if (Integer.valueOf(userArray[loop]) == bonus)
{
bonus = true;
}
}//for
}//for main
Parse Like this :
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (Integer.parseInt(userArray[loop]) == numbers[loopOther])
{
lottCount++;
}else if (userArray[loop] == bonus)
{
bonus = true;
}
}
}
I have a JSON loop and I am able to get objects in the loop, but the problem is my output is not in order:
My expected output is:
Menu Id 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
but I get results like:
Menu Id: 19,18,23,16,17,14,15,12,13,21,20,22,4,3,11,2,1.
How can I sort this the way I expect?
JSONArray values = menuObject.toJSONArray(names);
for (int i = 0; i< values.length(); i++) {
JSONObject json2 = (JSONObject) values.getJSONObject(i);
//int menu_id = json2.getInt("menu_id");
menu_id = json2.getString("menu_id");
int m_id = Integer.parseInt(menu_id);
if (json2.has("menu_parent")) {
menu_parent = json2.getString("menu_parent");
}
if (m_id < 0) {
//
} else {
id = id + menu_id + ",";
int menu_category = Integer.parseInt(menu_parent);
System.out.println("Menu Id" + id);
if (json2.has("menu_name")) {
menu_list = json2.getString(KEY_MENU).trim();
System.out.println("Menu List" +menu_title);
menu_title = menu_title + menu_list + ",";
}
}
}
I think you can get it sorted this way:
Collections.sort("your data", new Comparator<Item>() {
public int compare(Item i1, Item i2) {
return i1.getCaption().compareTo(i2.getCaption());
}
});
After this is done, it should be sorted out.
Try this:
String menuids = "19,18,23,16,17,14,15,12,13,21,20,22,4,3,11,2,1";
String[] ids = menuids.split(",");
Integer[] result = new Integer[ids.length];
for (int i = 0; i < ids.length; i++) {
result[i] = Integer.parseInt(ids[i].trim());
}
Collections.sort(Arrays.asList(result));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++) {
Integer intValue = result[i];
sb.append(intValue);
if (i < result.length - 1) {
sb.append(", ");
}
}
String finaldata = sb.toString();
System.out.println(finaldata);
I have written Update table using dbAdapter.
public void loadDownloadData() {
SoapPrimitive responsePrimitiveData;
//Loop Table list
for (int i = 0; i < tablesName.size(); i++) {
try {
responsePrimitiveData = soapPrimitiveData(tablesName.get(i));
if (responsePrimitiveData != null) {
try {
String result = responsePrimitiveData.toString();
JSONObject jsonobject = new JSONObject(result);
JSONArray array = jsonobject.getJSONArray("Table1");
int max = array.length();
// Loop each table data
for (int j = 0; j < max; j++) {
JSONObject obj = array.getJSONObject(j);
JSONArray names = obj.names();
StringBuilder strFields = new StringBuilder();
StringBuilder strValues = new StringBuilder();
String[] strToFields = new String[names.length()];
String[] strToFieldsVal = new String[names.length()];
//getting the Json name, values in separate string array
for (int k = 0; k < names.length(); k++) {
String name = names.getString(k);
strToFields[k] = names.getString(k);
String strVal;
if(obj.getString(name)== null){
strVal="";
strToFieldsVal[k]="";
}else{
if(obj.getString(name).equals(" ")){
strVal="";
strToFieldsVal[k]="";
}else{
String tmp1 = obj.getString(name).replaceAll("\\s+", " ");
String tmp = tmp1.replaceAll("\\s+", " ");
strVal =tmp.replaceAll("\\s+", " ");
strToFieldsVal[k]=strVal;
}
}
strFields.append(name + ",");
strValues.append(strVal+",");
} //end of json for loop
strFields.deleteCharAt(strFields.length() - 1);
strValues.deleteCharAt(strValues.length() - 1);
if(getTableUpdateType(tablesName.get(i)).equals("1")){
String actualtable = getAndroidTablename(tablesName.get(i));
if(isTableRecords(tablesName.get(i))){
String[] strWhereField = getTablePrimaryKey(tablesName.get(i),strBusinessUnit);
String[] strWhereFieldVal = new String[strWhereField.length];
StringBuilder whereFields = new StringBuilder();
for (int a = 0; a < strWhereField.length; a++) {
strWhereFieldVal[a] = obj.getString(strWhereField[a]);
whereFields.append(strWhereField[a] + "= ? and ");
}
whereFields.delete(whereFields.length() - 4, whereFields.length());
updateTableRecords(actualtable, strToFields, strToFieldsVal,whereFields.toString() ,strWhereFieldVal);
}else{
insertTableRecords(actualtable, strToFields, strToFieldsVal);
}
}else if(getTableUpdateType(tablesName.get(i)).equals("2")){
}else if(getTableUpdateType(tablesName.get(i)).equals("3")){
}else{
}
}//end of each table data
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
and I called like update method:
public void updateTableRecords(String strTableName, String[] strToFields, String[] strValues,String strWhereField ,String[] strWhereFieldVal){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(DownlaodTableActivity.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
for(int i=0 ;i<strToFields.length;i++){
initialValues.put(strToFields[i],strValues[i]);
}
long n = dbAdapter.updateRecordsInDB(strTableName, initialValues, strWhereField, strWhereFieldVal);
System.out.println( " -- n--- " + n);
Toast.makeText(DownlaodTableActivity.this, n+" rows updated", Toast.LENGTH_SHORT).show();
}
I want to generate update statement dynamic way. From These code I put Where part also.But I did not generate where clause.
see :
UPDATE strTableName SET ExecutiveCode=?, FreeIssuePrefix=?, DisPaySchedulePrefix=?, NextFreeIssueNo=?, NextReturnNo=?, UploadedType=?, DisNextFOCNo=?, DisNextFreeIssueNo=?
Please help me How to give the Where clase(Here I gave String & arguments as string array)
Thanks in advance...
try like this
dbAdapter.updateRecordsInDB(strTableName, initialValues,""+whereField+"='"+whereFieldValue+"'",null);
if your whereField field's type is number then don't use ''
If you have to compare with multiple values use
String where="";
for(int i=0;i<strWhereField.length();i++)
{
where=where+whereField[i]+"='"+strWhereFieldValue[i]+"'"
if(i<(strWhereField.length()-1)) where=where+" and"
}
dbAdapter.updateRecordsInDB(strTableName, initialValues,where,null);