I tried to do to fetch the data's between from and to dates.
I did it on sql lite,it works and
I tried in android coding part,it doesn't work,could you guys please help
protected void adddata1() throws ParseException {
Database db=new Database(Reportmonth.this);
SQLiteDatabase sb=db.getReadableDatabase();
String a=from.getText().toString();
String b=to.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date a1=sdf.parse(a);//convert string to date
Date b1=sdf.parse(b);//convert string to date
Cursor cus=sb.rawQuery("select * from expenz where daty between '" + a1 +"' AND '"+b1+"'",null);
cus.moveToFirst();
for(int i=0;i<cus.getCount();i++)
{
if(cus!=null) //i think the error starts from this onwards.
{
soi.setText(cus.getString(0));
Log.i("",cus.getString(0));
desc.setText(cus.getString(3));
dat.setText(cus.getString(1));
woc.setText(cus.getString(2));
amount.setText(cus.getString(5));
adddata();
search.setClickable(false);
}
cus.moveToNext();
}
}
It is not advisable to store date in database as varchar as when it comes to situation like yours, its a real pain
Still below I have shown a work around, where you can extract all data from the table, convert the date column in the table from string to Date object and then do your comparison. But this will hit the performance a lot specially when the rows in your database is really high.
//For storing the rows that are in between the date range
ArrayList<HashMap<String, String>> rowList = new ArrayList<HashMap<String, String>>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//Important that the date should be in the same format as specified above
Date startDate = sdf.parse(a);//convert string to date
Date endDate = sdf.parse(b);//convert string to date
Cursor cus = sb.rawQuery("select * from expenz",null);
if (cursor.moveToFirst()) {
do {
try {
//Converting the database `varchar date` to `Date` object here
//Here cursor.getString(X) should be the column number of your daty column
//And also the date format in the database should also be same as "yyyy-MM-dd"
Date thisDate = sdf.parse(cursor.getString(X));
// Check if the database date is within the range
if (thisDate.after(startDate) && thisDate.before(endDate)) {
HashMap<String, String> map = new HashMap<String, String>();
//Here have the number of columns you want to have according to your database
map.put("column0", cursor.getString(0));
map.put("column1", cursor.getString(1));
map.put("column2", cursor.getString(2));
map.put("column3", cursor.getString(3));
map.put("column4", cursor.getString(4));
map.put("column5", cursor.getString(5));
rowList.add(map);
}
} catch (ParseException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
}
// Now here the rowList will have the rows between the specified date range
You could modify the inner most if loop to meet your requirements.
I hope it helps!
Related
I have a table that store two variables Days and percent’s. I want to assign them to a specific variable. From the Database Helper class, I’m getting the last 7 entries:
//----------------Graping the last seven elements ----------------------------------//
public ArrayList<StatsitcsHelper> GetWeaklyPrograss() {
SQLiteDatabase db = this.getReadableDatabase ();
Cursor cursor = db.rawQuery ("select * from " + TABLE_PROGGRES, null);
ArrayList<StatsitcsHelper> datas = new ArrayList<>();
if (cursor != null) {
cursor.moveToFirst ();
for (int i = cursor.getCount () - 7 ; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
StatsitcsHelper data = new StatsitcsHelper();
data.WeakleyDate= cursor.getString(cursor.getColumnIndex(COL_P_Date));
data.WeakleyPercent = cursor.getInt (cursor.getColumnIndex(COL_P_Percentage));
datas.add(data);
cursor.moveToNext ();
}
cursor.close ();
}
return datas;
}
I want to build if statement that will say if day is Saturday then assign Saturday Percent Variable is Statistics Class to the percent associated from the database. Same goes for Sunday ….etc.
Inside the Statistics Class:
public void WeaklyStatstics(){
int saturday = 0,
sunday = 0,
monday = 0,
tuesday = 0,
wednsday = 0,
thersday = 0,
friday = 0;
StatsitcsHelper statsitcsHelper = new StatsitcsHelper ();
DatabaseHelper databaseHelper = new DatabaseHelper (getActivity ());
//---------------------TO DO----------------------------------------//
}}
I don’t know how to analysis each item from the list in the database to another class.
Here is the Insertion of the Table:
// ----------------Proggres Table ------------------------------------//
public boolean insertPrograss(String Date, Integer percentage) {
SQLiteDatabase db = this.getWritableDatabase ();
ContentValues contentValues = new ContentValues ();
contentValues.put (COL_P_Date, Date);
contentValues.put (COL_P_Percentage, percentage);
long result = db.insert (TABLE_PROGGRES, null, contentValues);
db.close ();
return result != -1;
}
the method is called by scheduler that will store the date into just day by using date formate, and the output will be Monday, 87.
i want to write a method to get the last 7 inputs through GetWeaklyPrograss method. and assign it to the variables something like this
if(statsitcsHelper.WeakleyDate.equals ("monday")){
saturday = statsitcsHelper.WeakleyPercent;
}
and here is the statsitcsHelper:
public class StatsitcsHelper {
//-------------- Weakly Progress -----------------------/
public String WeakleyDate;
public int WeakleyPercent;
}
can you try this logic ,
public void WeaklyStatstics(){
int saturday = 0,
sunday = 0,
monday = 0,
tuesday = 0,
wednsday = 0,
thersday = 0,
friday = 0;
//StatsitcsHelper statsitcsHelper = new StatsitcsHelper ();
DatabaseHelper databaseHelper = new DatabaseHelper (getActivity());
ArrayList<StatsitcsHelper> statsitcsHelperList = databaseHelper.GetWeaklyPrograss();
for (StatsitcsHelper statsitcsHelper : statsitcsHelperList)
{
if(statsitcsHelper.WeakleyDate.equals("Monday")){
monday = statsitcsHelper.WeakleyPercent;
}else if (statsitcsHelper.WeakleyDate.equals("Tuesday")){
tuesday = statsitcsHelper.WeakleyPercent;
}
//todo and write for other days too
}
// In here you can use all valid data
}
I am not sure I understand what the problem is.
However to check the day of week, you can get some ideas from this:
check if date() is monday? java
On a side note:
Your cursor contains all of the data in the table! It is usually better to get the results you want (last seven elements) on your cursor.
Limit your DB query, down to the interesting data. Instead of taking all data from the DB (select * from), you should specialize your query.
Look for SQL expressions ORDER BY, ASC, DESC, LIMIT, and you will get there.
i want to sort my data as par desc date in local cloudant query.
i have insert_ts in my database document.
my code for simple query is:-
public List<BasicDocumentMAP> allTasksWithAllArg(Map<String, Object> query, int skip, int limit, List<String> fields, List<Map<String, String>> sortDocument) {
int nDocs = this.sunDatastore.getDocumentCount();
QueryResult all = this.im.find(query, skip, limit, fields, sortDocument);
List<BasicDocumentMAP> arrayListBasicDocumentMAP = new ArrayList<>();
// Filter all documents down to those of type Task.
for (DocumentRevision rev : all) {
}}
please help me to sort data as date wise. thank you
Try this code:
Sql query :
Select _id , _rev , insert_ts , title from table
where year=2010 order by insert_ts
Cloudant query :
{
"selector": {
"year": {
"$gt": 2010
}
},
"fields": ["_id", "_rev", "insert_ts", "title"], //
"sort": [{"insert_ts": "asc"}]
}
Update: The original answer (at the bottom) shows you how to sort by year (OP asked how to get the year, so I assumed that was how they wanted to sort). This is how to sort by date:
Either change the insert_ts field to be a date, or add a new field that is a date, for example:
Date insertTsDate = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss-SS");
try {
insertTsDate = dateFormat.parse(insert_ts);
}
catch (Exception e) {
// handle exception
}
Then add a new field to your document called insert_ts_date (or whatever you want to call it), set it to the insertTsDate variable above, and sort like so:
List<Map<String, String>> sortDocument = new ArrayList<Map<String, String>>();
Map<String, String> sortByInsertTsDate = new HashMap<String, String>();
sortByInsertTsDate.put("insert_ts_date", "asc");
sortDocument.add(sortByInsertTsDate);
Original Answer:
I think you are going to have to explicitly add a year property to your document. If you have the year then just add it to your document. If you need to parse it from the string you can use regex or the Date/Calendar classes to parse the date:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss-SS");
try {
Date date = dateFormat.parse(insert_ts);
Calendar c = Calendar.getInstance();
c.setTime(date);
int year = c.get(Calendar.YEAR);
}
catch (Exception e) {
// handle exception
}
Then issue your query as follows:
List<Map<String, String>> sortDocument = new ArrayList<Map<String, String>>();
Map<String, String> sortByYear = new HashMap<String, String>();
sortByYear.put("year", "asc");
sortDocument.add(sortByYear);
I am trying to select the max date using the ORMLITE lib:
GenericRawResults<Object[]> result = null;
try {
String sql = "select MAX(t.last_updated_on_server_utc) from measurements t";
result = databaseManager.getMeasurementDao().queryRaw(
sql, new DataType[]{DataType.DATE_LONG}
);
List<Object[]> results = result.getResults();
if (results.size() == 0) {
return null;
} else {
Date d = (Date) results.get(0)[0];
// Date d = new Date((Long) results.get(0)[0]);
Log.d(TAG, "d=" + d);
}
} catch (SQLException e) {
}
The date returned is always 1970-01-01 (i.e the value of d in the debug output)...That field is declared as a java.util.Date. I also tried using DataType.LONG, and still the same. If I use a raw query to select one of the date columns it's fine, my problem is when I use MAX().
I have an array which having time ranges like below,
String[] str ={"6.30 AM","6.10 AM","10.00 PM","7.00 PM"};
i want to get the minimum time and maximum time in above array such as "6.10 AM" and "10.00 PM".i can find out using sorting but it takes long time.Is any other method avail.Guide me,Below i sorted like,
String[] str ={"1:0 PM","2:0 AM","3:0 PM",.....};
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa", Locale.getDefault());
Date TimeToCompare = null,Time1 = null;
for(int i=0;i<10;i++)
{
TimeToCompare=sdf.parse(str[i]);
for(int j=i+1;j<10;j++)
{
Time1=sdf.parse(str[j]);
if(TimeToCompare.after(Time1))
{
//sorting
}
}
}
This solution makes one pass through the array, keeping track of the min and max times. Runs in O(n).
double maxTime = 0.0;
double minTime = 0.0;
for(String s : str) {
String[] parts = str.split(" ");
double time = Double.parse(parts[0]);
if (parts[1].equals("PM")) {
time += 12;
}
if (time > maxTime) {
maxTime = time;
}
if (time < minTime) {
minTime = time;
}
}
// convert doubles back into strings and print
Date-Time Values
When working with date-time values, it's usually best to work with them as date-time values.
Parse the strings as date-time values, collect them, sort the collection, and retrieve the first and last elements in collection to get earliest & latest values. Convert back to strings if needed.
Joda-Time & java.time
You can easily parse the strings to create date-time objects.
However avoid using the bundled java.util.Date & .Calendar classes in Java as they are notoriously troublesome. Furthermore, they always combine date and time-of-day while in your case you have only a time-of-day.
Use either Joda-Time or the new java.time package in Java 8. Both offer a day-of-time only class, LocalTime.
Example Code
Example code using Joda-Time 2.3.
Convert your array to Collection as I prefer to not work with arrays.
String[] strings = { "6.30 AM", "6.10 AM", "10.00 PM", "7.00 PM" };
List<String> stringList = Arrays.asList( strings );
Create an empty collection to collect our LocalTime objects as we instantiate them.
List<LocalTime> localTimes = new ArrayList<>();
Create a formatter to parse your particular string format. By the way, if you can change the source of these strings, I suggest creating strings in 24-hour format without the "AM/PM", akin to the standard ISO 8601 format.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "h'.'mm aa" );
Loop through our collection of strings, parsing each one. Store the new LocalTime instance in a collection.
for ( String string : stringList ) {
LocalTime localTime = formatter.parseLocalTime( string );
localTimes.add( localTime );
}
Sort the collection of LocalTime objects, to determine the earliest and latest.
Collections.sort( localTimes ); // Ascending order. Earliest first, latest last.
Retrieve the earliest and latest.
LocalTime earliest = localTimes.get( 0 );
LocalTime latest = localTimes.get( localTimes.size() - 1 );
Dump to console.
System.out.println( "localTimes: " + localTimes );
if ( !( localTimes.isEmpty() ) ) {
System.out.println( "earliest: " + formatter.print( earliest ) );
System.out.println( "latest: " + formatter.print( latest ) );
}
When run…
localTimes: [06:10:00.000, 06:30:00.000, 19:00:00.000, 22:00:00.000]
earliest: 6.10 AM
latest: 10.00 PM
Here's a sample solution picked from ggreiner #
How to sort a list of time strings in Java or Groovy
String[] str ={"6.30 AM","6.10 AM","10.00 PM","7.00 PM"};
List<String> times = Arrays.asList(str); // convert int to list
Collections.sort(times, new MyComparator()); // use a custom comparator
Log.i("Min time is ",""+times.get(0));
Log.i("Max Time is ",""+times.get(times.size()-1));
Custom Comparator
class MyComparator implements Comparator<String>
{
private DateFormat primaryFormat = new SimpleDateFormat("h.mm a");
#Override
public int compare(String time1, String time2){
return timeInMillis(time1) - timeInMillis(time2);
}
public int timeInMillis(String time){
return timeInMillis(time, primaryFormat);
}
// in milliseconds
private int timeInMillis(String time, DateFormat format) {
Date date = null ;
try {
date = format.parse(time); //
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (int)date.getTime();
}
}
// Try this way,hope this will help you to solve your problem.
String[] str =new String[]{"6.30 AM","6.10 AM","10.00 PM","7.00 PM"};
ArrayList<Double> list = new ArrayList<Double>();
HashMap<Double,String> map = new HashMap<Double, String>();
for (int i=0;i<str.length;i++){
list.add(Double.parseDouble(str[i].split(" ")[0]));
map.put(Double.parseDouble(str[i].split(" ")[0]),str[i]);
}
System.out.println("Min >> " +map.get(Collections.min(list)));
System.out.println("Max >> "+map.get(Collections.max(list)));
Can you use these, But you may need some pre-arragments
Collections.max(arrayList);
Collections.min(arrayList);
Depending on how you're originally filling the array of values, like are you getting the long from the system then you could compare those. Or create an class that holds the value part and the AM or PM seperately like a flag or something, so then sort between AM and PM then values. I dabbled a lot with java date and calendars, and just use JodaTime. It's convenient!
I am new to the android world and have a problem with an id. What i need is that when the user clicks on new match it will insert a new row into the db. This is working and i get the lastId but now i need this id in the next activities. How can i store that id so i can use it elsewhere?
This is how i insert the new match:
public void newMatch(WedstrijdenGeschiedenis wedstrijd){
// 1.
SQLiteDatabase db = this.getWritableDatabase();
// 2.
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
ContentValues values = new ContentValues();
values.put(KEY_DATUM, dateFormat.format(date)); // get datum
// 3.
long lastId = db.insert(TABLE_WEDSTRIJD, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
Log.d("New Match","ID ="+lastId);
// 4. close
db.close();
}
so i see the lastId in LogCat but i don't know how to store it for further use. I tried void but offcourse that is not possible on void. Sorry for the dummy question
change void to long and add a return statement that returns the lastId
public long newMatch(WedstrijdenGeschiedenis wedstrijd){
// Your other code
return lastId;
}
Access it with:
long lastId= db.newMatch(new WedstrijdenGeschiedenis());