Cursor not returning any value,it is showing error? - android-sqlite

Am calling readPlaceName from TourGuideController, and passing the string in method readPlaceName(Placename), the cursor is showing null pointer exeception, not showing any values,Can any give solution for this error?
TourGuideController.java
public Cursor readPlaceName(String place_name){
String sql = "SELECT * FROM " + TourGuideDatabasehandler.VISTING_INBETWEEN_PLACES +
" WHERE "+ TourGuideDatabasehandler.PLACE_NAME + " = '" + place_name+"'";
Log.e("","Sql "+sql);
Cursor v = database.rawQuery(sql,null);
Log.e("v","Cursor v : "+v.toString());
return v;
}
MainActivity.java
protected void onPostExecute(Void result) {
super.onPostExecute(result);
int time = t_time;
TourGuideController dbcon = new TourGuideController(ourcontext);
System.out.println("dbcon"+dbcon+"temp_dbcon"+dbcon);
Log.e("OPEN","DB OPEN "+dbcon);
String place = "Juhu Beach";
Cursor cursors = dbcon.readPlaceName(place);
Log.e("dpopen", "cursor"+cursors);
Log.e("Updating cursor and cursor", DatabaseUtils.dumpCursorToString(cursors));
Integer wait_time = null;
while(cursors.moveToNext())
{
wait_time = Integer.parseInt(cursors.getString(8));
}
cursors.close();
String google_distance_time = "5";
Integer google_time = null;
google_time = Integer.parseInt(google_distance_time);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
LocalTime time1 = formatter.parseLocalTime(start_time);
System.out.println("wait_time"+wait_time);
int pred_time = (wait_time) + (google_time);
int get_total_time = (time)-(pred_time);
total_time = String.valueOf(get_total_time);
int addTimeMin = pred_time;
time1 = time1.plusMinutes(addTimeMin);
prediction_time = String.valueOf(time1);
dbcon.updateDateTime(place, start_date, start_time,google_distance_time,prediction_time,total_time);
Cursor cursor2 = dbcon.readPlaceName(place);
Log.e("Updating time and date", DatabaseUtils.dumpCursorToString(cursor2));
}
}}

Related

Is there a way to replace multiple keywords in a string and wrapping them with their own keyword?

Say I have a string:
typed = "need replace this ap"
str = "hello I need to replace this asap"
so the end result I want would be this:
newStr = "hello I <bold>need</bold> to <bold>replace</bold> <bold>this</bold> as<bold>ap</bold>"
please don't mind the weird syntax.
I wonder if the order would matter, for example:
typed = "applicable app"
str = "the app is very applicable in many applications"
The end result I wish should be:
newStr = "the <bold>app</bold> is very <bold>applicable</bold> in many <bold>app</bold>lications"
right? is this possible?
Hey,If You can ignore the weird HTML syntax here,
Then I have wrote a solution for you,
Paste this code in dart pad here
removeDuplicates(var typed, var str) {
Map<String, String> m = new Map<String, String>();
var n = typed.length;
String ans = "";
//for storing the "typed" string (word by word) into a map "m" variable for later searching purpose
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
m[temp] = temp;
temp = "";
} else {
temp = temp + typed[i];
}
}
//for storing the last word of the string "typed", coz loop will never find a space in last of the string
m[temp] = temp;
// map variable loop for search from map "m" in the "str" string, and matching if the word is present or not
var n2 = str.length;
String temp2 = "";
for (int j = 0; j < n2; j++) {
if (str[j] == " ") {
if (m.containsKey(temp2)) {
} else {
ans = ans + " " + temp2; //storing the "temp2" string into "ans" string, everytime it finds a space and if the string is not already present in the map "m"
}
temp2 = "";
} else {
temp2 = temp2 + str[j];
}
}
//for searching for the last word of the string "str" in map "m", coz loop will never find a space in last of the string,
if (m.containsKey(temp2)) {
} else {
ans = ans + " " + temp2;
}
return ans;
}
void main() {
String typed = "need replace this ap";
var str = "hello I need to replace this asap";
String answer = removeDuplicates(typed, str);
print(answer);
}
Here, I have made a method removeDuplicates() to simplify your work, You just have to pass those string in your method, and then it will return you the desired answer string by removing the duplicates, with a new string.
UPDATED CODE (TO SHOW HTML CODE):
removeDuplicates(var typed, var str) {
Map<String, String> m = new Map<String, String>();
var n = typed.length;
String ans = "";
//for storing the "typed" string (word by word) into a map "m" variable for later searching purpose
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
m[temp] = temp;
temp = "";
} else {
temp = temp + typed[i];
}
}
//for storing the last word of the string "typed", coz loop will never find a space in last of the string
m[temp] = temp;
print(m);
// map variable loop for search from map "m" in the "str" string, and matching if the word is present or not
var n2 = str.length;
String temp2 = "";
for (int j = 0; j < n2; j++) {
if (str[j] == " ") {
if (m.containsKey(temp2)) {
temp2 = "<bold>" + temp2 + "</bold> ";
ans = ans + " " + temp2;
} else {
ans = ans +
" " +
temp2; //storing the "temp2" string into "ans" string, everytime it finds a space and if the string is not already present in the map "m"
}
temp2 = "";
} else {
temp2 = temp2 + str[j];
}
}
//for searching for the last word of the string "str" in map "m", coz loop will never find a space in last of the string,
if (m.containsKey(temp2)) {
temp2 = "<bold>" + temp2 + "</bold> ";
temp2 = "";
} else {
ans = ans + " " + temp2;
temp2 = "";
}
return ans;
}
void main() {
var typed = "applicable app";
var str = "the app is very applicable in many applications";
String answer = removeDuplicates(typed, str);
print(answer);
}
UPDATE 2 (ALL THANKS TO PSKINK FOR THE str.replaceAllMapped APPROACH)
replaceWithBoldIfExists(String typed, String str) {
var n = typed.length;
List<String> searchList = new List<String>();
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
searchList.add(temp);
temp = "";
} else {
temp = temp + typed[i];
}
}
searchList.add(temp);
String pat = searchList.join('|');
final pattern = RegExp(pat);
final replaced =
str.replaceAllMapped(pattern, (m) => '<bold>${m.group(0)}</bold>');
return replaced;
}
void main() {
var typed = "need replace this ap";
var str = "hello I need to replace this asap";
print(replaceWithBoldIfExists(typed, str));
}

get_value of a feature in IFeatureCursor

I'm trying to read the attribute "POSTCODE" of the features in IFeatureCursor. The FID was successful read but the "POSTCODE" was failed. The runtime error 'An expected Field was not found or could not be retrieved properly. Appreciate your advise. Paul
private void test2(IFeatureCursor pFeatc1)
{
IFeature feature = null;
IFields pFields;
int ctcur = 0;
while ((feature = pFeatc1.NextFeature()) != null)
{
pFields = feature.Fields;
int indxid = pFields.FindField("FID");
int indxpost = pFields.FindField("POSTCODE");
object valu = feature.get_Value(indxid);
string valupost = feature.get_Value(indxpost);
string aValu = Convert.ToString(valu);
Debug.WriteLine("FID: " + aValu + " Postcode: " + valupost);
ctcur++;
feature = pFeatc1.NextFeature();
}
MessageBox.Show("count cursor = " + ctcur);
}
I have modified the program and successfully read the feature attribute 'POSTCODE'. I have added IFeatureClass.Search(queryFilter, true) to search the feature again by FID and save in a cursor then use the 'feature.get_Value' to read the attribute. Please see my updated code below. Thanks.
private void test2(IFeatureCursor pFeatc1)
{
IMxDocument mxdoc = ArcMap.Application.Document as IMxDocument;
IMap map = mxdoc.FocusMap;
IFeatureLayer flayer;
IMaps pMaps = mxdoc.Maps;
for (int i = 0; i <= pMaps.Count - 1; i++)
{
map = pMaps.get_Item(i);
IEnumLayer pEnumLayer = map.get_Layers(null, true);
pEnumLayer.Reset();
ILayer pLayer = pEnumLayer.Next();
while (pLayer != null)
{
if (pLayer.Name == "AddrKey")
{
Debug.WriteLine("Layer: " + pLayer.Name);
flayer = (IFeatureLayer)pLayer;
IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;
IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
IFeature feature = null;
IFields pFields;
while ((feature = pFeatc1.NextFeature()) != null)
{
pFields = feature.Fields;
int indx = pFields.FindField("FID");
object valu = feature.get_Value(indx);
string sFID = Convert.ToString(valu);
IQueryFilter queryFilter = new QueryFilter();
queryFilter.WhereClause = ("FID = " + sFID);
Debug.WriteLine("FID: " + sFID);
queryFilter.SubFields = "POSTCODE";
int fieldPosition = pFeatureClass.FindField("POSTCODE");
IFeatureCursor featureCursor = pFeatureClass.Search(queryFilter, true);
while ((feature = featureCursor.NextFeature()) != null)
{
MessageBox.Show(feature.get_Value(fieldPosition));
}
feature = pFeatc1.NextFeature();
}
}
pLayer = pEnumLayer.Next();
}
}
}

Postgresql update - Using ArrayList

I am getting an exception on update of postgres:
org.postgresql.util.PSQLException: Can't infer the SQL type...
Here is the code where in I build the sql statement dynamically and append the params:
public Boolean update(UserData usrData){
String sqlUpdateUser = "UPDATE \"USER\" ";
String sqlSetValues = "SET";
String sqlCondition = "Where \"USER_ID\" = ? ";
List<Object> params = new ArrayList<Object>();
List<Integer> types = new ArrayList<Integer>();
if(usrData.getFirstName() != null){
sqlSetValues = sqlSetValues.concat(" \"FIRST_NAME\" = ? ").concat(", ");
params.add(usrData.getFirstName());
types.add(Types.VARCHAR);
}
if(usrData.getMiddleName() != null){
sqlSetValues = sqlSetValues.concat("\"MIDDLE_NAME\" = ? ");
params.add(usrData.getMiddleName());
types.add(Types.VARCHAR);
}
params.add(usrData.getUserId());
types.add(Types.BIGINT);
Object[] updateParams = new Object[params.size()];
updateParams = params.toArray(updateParams);
Integer[] paramTypes = new Integer[types.size()];
paramTypes = types.toArray(paramTypes);
sqlUpdateUser = sqlUpdateUser.concat(sqlSetValues).concat(sqlCondition);
int rowsAffected = this.jdbcTemplate.update(sqlUpdateUser, updateParams, paramTypes);
if(rowsAffected > 0){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}
And table schema for the USER table is:
"FIRST_NAME" character varying(50),
"MIDDLE_NAME" character varying(50),
If I do an update statically without using the collection, but by using Array, I see no issue.
Code snipped using arrays:
Object[] param = { usrData.getFirstName(), usrData.getMiddleName(), usrData.getUserId() };
int[] type = { Types.VARCHAR, Types.VARCHAR, Types.BIGINT };
int rowsAffected = this.jdbcTemplate.update(sqlUpdateUser, param, type);
Am I missing something?
Thanks
K
Move these lines
Object[] updateParams = new Object[params.size()];
updateParams = params.toArray(updateParams);
Integer[] paramTypes = new Integer[types.size()];
paramTypes = types.toArray(paramTypes);
beneath
params.add(usrData.getUserId());
types.add(Types.INTEGER);
In your case you are missing to add usrData.getUserId() in updateParams.

Calling a function from onEdit() trigger doesn't work

I want to run a function that updates some values when I edit one cell of a column. This line of the trigger works well: dataCell0.setValue(today_date(new Date())[2]);. But this other line updatePercent(); doesn't. But if I call this updatePercent() function from a time based trigger (in Resources), it works well. What is going wrong with this updatePercent() call?
function onEdit(){
var s = SpreadsheetApp.getActiveSheet();
if( ( s.getName() == "mySheet1" ) || (s.getName() == "mySheet2") ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( s.getRange(1, r.getColumn()).getValue() == "PORCENT_TIME") { // If you type a porcent, it adds its date.
var dataCell0 = r.offset(0, 1);
dataCell0.setValue(today_date(new Date())[2]);
updatePercent();
}
}
}
Here the updatePercent function code:
/**
* A function to update percent values accoding to input date.
**/
function updatePercent() {
var sheet = SpreadsheetApp.getActiveSheet();
var column = getColumnNrByName(sheet, "PORCENT_TIME");
var input = sheet.getRange(2, column+1, sheet.getLastRow(), 4).getValues();
var output = [];
for (var i = 0; i < input.length; i++) {
var fulfilledPercent = input[i][0];
Logger.log("fulfilledPercent = " + fulfilledPercent);
var finalDate = input[i][3];
Logger.log("finalDate = " + input[i][3]);
if ( (typeof fulfilledPercent == "number") && (finalDate instanceof Date) ) {
var inputDate = input[i][1]; // Date when input was added.
var restPorcentPen = 100 - fulfilledPercent;
var restantDays = dataDiff(inputDate, finalDate);
var percentDay = restPorcentPen/restantDays;
Logger.log("percentDay = " + percentDay);
var passedTime = dataDiff(inputDate, new Date());
Logger.log("passedTime = " + passedTime);
var passedPorcent = passedTime * percentDay; // How much percent this passed time is?
Logger.log("passedPorcent = " + passedPorcent);
var newPorcent = (fulfilledPercent + passedPorcent);
newPorcent = Math.round(newPorcent * 100) / 100;
Logger.log("newPorcent = " + newPorcent);
var newInputDate = hoje_data(new Date())[2]; // Now update the new input date
// newPorcent = newPorcent.toFixed(2);
output.push([newPorcent, newInputDate]);
sheet.getRange(2, column+1, output.length, 2).setValues(output);
Logger.log(" ");
var column25Dec = getColumnNrByName(sheet, "PORCENT_25DEZ");
var passedTimeSince25Dec = dataDiff(new Date(2013,11,25), new Date()); // Months: January is 0;
var decPercent = (newPorcent - (passedTimeSince25Dec * percentDay)); // .toFixed(2).replace(".", ",");
decPercent = Math.round(decPercent * 100) / 100;
// if (sheet.getRange(output.length+1, column25Dec+1).getValues() == ''){
sheet.getRange(output.length+1, column25Dec+1).setValue(decPercent );
// }
var remainingYears = dataDiffYears(new Date(), finalDate);
sheet.getRange(output.length+1, column).setValue(remainingYears);
}
else {
newPorcent = "Put a final date"
output.push([newPorcent, inputDate]);
sheet.getRange(2, column+1, output.length, 2).setValues(output);
}
if (finalDate instanceof Date){
var remainingYears = dataDiffYears(new Date(), finalDate);
// Logger.log("remainingYears = " + remainingYears);
}
else {
remainingYears = "insert a valid date";
}
sheet.getRange(output.length+1, column).setValue(remainingYears);
}
}
I will guess you're using the new gSheets. Check if it will work in the old-style sheets. The new sheets' onEdit trigger has problems, particularly with getActive.
My problem was in the updatePercent() funciton. Thank you, guys!

twitter4j error - connect timed out

I am using the twitter4j code and I get connect timed out for making about 5 queries a day.
I am using twitter4j with a servlet and I get the error a lot with timeout.
What happens is that I run the code and the system provides the error when searching and hence the system stops and no more details are provided.
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try {
Query query = new Query(searchTerm);
twitter4j.QueryResult result1;
do {
result1 = twitter.search(query);
List<Status> tweets = result1.getTweets();
int i=0;int maxint = 20;
for (Status tweet : tweets) {
i++;
if (i<maxint)
{
out.println("procvess");
xmlStr=xmlStr+"<tweet>";
String tweetText = tweet.getText();
tweetText=cleanStringData(tweetText );
HashtagEntity[] hashtags = tweet.getHashtagEntities();
URLEntity[] urls = tweet.getURLEntities();
Date createdDate = tweet.getCreatedAt();
User twitteruser = tweet.getUser();
long tweetId = tweet.getId();
long id1 = tweet.getInReplyToStatusId();
long id2 = tweet.getInReplyToUserId();
String userImageURL = twitteruser.getProfileImageURL();
String userProfileURL = "http://twitter.com/"+twitteruser.getScreenName();
String realname = twitteruser.getName();
String authorname = twitteruser.getScreenName();
Calendar cal = Calendar.getInstance();
cal.setTime(createdDate);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String tweetDateStr = String.valueOf(year)+"/"+String.valueOf(month)+"/"+String.valueOf(day);
int l=0;
xmlStr=xmlStr+"</tweet>";
}
// System.out.println("#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
}
} while ((query = result1.nextQuery()) != null);
} catch (TwitterException te) {
te.printStackTrace();
out.println("Failed to search tweets: " + te.getMessage());
// return "<error>" + te.getMessage()+"</error>";
}