How to validate range in android? - java

I'm new to Android programming and I'm currently developing an app. Can someone help me on how to validate the date that is being input by the user if is it in range 7 days?
so, i have two string 'startDay' and 'endDay' where user input
startDay = 1/2/2017
endDay = 6/2/2017
then it went on the next step. and if user input
startDay = 1/2/2017
endDay = 9/2/2017 then it return message 'maximum 7 days'
there is the code that i made
#Override
public void onClick(View v) {
if (v==btnSearch){
String startDaystr = startDay.getText().toString();
String startMonthtstr = startMonth.getText().toString();
String endDaystr = endDay.getText().toString();
String endMonthstr = endMonth.getText().toString();
String endYearstr = endYear.getText().toString();
if(Integer.valueOf(startDaystr) >1 && Integer.valueOf(endDaystr) < 8){
sharedPreferenceCustom = SharedPreferenceCustom.getInstance(getContext());
sharedPreferenceCustom.putSharedPref("startDay", startDaystr);
sharedPreferenceCustom.putSharedPref("startMonth",startMonthtstr);
sharedPreferenceCustom.putSharedPref("endDay",endDaystr);
sharedPreferenceCustom.putSharedPref("endMonth",endMonthstr);
sharedPreferenceCustom.putSharedPref("endYear",endYearstr);
startActivity(new Intent(getActivity(), activity_history.class));
}else{
Toast.makeText(getActivity(), "Maximum 7 days!", Toast.LENGTH_LONG).show();
}
}
}
but when im input
startDay = 22/2/2017
endDay = 25/2/2017
the result is 'maximum 7 days' it should be return to the next step
please help me..im searched and tried also but not get such a solution..

I added startYearStr, please note that.
Use below code :
String startDaystr = startDay.getText().toString();
String startMonthtstr = startMonth.getText().toString();
String startYearstr = startYear.getText().toString();
String endDaystr = endDay.getText().toString();
String endMonthstr = endMonth.getText().toString();
String endYearstr = endYear.getText().toString();
Calendar startDate = Calendar.getInstance();
startDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(startDaystr));
startDate.set(Calendar.MONTH, Integer.parseInt(startMonthtstr));
startDate.set(Calendar.YEAR, Integer.parseInt(startYearstr));
startDate.set(Calendar.HOUR_OF_DAY, 0);
startDate.set(Calendar.MINUTE, 0);
startDate.set(Calendar.SECOND, 0);
Calendar endDate = Calendar.getInstance();
endDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(endDaystr));
endDate.set(Calendar.MONTH, Integer.parseInt(endMonthstr));
endDate.set(Calendar.YEAR, Integer.parseInt(endYearstr));
endDate.set(Calendar.HOUR_OF_DAY, 0);
endDate.set(Calendar.MINUTE, 0);
endDate.set(Calendar.SECOND, 0);
long diff = endDate.getTimeInMillis() - startDate.getTimeInMillis();
long dayCount = diff / (24 * 60 * 60 * 1000);
dayCount gives you the day difference between two dates.

To compare dates you would want to use the Java Date or Calendar objects but reading in the initial dates from an EditText like you are doing wouldn't be safe. If you aren't validating the input, a user could enter in something like "February 2nd 2016" when you are expecting "2/2/2016" so you might want to change it from a freeform EditText to a date picker so you can control how the user inputs the dates first.
Once you have the two dates in a supported Java object you can compare them against each other. This answer has an example how to do the comparison.

Related

How to get values from array in strings.xml in order of each day?

I want to get values ​​from an array every day, respectively, and set these values ​​to a textbox. I can get values ​​from array and set them in textbox but next day value stays same. does not set the next value in array? what can I do?
<string-array name="morning">
<item>Good Morning. Message 1.</item>
<item>Good Morning. Message 2.</item>
<item>Good Morning. Message 3.</item>
</string-array>
mTestArray = getResources().getStringArray(R.array.morning);
preference_shared = this.getSharedPreferences("PREFERENCE", MODE_PRIVATE);
text_shared = this.getSharedPreferences("TEXT", MODE_PRIVATE);
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.DAY_OF_YEAR);
if (timeOfDay >= 0 && timeOfDay < 24) {
if (preference_shared.getBoolean("isFirstRun", true)) {
dailyGreetings.setText(mTestArray[(0) % (mTestArray.length)]);
saveDate();
}else {
if (!Objects.equals(preference_shared.getString("Date", ""), dateFormat.format(date))) {
int idx = new Random().nextInt(mTestArray.length);
dailyGreetings.setText(mTestArray[idx]);
text_shared.edit().putString("TEXT", dailyGreetings.getText().toString()).apply();
saveDate();
}
else {
dailyGreetings.setText(text_shared.getString("TEXT", ""));
}
}
}
It's Easy just
Resources res = getResources();
String[] mornings = res.getStringArray(R.array.morning);
//then use mornings as you use array.
String morning[] = getResources().getStringArray(R.array.morning);
// Solution
SharedPreferences sharedPreferences = getSharedPreferences("my_preference", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String currentDate = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault()).format(System.currentTimeMillis());
String[] msgArrays = getResources().getStringArray(R.array.morning);
String savedDate = sharedPreferences.getString(DATE_KEY, "");
int savedCounter = sharedPreferences.getInt(COUNTER_KEY, 0);
// First time
if (savedDate.isEmpty()) {
editor.putInt(COUNTER_KEY, savedCounter);
editor.putString(DATE_KEY, currentDate);
editor.apply();
} else if (!savedDate.equals(currentDate)) {
// New date appears, update shared preference.
savedCounter++;
if (savedCounter < msgArrays.length) {
editor.putInt(COUNTER_KEY, savedCounter);
editor.putString(DATE_KEY, currentDate);
editor.apply();
}
}
binding.tvTitle.setText(msgArrays[savedCounter]);
In this snipped of code, I'm updating shared preference by date and counter.
Date: It will be saved for next date, and if these both are not matching, shared preference will gets update with counter.
Counter: The position of your strings-arrays.
Reset: I have add another check that if in case your counter reaches to the end of array, it will be reset to '0'.

Finding out the closer time between two times

I wish to ask some question at Java. I have list of time (String) which i parsed from JSON data. I need to find which time is closer to system time. Its like this, now time is 16:40. And my time list contains
"16:32", "16:38", "16:44", "16:50" and so on. For 16:40, 16:38 is closer than 16:44 and i need to find this. I've tried to get current index and next index, parse them and initate new Calender and so on. But i cant figure out how can i do next.
Any solutions for this problem?
String returnTime = current.getDonus();
if (i < list.size() + 1) {
TimeList nextOne=list.get(i+1);
String nextReturnTime = nextOne.getDonus();
String[] parsedNextReturn = nextReturnTime.split(":");
String[] parsedReturn = returnTime.split(":");
Date date = new Date();
Calendar calNextReturn= Calendar.getInstance();
calNextReturn.setTime(date);
calNextReturn.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parsedNextReturn[0]));
calNextReturn.set(Calendar.MINUTE, Integer.parseInt(parsedNextReturn[1]));
calNextReturn.set(Calendar.SECOND, 0);
calNextReturn.set(Calendar.MILLISECOND, 0);
Calendar calCurrentReturn= Calendar.getInstance();
calCurrentReturn.setTime(date);
calCurrentReturn.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parsedReturn[0]));
calCurrentReturn.set(Calendar.MINUTE, Integer.parseInt(parsedReturn[1]));
calCurrentReturn.set(Calendar.SECOND, 0);
calCurrentReturn.set(Calendar.MILLISECOND, 0);
Calendar calSystem = Calendar.getInstance();
calSystem.setTime(date);
calSystem.set(Calendar.SECOND, 0);
calSystem.set(Calendar.MILLISECOND, 0);
}
Try this:
long smallestABS = Long.MAX_VALUE;
long systemTime = System.currentTimeMillis();
long timeClosest;
for (long time : timeList) {
long abs = Math.abs(systemTime - time);
if(smallestABS > abs){
smallestABS = abs;
timeClosest = time;
}
}

Take system time and convert to season to display information in Java

I am working on my first project in android studio using Java and have gotten lost. The app I am working on has a button (that works) that will go to a new activity. Depending on the user selection, I would like the new activity to display data by season. For example, if I click on NY and say submit, the new activity would show the New York Knicks if system time says it's fall, or Yankees in Spring, etc. The only problem is I have no idea where to start and google searching has led to nothing. I'm coming from Python and am basically just trying to teach myself more languages for better opportunities but haven't been that lucky in java. Any ideas?
I would do something like this :
public enum Season {
Winter,
Spring,
Summer,
Fall
}
public Season getSeason(int dayOfYear) {
// define "day of year" ranges for the northern hemisphere
final int DAY_SPRING_MIN = 80;
final int DAY_SPRING_MAX = 172;
final int DAY_SUMMER_MIN = DAY_SPRING_MAX;
final int DAY_SUMMER_MAX = 264;
final int DAY_FALL_MIN = DAY_SUMMER_MAX;
final int DAY_FALL_MAX = 355;
Season result = Season.Winter;
if (dayOfYear > DAY_SPRING_MIN && dayOfYear <= DAY_SPRING_MAX) {
result = Season.Spring;
} else if (dayOfYear > DAY_SUMMER_MIN && dayOfYear <= DAY_SUMMER_MAX) {
result = Season.Summer;
} else if (dayOfYear > DAY_FALL_MIN && dayOfYear <= DAY_FALL_MAX) {
result = Season.Fall;
}
return result;
}
and call it :
Calendar calendar = Calendar.getInstance();
int currentDayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
Log.e("Season", "current season : " + getSeason(currentDayOfYear));
I advice you to check my values by the way ^^

How do I search for a range of values in between two Strings in Java

First I know this is bad way to compare dates but I don't understand how to evaluate a strings to include the data between 2 values. For example in this code how would I list not only transactions that occurred on tdate 1 and 2 but also the transactions that fell between them.
tdate information is set up like 11/07/2013
System.out.println("Start Date: ");
tdate = in.next();
System.out.println("End Date: ");
tdate2 = in.next();
transactionSet trr = new transactionSet();
for(int idx = 0; idx < ts.getNumTrans(); idx++){
t = ts.retrieve(idx);
if (t.getTdate().equals(tdate) || t.getTdate().equals(tdate2)){
trr.insert(t);
}
}
SimpleDateFormat format = new SimpleDateFormat("d/M/yyyy"); // If this is the right format
Date first = format.parse(tdate);
Date second = format.parse(tdate2);
Date toCheck = format.parse(someDate);
if (toCheck.after(first) && toCheck.before(second)){
// ...
}
You might want to do this in a try/catch block, in case the dates that are input are not formatted correctly.

Using a for loop to find the difference between two time strings (hh:mm:ss)

I need to use a for loop, and arrays, to take two inputs and subtract them (input format hh:mm:ss). Then output the difference in a editText. But I can't seem to get to get my code to run.
Sorry if this is a really basic problem. I have spent days looking on the web trying to understand the problem. This is my first attempt at Java.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
end = (EditText) findViewById(R.id.etEnd);
start = (EditText) findViewById(R.id.etStart);
diff = (EditText) findViewById(R.id.etDiff);
calc = (Button) findViewById(R.id.bCalc);
clear = (Button) findViewById(R.id.bClear);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int hh = tot[0];
int mm = tot[1];
int ss = tot[2];
String sGet2 = end.getText().toString(); // end to string
String sGet1 = start.getText().toString(); // start to string
String[] erA = sGet2.split(":"); // end string to end array
String[] srA = sGet1.split(":"); // start string to string array
for (int i = 0; i < srA.length; i++) {
inted = Integer.parseInt(erA[i].trim());
intst = Integer.parseInt(srA[i].trim());
tot[i] = inted - intst;
if (i == 2) {
String mt = ":" + mm;
String st = ":" + ss;
String ht = ":" + hh;
String tota = mt + st;
String total = tota + ht;
out = String.format("%4.4s", total);
diff.setText(out);
} else
return;
It's not surprising your code doesn't work... a lot of it never executes!
for (int i = 0; i < srA.length; i++) {
// bla bla bla
if (i == 2) {
// This code never runs because i is always 0.
} else
return; // What is this doing here!?
}
If this is your first attempt at programming then I think you should start with something a little simpler such as a console program. Also use a debugger to step through the code so that you can see how the control flow works.
You might also want to buy a book that teaches Java. There are many good books you can use that start you off with the basics.
Great code why return in else part. it terminates the execution when i=0. That is as the for loop starts execution.
first time i value is zero and your condition i==2 fails then it execute else part so it terminaes the for loop. then what is the use of for loop?????
use the below code::
String time1 = "22:55:00";
String time2 = "23:05:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
difference is in millis you can convert it to any unit or you can use DurationFormatUtils from apache-commons to pretty format it.
System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm:ss"));
apache commons has really nice utility functions, apache-commons (lang)

Categories