MPAndroidChart can't show markerview if I add onTouchListener ,if I remove onTouchListener ,markview can show again - mpandroidchart

I'm using MPAndroidChart and it's very good ,but now I have a problem just like what I described . Besides, my onClick event can be triggered !

Try using the "onChartValueSelectedListener":
mChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
#Override
public void onValueSelected(Entry entry, int i, Highlight highlight) {
//display msg when value selected
if (entry == null)
return;
Toast.makeText(getActivity(), entry.getXIndex() + " = " + entry.getVal() + "%", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected() {
}
});

Related

How to return object from retrofit api get call

I am trying to get list of objects from api call with retrofit but i just cant find the way to do so :(
This is the function i built:
private List<Business> businesses getBusinesses()
{
List<Business> businessesList = new ArrayList<>();
Call<List<Business>> call = jsonPlaceHolderApi.getBusinesses();
call.enqueue(new Callback<List<Business>>() {
#Override
public void onResponse(Call<List<Business>> call, Response<List<Business>> response) {
if(!response.isSuccessful())
{
textViewResult.setText("Code: " + response.code());
return;
}
List<Business> businesses = response.body();
for(Business business : businesses)
{
String content = "";
content += "ID: " + business.getId() + "\n";
content += "Name: " + business.getName() + "\n";
content += "On promotion: " + business.isOnPromotion() + "\n\n";
textViewResult.append(content);
}
businessesList = businesses;
}
#Override
public void onFailure(Call<List<Business>> call, Throwable t) {
call.cancel();
textViewResult.setText(t.getMessage());
}
});
}
I am trying to get the businesses response and return it.
can anyone help me?
Feeling frustrated :(
The way your executing the Retrofit call is asynchronous - using call.enqueue. there's nothing wrong with this approach. In fact it's perhaps the best option, since network calls can take a while and you don't want to block unnecessarily.
Unfortunately, this means you cannot return the result from the function. In most scenarios, if you did, the call would likely finish after the return making your return useless.
There are several ways to deal with this, the simplest one is to use callbacks. For example:
interface OnBusinessListReceivedCallback {
void onBusinessListReceived(List<Business> list);
}
private void businesses getBusinesses(OnBusinessListReceivedCallback callback){
Call<List<Business>> call = jsonPlaceHolderApi.getBusinesses();
call.enqueue(new Callback<List<Business>>() {
#Override
public void onResponse(Call<List<Business>> call, Response<List<Business>> response) {
if(!response.isSuccessful()){
textViewResult.setText("Code: " + response.code());
return;
}
callback.onBusinessListReceived(response.body());
}
#Override
public void onFailure(Call<List<Business>> call, Throwable t) {
call.cancel();
textViewResult.setText(t.getMessage());
}
});
}
You can then call it like so:
getBusinesses(new OnBusinessListReceivedCallback() {
public void onBusinessListReceived(List<Business> list){
// list holds your data
}
});

Show a toast message when a text is recognized from camera

I am trying to detect a text with a specific format from a live camera feed and show a toast message when that text is detected automatically.
I was able to detect the text and put a box around it. But I'm having a hard time showing that toast message.
This is the receiveDetections method from the Processor
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
mGraphicOverlay.clear();
SparseArray<TextBlock> items = detections.getDetectedItems();
for (int i = 0; i < items.size(); ++i) {
TextBlock item = items.valueAt(i);
if (item != null && item.getValue() != null) {
Log.d("OcrDetectorProcessor", "Text detected! " + item.getValue());
// Check if it is the correct format
if (item.getValue().matches("^\\d{3} \\d{3} \\d{4} \\d{4}")){
OcrGraphic graphic = new OcrGraphic(mGraphicOverlay, item);
mGraphicOverlay.add(graphic);
// Show the toast message
}
}
}
}
-> Showing a toast is not my end goal, If I'm able to fix that I'll fix the main problem.
-> I'm building on top of the code labs tutorial for the text vision api
First pass context to OcrDetectorProcessor class from OcrCaptureActivity and runUiThread from that context. This piece of code show all text at once. If you want to show words one by one you need to split from TextBlock items.
Context context;
OcrDetectorProcessor(GraphicOverlay<OcrGraphic> ocrGraphicOverlay, Context context) {
mGraphicOverlay = ocrGraphicOverlay;
this.context = context;
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
mGraphicOverlay.clear();
final String result;
String detectedText = "";
SparseArray<TextBlock> items = detections.getDetectedItems();
for (int i = 0; i < items.size(); ++i) {
final TextBlock item = items.valueAt(i);
OcrGraphic graphic = new OcrGraphic(mGraphicOverlay, item);
mGraphicOverlay.add(graphic);
detectedText += item.getValue();
}
result = detectedText;
((OcrCaptureActivity)context).runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
}
});
}

JavaFX 8.0 - How can I get a MouseEventHandle at title bar

I have implemented a EventHandler which gets the window-drag of the mouse:
public void mouseEventHandler(){
final Delta dragDelta = new Delta();
view.getScene().setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
dragDelta.x = mainStage.getX() - mouseEvent.getScreenX();
dragDelta.y = mainStage.getY() - mouseEvent.getScreenY();
}
});
view.getScene().setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
mainStage.setX(mouseEvent.getScreenX() + dragDelta.x);
mainStage.setY(mouseEvent.getScreenY() + dragDelta.y);
stage.setX(mainStage.getX());
stage.setY(mainStage.getY() + view.getScene().getHeight() + 25);
}
});
}
I have two stages: mainStage and a stage, which is addicted to the coordinates of the mainStage. My problem is, that the stage only moves if I click in the window of the mainStage and drag it. But it won't move if I click the title bar of the window for removing.
How can I get the MouseEvent for the title bar?
Here is the show() method, so you can understand the Addiction:
public void show(Stage mainStage, MenuPresenter menuPresenter){
this.model = new Model();
this.view = new GameView(this.model);
this.chatWatchView = new ChatWatchView();
this.score = this.model.getScore();
this.menuPresenter = menuPresenter;
this.mainStage = mainStage;
mainStage.setScene(view.getScene());
mainStage.centerOnScreen();
stage = new Stage();
stage.setScene(chatWatchView.getScene());
stage.initStyle(StageStyle.UNDECORATED);
stage.setX(mainStage.getX());
stage.setY(mainStage.getY() + view.getScene().getHeight() + 25);
stage.show();
mainStage.show();
startTimeline();
activateEventHandler();
mouseEventHandler();
//view.setScore("Score: " + model.getScore());
}
Had similar problem. Consider to add listeners to xProperty() and yProperty() of your Stage, I think it will work better.
In my case I ended up with something like this
void updatePosition(double stageX, double stageY) {
//...
}
And then
stage.xProperty().addListener(((observable, oldValue, newValue) -> {
updatePosition(newValue, stage.getY())
}));
stage.yProperty().addListener(((observable, oldValue, newValue) -> {
updatePosition(stage.getX(), newValue)
}));

How to SuggestAppend a ComboBox containing a string

Goal
I'd like to have my ComboBox items suggest and append its items when something is contained in them, not just via the StartsWith function.
My ComboBox is bound to a DataView which contains clients [CompanyName], [Address], [City] in a long concatenation.
I want my users to be able to type in the city and still find the records which matches with all of the fields above. I know this is possible with Infragistics but I don't have that package.
Search Term: "Sher"
Costco, 123 1st Avenue, Sherbrooke
Provigo, 344 Ball Street, Sherbrooke
Sherbox, 93 7th Street, Montreal
Is this possible in VB.Net or should I be searching for something else?
I did some research and found the following question:
Override Winforms ComboBox Autocomplete Suggest Rule
In that question they reffer to another question:
C# AutoComplete
Let's quote the best answer from that question
The existing AutoComplete functionality only supports searching by
prefix. There doesn't seem to be any decent way to override the
behavior.
Some people have implemented their own autocomplete functions by
overriding the OnTextChanged event. That's probably your best bet.
For example, you can add a ListBox just below the TextBox and set
its default visibility to false. Then you can use the OnTextChanged
event of the TextBox and the SelectedIndexChanged event of the
ListBox to display and select items.
This seems to work pretty well as a rudimentary example:
public Form1()
{
InitializeComponent();
acsc = new AutoCompleteStringCollection();
textBox1.AutoCompleteCustomSource = acsc;
textBox1.AutoCompleteMode = AutoCompleteMode.None;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
private void button1_Click(object sender, EventArgs e)
{
acsc.Add("[001] some kind of item");
acsc.Add("[002] some other item");
acsc.Add("[003] an orange");
acsc.Add("[004] i like pickles");
}
void textBox1_TextChanged(object sender, System.EventArgs e)
{
listBox1.Items.Clear();
if (textBox1.Text.Length == 0)
{
hideResults();
return;
}
foreach (String s in textBox1.AutoCompleteCustomSource)
{
if (s.Contains(textBox1.Text))
{
Console.WriteLine("Found text in: " + s);
listBox1.Items.Add(s);
listBox1.Visible = true;
}
}
}
void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
hideResults();
}
void listBox1_LostFocus(object sender, System.EventArgs e)
{
hideResults();
}
void hideResults()
{
listBox1.Visible = false;
}
There's a lot more you could do without too much effort: append text
to the text box, capture additional keyboard commands, and so forth.
Improved the technique demonstrated by BenD in his answer so as to have the mechanism handle a bit more elegantly certain cornercases:
public sealed class CCComboboxAutocomplete : ComboBox
{
public CCComboboxAutocomplete()
{
AutoCompleteMode = AutoCompleteMode.Suggest; //crucial otherwise exceptions occur when the user types in text which is not found in the autocompletion list
}
protected override void OnTextChanged(EventArgs e)
{
try
{
if (DesignMode || !string.IsNullOrEmpty(Text) || !Visible) return;
ResetCompletionList();
}
finally
{
base.OnTextChanged(e);
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
try
{
if (DesignMode) return;
if (e.KeyChar == '\r' || e.KeyChar == '\n')
{
e.Handled = true;
if (SelectedIndex == -1 && Items.Count > 0 && Items[0].ToString().ToLowerInvariant().StartsWith(Text.ToLowerInvariant()))
{
Text = Items[0].ToString();
}
DroppedDown = false;
return; //0
}
BeginInvoke(new Action(ReevaluateCompletionList)); //1
}
finally
{
base.OnKeyPress(e);
}
}
//0 Guardclose when detecting any enter keypresses to avoid a glitch which was selecting an item by means of down arrow key followed by enter to wipe out the text within
//1 Its crucial that we use begininvoke because we need the changes to sink into the textfield Omitting begininvoke would cause the searchterm to lag behind by one character That is the last character that got typed in
private void ResetCompletionList()
{
_previousSearchterm = null;
try
{
SuspendLayout();
var originalList = (object[])Tag;
if (originalList == null)
{
Tag = originalList = Items.Cast<object>().ToArray();
}
if (Items.Count == originalList.Length) return;
while (Items.Count > 0)
{
Items.RemoveAt(0);
}
Items.AddRange(originalList);
}
finally
{
ResumeLayout(performLayout: true);
}
}
private string _previousSearchterm;
private void ReevaluateCompletionList()
{
var currentSearchterm = Text.ToLowerInvariant();
if (currentSearchterm == _previousSearchterm) return; //optimization
_previousSearchterm = currentSearchterm;
try
{
SuspendLayout();
var originalList = (object[])Tag;
if (originalList == null)
{
Tag = originalList = Items.Cast<object>().ToArray(); //0
}
var newList = (object[])null;
if (string.IsNullOrEmpty(currentSearchterm))
{
if (Items.Count == originalList.Length) return;
newList = originalList;
}
else
{
newList = originalList.Where(x => x.ToString().ToLowerInvariant().Contains(currentSearchterm)).ToArray();
}
try
{
while (Items.Count > 0) //1
{
Items.RemoveAt(0);
}
}
catch
{
try
{
Items.Clear();
}
catch
{
}
}
Items.AddRange(newList.ToArray()); //2
}
finally
{
if (currentSearchterm.Length >= 2 && !DroppedDown)
{
DroppedDown = true; //3
Cursor.Current = Cursors.Default; //4
Text = currentSearchterm; //5
Select(currentSearchterm.Length, 0);
}
ResumeLayout(performLayout: true);
}
}
//0 backup original list
//1 clear list by loop through it otherwise the cursor would move to the beginning of the textbox
//2 reset list
//3 if the current searchterm is empty we leave the dropdown list to whatever state it already had
//4 workaround for the fact the cursor disappears due to droppeddown=true This is a known bu.g plaguing combobox which microsoft denies to fix for years now
//5 Another workaround for a glitch which causes all text to be selected when there is a matching entry which starts with the exact text being typed in
}
Sorry for another answer in C# but I have a more improved answer based on xDisruptor's code.
Using kinda behavior (decorator).
You don't have to subclass ComboBox and change all existing combos in the designed.
Be careful when using Datasource instead of Items collection, because it'll raise an exception.
Code:
public class AutoCompleteBehavior
{
private readonly ComboBox comboBox;
private string previousSearchterm;
private object[] originalList;
public AutoCompleteBehavior(ComboBox comboBox)
{
this.comboBox = comboBox;
this.comboBox.AutoCompleteMode = AutoCompleteMode.Suggest; // crucial otherwise exceptions occur when the user types in text which is not found in the autocompletion list
this.comboBox.TextChanged += this.OnTextChanged;
this.comboBox.KeyPress += this.OnKeyPress;
this.comboBox.SelectionChangeCommitted += this.OnSelectionChangeCommitted;
}
private void OnSelectionChangeCommitted(object sender, EventArgs e)
{
if (this.comboBox.SelectedItem == null)
{
return;
}
var sel = this.comboBox.SelectedItem;
this.ResetCompletionList();
this.comboBox.SelectedItem = sel;
}
private void OnTextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(this.comboBox.Text) || !this.comboBox.Visible || !this.comboBox.Enabled)
{
return;
}
this.ResetCompletionList();
}
private void OnKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r' || e.KeyChar == '\n')
{
e.Handled = true;
if (this.comboBox.SelectedIndex == -1 && this.comboBox.Items.Count > 0
&& this.comboBox.Items[0].ToString().ToLowerInvariant().StartsWith(this.comboBox.Text.ToLowerInvariant()))
{
this.comboBox.Text = this.comboBox.Items[0].ToString();
}
this.comboBox.DroppedDown = false;
// Guardclause when detecting any enter keypresses to avoid a glitch which was selecting an item by means of down arrow key followed by enter to wipe out the text within
return;
}
// Its crucial that we use begininvoke because we need the changes to sink into the textfield Omitting begininvoke would cause the searchterm to lag behind by one character That is the last character that got typed in
this.comboBox.BeginInvoke(new Action(this.ReevaluateCompletionList));
}
private void ResetCompletionList()
{
this.previousSearchterm = null;
try
{
this.comboBox.SuspendLayout();
if (this.originalList == null)
{
this.originalList = this.comboBox.Items.Cast<object>().ToArray();
}
if (this.comboBox.Items.Count == this.originalList.Length)
{
return;
}
while (this.comboBox.Items.Count > 0)
{
this.comboBox.Items.RemoveAt(0);
}
this.comboBox.Items.AddRange(this.originalList);
}
finally
{
this.comboBox.ResumeLayout(true);
}
}
private void ReevaluateCompletionList()
{
var currentSearchterm = this.comboBox.Text.ToLowerInvariant();
if (currentSearchterm == this.previousSearchterm)
{
return;
}
this.previousSearchterm = currentSearchterm;
try
{
this.comboBox.SuspendLayout();
if (this.originalList == null)
{
this.originalList = this.comboBox.Items.Cast<object>().ToArray(); // backup original list
}
object[] newList;
if (string.IsNullOrEmpty(currentSearchterm))
{
if (this.comboBox.Items.Count == this.originalList.Length)
{
return;
}
newList = this.originalList;
}
else
{
newList = this.originalList.Where(x => x.ToString().ToLowerInvariant().Contains(currentSearchterm)).ToArray();
}
try
{
// clear list by loop through it otherwise the cursor would move to the beginning of the textbox
while (this.comboBox.Items.Count > 0)
{
this.comboBox.Items.RemoveAt(0);
}
}
catch
{
try
{
this.comboBox.Items.Clear();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
this.comboBox.Items.AddRange(newList.ToArray()); // reset list
}
finally
{
if (currentSearchterm.Length >= 1 && !this.comboBox.DroppedDown)
{
this.comboBox.DroppedDown = true; // if the current searchterm is empty we leave the dropdown list to whatever state it already had
Cursor.Current = Cursors.Default; // workaround for the fact the cursor disappears due to droppeddown=true This is a known bu.g plaguing combobox which microsoft denies to fix for years now
this.comboBox.Text = currentSearchterm; // Another workaround for a glitch which causes all text to be selected when there is a matching entry which starts with the exact text being typed in
this.comboBox.Select(currentSearchterm.Length, 0);
}
this.comboBox.ResumeLayout(true);
}
}
}
Usege:
new AutoCompleteBehavior(this.comboBoxItems);
this.comboBoxItems.Items.AddRange(new object[] { "John", "Tina", "Doctor", "Alaska" });
TIP: Can be further improved by making an extension to the ComboBox class like myCombo.ToAutoComplete()
A ComboBox,TextBox and I think a DropDownList has AutoComplete properties
Look at http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.autocompletemode(v=vs.110).aspx
It explains which AutoCompleteMode you should use and how to set the AutoCompleteSource
You could try the following lines, it worked for me
cbxName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
cbxName.AutoCompleteSource = AutoCompleteSource.ListItems;

How to send Keys.Tab as a parameter to a function

I have a code as below:
void someFunc(){
driver.findElement(By.xpath(OR.getProperty("Nodes_AddNodeDescriptionInput"))).sendKeys(Keys.TAB);
}
which sends a key Tab to the xPath mentioned.
But i want to avoid driver...details in that someFunc(), so I want to have a code which replaces the above code with the below one.
if(!sendKeyboardKeysByXpath("Nodes_AddNodeDescriptionInput", Keys.TAB)) {
printError("Failed to send the Tab key.");
return(false);
}
Def for sendKeyboardKeysByXpath:
public static boolean sendKeyboardKeysByXpath(String xPathKey, CharSequence... textToType) {
printLogs("Calling sendKeyboardKeysByXpath with values: " + xPathKey + ", " + textToType);
try {
printLogs("Typing '"+ textToType + "' to " + xPathKey);
if(!checkElementPresenceByXpath(xPathKey)) {
printFunctionReturn(fn_fail);
return(false);
}
driver.findElement(By.xpath(OR.getProperty(xPathKey))).clear();
driver.findElement(By.xpath(OR.getProperty(xPathKey))).sendKeys(textToType);
}
catch(Throwable t) {
ErrorUtil.addVerificationFailure(t);
printError("sendKeysByXpath: Exception occurred while typing keys.");
printFunctionReturn(fn_fail);
return(false);
}
return(true);
}
How to send the Keys.Tab as a parameter. I am getting garbage value in sendKeyboardKeysByXpath function
Use Keys.TAB.name() it will write TAB
So in your log method it would be textToType.name()