Load More Button Android with Limit and Offset - java

I have implemented a custom scroll view (not list view). Its using Intent Service to hit the server with offset and limit and display the result. For instance. i set offset = 0 and limit = FIRST_BATCH (int FIRST_BATCH = 15) for the first call. Its returning 15 names and details. And the next intent service call. I am using offset = FIRST_BATCH and limit = FIRST_BATCH. Its retuning next 15 names, from 15 to 30. And i am displaying Load More button at the end of 30 names. Here is my problem. Once i hit Load More button, i want to display the next 15 names, with offset = FIRST_BATCH + FIRST_BATCH and limit = FIRST_BATCH. And it will be growing more ..... Here is my implementation ....
private void startName(){
Intent getNameSearch = new Intent(getSherlockActivity(), IntentService.class);
getNameSearch.putExtra("search_offset", 0);
getNameSearch.putExtra("search_limit", FIRST_BATCH);
getNameSearch.setAction(IntentService.ACTION_GET_NAMESEARCH);
getSherlockActivity().startService(getNameSearch);
mCallback.onCreateProgressDialog();
getNameSearch = new Intent(getSherlockActivity(), IntentService.class);
getNameSearch.putExtra("search_offset", FIRST_BATCH);
getNameSearch.putExtra("search_limit", FIRST_BATCH);
getNameSearch.setAction(IntentService.ACTION_GET_NAMESEARCH);
getSherlockActivity().startService(getNameSearch);
mCallback.onCreateProgressDialog();
}
Once the view is displayed. I am loading the LoadMore Button. And once i click the LoadMore button i am calling the intent service again. But i know this is wrong. As the offset will be always 30 everytime. So the name will be displayed from 30 to 45 all the time. I want this to grow. Say, after i click LoadMore button. I want this to be 30 to 45 and Again hit the load More button, it should be 45 to 60 and goes on ...
final Button btnAddMore = (Button) myNameSearch.findViewById(R.id.loadMore);
btnAddMore.setVisibility(View.VISIBLE);
loadMoreButton = false;
btnAddMore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loadMoreButton();
}
});
And here is the loadMoreSpinner method
private void loadMoreButton(){
Intent getNameSearch = new Intent(getSherlockActivity(), IntentService.class);
int finalOffset = FIRST_BATCH * 2;
getNameSearch.putExtra("search_offset", finalOffset);
getNameSearch.putExtra("search_limit", FIRST_BATCH);
getNameSearch.setAction(IntentService.ACTION_GET_NAMESEARCH);
getSherlockActivity().startService(getNameSearch);
mCallback.onCreateProgressDialog();
}

Related

Open next Activity multiple times

I'm trying to modify the MLSeries pose detection code by Google, when it reached 3 squats it will open a new activity. But, after I edit the code and ran it, it open the new activity multiple times. How I can avoid the app to open the activity multiple times when it reached certain reps?
// Update {#link RepetitionCounter}s if {#code isStreamMode}.
if (isStreamMode) {
// Feed pose to smoothing even if no pose found.
classification = emaSmoothing.getSmoothedResult(classification);
// Return early without updating repCounter if no pose found.
if (pose.getAllPoseLandmarks().isEmpty()) {
result.add(lastRepResult);
return result;
}
for (RepetitionCounter repCounter : repCounters) {
int repsBefore = repCounter.getNumRepeats();
repsAfter = repCounter.addClassificationResult(classification);
if (repsAfter > repsBefore) {
// Play a fun beep when rep counter updates.
ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
tg.startTone(ToneGenerator.TONE_PROP_BEEP);
lastRepResult = String.format(
Locale.US, "%s : %d reps", repCounter.getClassName(), repsAfter);
break;
}
if (repsAfter == 3){
//simpan nilai timer dekat sini dulu
swstopw2();
tmClass.stopTimer();
stopwatcher.swstop();
context.startActivity(intent);
}
}
result.add(lastRepResult);
}

Progressbar not filled on API 19

I'm building a ProgressBar dynamically at Runtime, and the Progressar is not filled on API 19 only, it works on higher APIs, the green bar that represent the percentage does not appear.
Why it doesn't work on API 19 ?
private ProgressBar drawProgressBar(MatiereProgression mat) {
ProgressBar progress = new ProgressBar(mContext, null, R.style.Widget_AppCompat_ProgressBar_Horizontal);
LinearLayout.LayoutParams progressLayout = new LinearLayout.LayoutParams(0, dpToPx(4));
progressLayout.weight = 11;
progressLayout.gravity = Gravity.CENTER_VERTICAL;
progress.setLayoutParams(progressLayout);
progress.setIndeterminate(false);
progress.setMax(100);
progress.setMinimumHeight(0);
progress.setMinimumWidth(150);
progress.setProgress(mat.mProgress);
progress.setProgressDrawable(ContextCompat.getDrawable(mContext, R.drawable.progressbar));
return progress;
}
I found the bug, it was the last lines, on API 19 you need to care about the line order between "setProgressDrawable" and "setProgress", it worked for me.
progress.setLayoutParams(progressLayout);
progress.setIndeterminate(false);
progress.setMax(100);
progress.setProgressDrawable(ContextCompat.getDrawable(mContext, R.drawable.progressbar));
progress.setMinimumHeight(0);
progress.setMinimumWidth(150);
progress.setProgress(mat.mProgress);

java.text.ParseException: Unparseable date: "" (at offset 0) error for timepickerdialog

Hi this is my first time developing an simple Android-based application. I need to validate my starting time and ending time, which means ending time must not be less than or equal to starting time. I'm using an EditText to prompt a timepicker dialog. I had tried this code but it doesn't work, in terms of getting the error above at the line below
Date endTimeDate = format.parse(inputEndTime.getText().toString());
This is the whole code of the OnClickListener for EditText field to prompt out a timepicker dialog. I even tried to reverse the statements in if-else but it doesn't work for me too. Anyone can help me in this. Really thanks a lot!
inputEndTime.OnClickListener code:
inputEndTime.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
int hour = myTime.get(Calendar.HOUR_OF_DAY);
int min = myTime.get(Calendar.MINUTE);
TimePickerDialog myEndTimePickerDialog = new TimePickerDialog(ViewDocActivity.this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
try
{
Date startTimeDate = format.parse(inputTime.getText().toString());
Date endTimeDate = format.parse(inputEndTime.getText().toString());
if (startTimeDate.compareTo(endTimeDate) <= 0)
{
Context timeContext = getApplicationContext();
CharSequence text = "Please enter the correct end time";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(timeContext, text, duration);
toast.show();
}
else
{
inputEndTime.setText(String.format("%02d:%02d", hourOfDay, minute));
}
}
catch(ParseException e)
{
e.printStackTrace();
}
}
}, hour, min, true);
myEndTimePickerDialog.setTitle("Select Time");
myEndTimePickerDialog.show();
}
});
The reason for your error is, that you are trying to parse the time from your EditText (inputEndTime), but that is empty at the time you do the format.parse().
As you set this up, you have an EditText and a TimePickerDialog. Now you are implementing the TimePickerDialog.OnTimeSetListener#onTimeSet() method. Here you get the time, the user selected in the dialog via the hourOfDay and minute parameters of the method. At this point you have the time, but it not yet written in the EditText field itself.
So the simplest solution to get your code working would be to set that time in your EditText field before doing anything further. To do so, add the following line as the first line of the onTimeSet() method:
inputEndTime.setText(String.format("%02d:%02d", hourOfDay, minute));
This sets the picked time as text in the EditText field in a format that can then be parsed with format.parse(...) later on.
I think you has to format string before format to Date
Maybe trim().
Date startTimeDate = format.parse(inputTime.getText().toString().trim());
Date endTimeDate = format.parse(inputEndTime.getText().toString().trim());

Android Linkify - Clickable telephone numbers

So I am trying to add the functionality that when you click on a phone number it would take you to the Dialer app with the pre-populated number. I have the code below:
mContactDetailsText.setText(phonetextBuilder.toString());
Pattern pattern = Pattern.compile("[0-9]+\\s+[0-9]+");
Linkify.addLinks(mContactDetailsText, pattern, "tel:");
and the Text is currently "T. 0123 4567890"
The current outcome is just having the above string without it being clickable. I have even tried added the following line, but to no luck:
mContactDetailsText.setAutoLinkMask(0);
Anyone got any ideas or can see what I am doing wrong?
Thanks
The autolink mask needs to include a search for phone numbers:
mContactDetailsText.setAutoLinkMask(Linkify.PHONE_NUMBERS);
Then you'll need to set the links to be clickable:
mContactDetailsText.setLinksClickable(true);
You might also need movement method set like so:
mContactDetailsText.setMovementMethod(LinkMovementMethod.getInstance())
You should be able to accomplish what you want with the other answers,
but this will definitely work and will give you more control over the display of the text and what will happen when you click the number.
String text = "T. ";
StringBuilder stringBuilder = new StringBuilder(text);
int phoneSpanStart = stringBuilder.length();
String phoneNumber = "0123 4567890"
stringBuilder.append(phoneNumber);
int phoneSpanEnd = stringBuilder.length();
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + phoneNumber.replace(" ", "")));
startActivity(intent);
}
public void updateDrawState(TextPaint ds) {// override updateDrawState
ds.setUnderlineText(false); // set to false to remove underline
ds.setColor(Color.BLUE);
}
};
SpannableString spannableString = new SpannableString(stringBuilder);
spannableString.setSpan(clickableSpan, phoneSpanStart, phoneSpanEnd,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(spannableString);
myTextView.setMovementMethod(LinkMovementMethod.getInstance());
You need to set an onClickListener() on your TextViews. Then they will respond to clicks.

No Default Date in SWT DateTime

I'm using a SWT DateTime component. It sets the current date as a default selection, when instanciated. How can i prevent this?
I want that no date is selected at all...
Thanks
Patrick
The SWT DateTime control does not support this at all.
I recommend CalendarCombo from the Eclipse Nebula project.
If this is still of use to anyone - I had the same problem, meaning that a field on the UI had to show a date or an empty value: because a date that was NOT selected was also valid input.
While SWT DateTime has to show some sort of a date, it is not a problem at all introducing another level of indirection by simply making a label and a button - too look like DateTime: The then button calls DateTime in a separate modal window. After the user has made the selection, we write the result to the label back in the application window. You also add another button to the modal window and call it e.g. NONE. If the user clicks NONE, you clear the label field in your application.
You will see that I scrape the current value of the date from the label first, so that I can initialize the DateTime control in the modal dialog. This way it all behaves like a new composite control, though I admit it is a bit awkward if you need to do it many times over. E.g.:
private Button buttonDeadlineDate;
private Label labelDeadlineDate;
// ... then define your "composite" control:
lblNewLabel_5 = new Label(group_2, SWT.NONE);
lblNewLabel_5.setBounds(10, 14, 50, 17);
lblNewLabel_5.setText("Deadline:");
// We make our own composite date control out of a label and a button
// and we call a modal dialog box with the SWT DateTime and
// some buttons.
labelDeadlineDate = new Label(group_2, SWT.BORDER | SWT.CENTER);
labelDeadlineDate.setBounds(62, 10, 76, 20);
// Note that I use the strange font DokChampa because this was the only way to get a margin at the top.
labelDeadlineDate.setFont(SWTResourceManager.getFont("DokChampa", 8, SWT.NORMAL));
labelDeadlineDate.setBackground(SWTResourceManager.getColor(255, 255, 255)); // so it does appear editable
buttonDeadlineDate = new Button (group_2, SWT.NONE);
buttonDeadlineDate.setBounds(136, 11, 20, 20); // x - add 74, y - add 1 with respect to label
// ... And later we have the call-back from the listener on the little button above:
//========================================
// Deadline Date
//========================================
buttonDeadlineDate.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
// Define the dialog shell.
// Note: DIALOG_TRIM = TITLE | CLOSE | BORDER (a typical application dialog shell)
final Shell dialog = new Shell (shlTaskScheduler, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
dialog.setText("Enter deadline date (NONE for none)");
//========================================
// Position and size the dialog (relative to the application).
// could have probably also used a single call to dialog.setBounds()
// instead of calling setLocation() and setSize().
//========================================
Point myPoint = new Point(0,0);
myPoint = shlTaskScheduler.getLocation();
myPoint.x +=80; // myPoint.x +=30;
myPoint.y +=320; // myPoint.y +=350;
dialog.setLocation(myPoint);
dialog.setSize(270, 220);
dialog.setLayout (null);
//========================================
// Define dialog contents
//========================================
// Make controls final they it can be accessed from the listener.
final DateTime DTDeadlineDate;
DTDeadlineDate = new DateTime(dialog, SWT.BORDER | SWT.CALENDAR | SWT.DROP_DOWN);
DTDeadlineDate.setBounds(10, 10, 175, 175);
final Button buttonNone = new Button (dialog, SWT.PUSH);
buttonNone.setText ("NONE");
buttonNone.setBounds(200, 35, 55, 25);
final Button buttonOK = new Button (dialog, SWT.PUSH);
buttonOK.setText ("OK");
buttonOK.setBounds(200, 85, 55, 25);
//========================================
// Initialize the DateTime control to
// the date displayed on the button or today's date.
//========================================
// Get the deadline from the main application window
String newDeadlineDateString = (labelDeadlineDate.getText().toString());
myLogger.i (className, "got deadline from main application window as " + newDeadlineDateString);
// If deadline date found, use it to initialize the DateTime control
// else the DateTime control will initialize itself to the current date automatically.
if ((newDeadlineDateString.length() == 10) // probably unnecessary test
&& (isThisDateValid(newDeadlineDateString, "yyyy-MM-dd"))) {
// parse and extract components
try {
String tmpYearString= newDeadlineDateString.substring(0,4);
String tmpMoString = newDeadlineDateString.substring(5,7);
String tmpDayString = newDeadlineDateString.substring(8,10);
int tmpYearInt = Integer.parseInt(tmpYearString);
int tmpMoInt = Integer.parseInt(tmpMoString);
int tmpDayInt = Integer.parseInt(tmpDayString);
DTDeadlineDate.setYear(tmpYearInt);
DTDeadlineDate.setMonth(tmpMoInt - 1); // the control counts the months beginning with 0! - like the calendar
DTDeadlineDate.setDay(tmpDayInt);
} catch(NumberFormatException f) {
// this should not happen because we have a legal date
myScreenMessage.e(className, "Error extracting deadline date from screen <" + newDeadlineDateString + ">. Ignoring");
}
} else if (newDeadlineDateString.length() > 0) {
myLogger.w (className, "Illegal current deadline date value or format <" + newDeadlineDateString + ">. Ignoring.");
// no need to do anything, as the control will initialize itself to the current date
} else {
// no need to do anything, as the control will initialize itself to the current date
}
//========================================
// Set up the listener and assign it to the OK and None buttons.
// Note that the dialog has not been opened yet, but this seems OK.
//
// Note that we define a generic listener and then associate it with a control.
// Thus we need to check in the listener, which control we happen to be in.
// This is a valid way of doing it, as an alternative to using
// addListener() or
// addSelectionListener()
// for specific controls.
//========================================
Listener listener = new Listener () {
public void handleEvent (Event event) {
if (event.widget == buttonOK) {
int newDeadlineDay = DTDeadlineDate.getDay();
int newDeadlineMonth = DTDeadlineDate.getMonth() + 1; // the returned month will start at 0
int newDeadlineYear = DTDeadlineDate.getYear();
String selectedDeadlineDate = String.format ("%04d-%02d-%02d", newDeadlineYear, newDeadlineMonth, newDeadlineDay);
if (isThisDateValid(selectedDeadlineDate, "yyyy-MM-dd")) {
labelDeadlineDate.setText(selectedDeadlineDate);
} else {
// This is strange as the widget should only return valid dates...
myScreenMessage.e(className, "Illegal deadline date selected: resetting to empty date");
labelDeadlineDate.setText("");
}
} else if (event.widget == buttonNone) {
// an empty date is also an important value
labelDeadlineDate.setText("");
} else {
// this should not happen as there are no other buttons on the dialog
myLogger.e(className, "Unexpected widget state: ignoring");
}
// once a button is pressed, we close the dialog
dialog.close ();
}
};
// Still need to assign the listener to the buttons
buttonOK.addListener (SWT.Selection, listener);
buttonNone.addListener (SWT.Selection, listener);
//========================================
// Display the date dialog.
//========================================
dialog.open ();
//========================================
// If you need to do this - you can wait for user selection before returning from this listener.
// Note that this wait is not necessary so that the above button listeners
// can capture events, but rather so that we do not continue execution and end this
// function call before the user has made a date selection clicked on a button.
// Otherwise we would just go on.
while (!dialog.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
...
}
});
You would have to manually set the fields of the instance to 0 or null whatever is appropriate. You could also implement your own NoDateTime object (using the null object pattern) to accomplish the same thing. I would be tempted to represent no time with just null though, is there a reason why you cannot do that?
One Way is to set a selection listener like in this example on Eclipse-DOC
Here is an adapted version:
private boolean isModified = false;
selectDate = new DateTime(this, SWT.DATE | SWT.DROP_DOWN);
SelectionListener selListener = new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
isModified = true;
}
};
selectDate.addSelectionListener(selListener);
Then you can do an If isModified where needed.

Categories

Resources