Is there a way wait for code to take effect before a "notify" method is called (E.G. notifyItemRangeInserted) on a Recycler view? - android-recyclerview

I want to show a progress dialog screen in my app whenever a recycler view begins to load more items. The problem is: I can't get to show the dialog screen because the notify method is ALWAYS executed (and freezes the screen) before the loading screen shows up. Happens even if the "show()" method for it is called in the very first line of my "addContacts()" method.
I've already tried:
getActivity().runOnUiThread();
creating a Thread, starting it, calling join()
starting it with executors
public void addContactsToScreen() {
((BaseActivity) lcf.getActivity()).showProgressDialog();
try {
int currentSize = contactsLoaded.size();
int inserted;
for (inserted = 0;
inserted < DEFAULT_ITEM_INSERTION
&& inserted < lcf.getController().getContacts().size()
&& contactsLoaded.size() < lcf.getController().getContacts().size()
; inserted++) {
contactsLoaded.add(lcf.getController().getContacts().get(currentSize + inserted));
}
if (inserted > 0) {
notifyItemRangeInserted(contactsLoaded.size() - 1, inserted);
}
lcf.getContactsRecycler().getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
lcf.isLoading=false;
lcf.getContactsRecycler().post(new Runnable() {
#Override
public void run() {
((BaseActivity) lcf.getActivity()).hideProgressDialog();
}
});
lcf.getContactsRecycler().getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
That is the original code (no threads or failed attempts). The void is called everytime I initialize the adapter or the view reaches a threshold limit. It loads a list that ends up being shown on screen after "notifyItemRangeInserted()" is called. As you can see the VERY FIRST LINE tries to show the loading screen but for some reason, in the debugger itself I find with breakpoints that the method calls the show method, but the loading screen never appears, fills the list in the "for" loop, calls the notify event, the screen freezes, THEN the loading screen finally shows up but then immediately the hide method is called (rendering teh loading screen useless)

Did you try post runnable method?
progressbar.setvisibility(view.visible);
progressbar.post(new Runnable() {
#Override
public void run() {
fetchMoreDataInTheRecyclerView();
}
});
*Now do the fetching inside fetchMoreDataInTheRecyclerView(); and once done simply make progressbar invisible.
Let me know if this helps.

Related

Monogame 3.5: Mouse Click Not Detected

My monogame game has stopped responding to mouse clicks. Prior to version 3.5, this was working fine. Here's how I'm currently getting the input:
protected override void Update (GameTime game_time)
{
Mouse_Input (game_time);
}
void Mouse_Input(GameTime game_time)
{
mouse_current = Mouse.GetState();
if (mouse_current.LeftButton == ButtonState.Pressed)
{
// click
}
}
Setting breakpoints in the function reveals all the code is being hit, but LeftButton is always ButtonState.Released.
I've tried with both a wired mouse and the trackpad. Keyboard input is working fine. Anyone else running into this?
I always use this way.
MouseState currentMouseState;
MouseState oldMouseState;
public bool checkClick()
{
oldMouseState = currentMouseState;
currentMouseState = Mouse.GetState();
if (Visible)
{
if (currentMouseState.LeftButton == ButtonState.Pressed && oldMouseState.LeftButton == ButtonState.Released)
{
return true;
}
}
}
If you want to check if the Mouse clicks on a Rectangle (Hud elements for example)
public bool checkClickRectangle(Rectangle rec)
{
oldMouseState = currentMouseState;
currentMouseState = Mouse.GetState();
if (Visible)
{
if (rec.Contains(new Vector2(Mouse.GetState().X, Mouse.GetState().Y)) && currentMouseState.LeftButton == ButtonState.Pressed && oldMouseState.LeftButton == ButtonState.Released)
{
return true;
}
}
}
This was actually a not a problem with Monogame, but a problem in my game logic that was very difficult to track down.
After upgrading to 3.5, I had to reconfigure how my Texture2D's were being loaded, which also meant refactoring some classes. I ended up with a class within a class which were both inheriting from Game.
public class Brush_Control : Game
{
public class Tile : Game
{
Process of elimination narrowed the search to this class. I believe this caused an infinite loop that interfered with the input somehow, but without throwing an error or causing an obvious freeze.
Removing the inner Game reference as a parent fixed the problem, and it turns out I no longer need to have it there anyway.

Debugging charm projects in Netbeans

I'm trying to debug a charm project. I've set break points in the code, but each time execution reaches a break point, Netbeans freezes and I'm obliged to forcefully close it.
For what it's worth, I'm using Ubuntu 15.04
[Edit 1]
Here's an image of a set break point
I am getting an exception:
Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException
that doesn't point to any line in my code, so I want to debug and get what is causing the problem. Immediately the code gets to line 106, everything freezes.
[Edit 2]
Ok here's most of the controller code.
public void initialize(URL url, ResourceBundle rb) {
departmentList.setPlaceholder(new Label("Oops!! EMPTY!!!"));
/*
Populate SideMenu
*/
ObservableList<Label> schools = FXCollections.observableArrayList();
ListView<Label> schoolList = new ListView<>(schools);
for (School school : schoolsList) {
schools.add(new Label(school.getName(), MaterialDesignIcon.ACCOUNT_BALANCE.graphic()));
}
/*
Add Listeners to side Menu ListView
*/
schoolList.getSelectionModel().selectedItemProperty().addListener(
(ObservableValue<? extends Label> observable, Label oldValue, Label newValue) -> {
selectedSchool = parser.findSchool(newValue.getText());
loadDepartments();
MobileApplication.getInstance().hideLayer("Side Menu");
});
/*
Add Listener to departments ListView
*/
departmentList.getSelectionModel().selectedItemProperty().addListener(
(ObservableValue<? extends Label> observable, Label oldValue, Label newValue) -> {
if (newValue == null) {//Got fired by clearing the Observable list
return;
}
System.out.println(newValue);
facDept[1] = newValue.getText();
/*
Reset before leaving; *to be removed and tried on mobile
*/
loadDepartments();
MobileApplication.getInstance().switchView(SEMESTER_VIEW);
});
borderPane.setCenter(schoolList);
center.getChildren().add(departmentList);
}
#FXML
private void showLayer(ActionEvent event) {
MobileApplication.getInstance().showLayer("Side Menu");
}
I set a break point in the showLayer method(MobileApplication...), and debugging works. I set another one the line selectedSchool = parser.findSchool(newValue.getText());, but here debugging freezes. Note that the exception doesn't occur here.

Enable - Disable a button while threading vsto for ms word

I'am very new to threading and quite unclear as to why this is happening in my code, when I click on a button that verifies hyperlinks in my document, I start a new thread that does the verification once it starts I want to disable the ribbon button and enable it again after thread finished but this is not happening and I dont know what is the mistake .Here is what I have tried so far:
public class Alpha :Ribbon1
{
// This method that will be called when the thread is started
public void Beta()
{
foreach() { //do something } after this loop ,enable the button again
button.enable=true //not applying
} }
private void button_Click(object sender, RibbonControlEventArgs e)
{
Alpha oAlpha = new Alpha();
// Create the thread object, passing in the Alpha.Beta method
Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
// MessageBox.Show("Please wait till the document is checked for invalid links");
// Start the thread
oThread.Start();
button7.Label = "Pls wait";
button7.Enabled = false;
}
Ribbon needs to be rendered again after enable/disable for change to take effect, you can do this by calling IRibbonUI.Invalidate()

Animation not starting until UI updates or touch event

I have a strange problem with an AlphaAnimation. It is supposed to run repeatedly when an AsyncTask handler is called.
However, the first time the handler is called in the Activity, the animation won't start unless I touch the screen or if the UI is updated (by pressing the phone's menu button for example).
The strange part is that once the animation has run at least once, it will start without problem if the handler is called again.
Here's what the code looks like:
// AsyncTask handler
public void onNetworkEvent()
{
this.runOnUiThread(new Runnable() {
#Override
public void run()
{
flashScreen(Animation.INFINITE);
}
});
}
// Called method
private void flashScreen(int repeatCount)
{
final View flashView = this.findViewById(R.id.mainMenuFlashView);
AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
alphaAnimation.setRepeatCount(repeatCount);
alphaAnimation.setRepeatMode(Animation.RESTART);
alphaAnimation.setDuration(300);
alphaAnimation.setInterpolator(new DecelerateInterpolator());
alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation)
{
flashView.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationEnd(Animation animation)
{
flashView.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) { }
});
flashView.startAnimation(alphaAnimation);
}
I have noticed that runOnUIThread isn't necessary (same results occur if I don't use it), but I prefer keeping it as I'm not on the UI thread.
Any ideas on what could cause this?
A little more research showed that my problem was the same a this question:
Layout animation not working on first run
The flashView's visibility was set to GONE by default (causing the Animation not to start immediately as the View had never been rendered), so I just need to set it to INVISIBLE before calling flashView.startAnimation()
If setting the View to VISIBLE won't work, as was in my case, it helped for me to call requestLayout() before starting the Animation, like so:
Animation an = new Animation() {
...
view.requestLayout();
view.startAnimation(an);
In my case, my View was 0dip high which prevented onAnimationStart from being called, this helped me around that problem.
This worked for me:
view.setVisibility(View.VISIBLE);
view.startAnimation(animation);
I had to set the view to VISIBLE (not INVISIBLE, neither GONE), causing the view renderization needed to animate it.
That's not an easy one. Till you got a real answer : The animation start is triggered by onNetworkEvent. As we don't know the rest of the code, you should look there, try to change onNetworkEvent by an other event that you can easily identify, just to debug if the rest of the code is ok or if it's just the trigger that is responsible for it.
May be it will help someone, because previous answers not helped me.
My animation was changing height of view (from 0 to it's real height and back) on click - expand and collapse animations.
Nothing worked until i added listener and set visibility to GONE, when animation ends:
collapseAnim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
view.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
And when expand just set it to VISIBLE before animation:
view.setVisibility(View.VISIBLE);
view.startAnimation(expandAnim);

JavaFX global scene variable unexpectedly changed to null

I want to make an application in javaFX 2 which opens as a smaller login window, then, when you put in correct data, it takes you to bigger main window. Both are designed in fxml and events are handled within java code.
Yes, I know, it is almost the same as the application in samples and I've tried to do what I want and it worked there.
Now, when I did the same in my project, I hit a problem when I want to change the value of stage.
As you can see in the code below, I have global variable and I set the value of primaryStage in start method to it. Just as a test, I print it out at end of start method and the value is set.
Then, when I try to use it when button is clicked(method buttonClick), the value of stage variable is null, therefore I cannot use it to resize window or anything else.
My question is why is stage variable value reseted despite that I don't use change anything between the two prints?
This code is sample of what I've tried, I've just cut out all code which is not crucial to understand how my application works.
public class App extends Application {
private Stage stage;
#FXML
private AnchorPane pane;
#Override
public void start(Stage primaryStage) {
try {
stage = primaryStage; // Set the value of primaryStage to stage
primaryStage.setScene(new Scene(openScene("Login"))); // Load Login window
primaryStage.show(); // Show the scene
} catch (IOException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(stage);// <-- Here it has the value of primaryStage obviously
}
#FXML
void buttonClick(ActionEvent event) throws IOException {
// Note that even if I try to print here, the value of stage is still
// null, so the code doesn't affect it
// Also, this loads what I want, I just can't change the size.
try{
pane.getChildren().clear(); // Clear currently displayed content
pane.getChildren().add(openScene("MainScene")); // Display new content
System.out.println(stage); // <-- Here, output is null, but I don't know why
stage.setWidth(500); // This line throws error because stage = null
} catch (IOException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Parent openScene(String name) throws IOException {
//Code from FXML login example
Parent parent = (Parent) FXMLLoader.load(PrijavnoOkno.class.getResource(name
+ ".fxml"), null, new JavaFXBuilderFactory());
return parent;
}
public static void main(String[] args) {
launch(args);
}
}
Although it is not clear by whom and where the buttonClick action method is called, I pressume it is a login button's action in Login.fxml. Also I assume you have defined the App (a.k.a PrijavnoOkno) as a controller of this Login.fxml.
According to these assumptions, there are 2 instances of App.class:
one created when the app starts up and where the stage variable is assigned with primary stage in start() method,
and another instance created by FXMLLoader (while loading Login.fxml) and where the stage variable is not assigned and thus NPE.
One of the right ways can be, create a new Controller class for Login.fxml, call your login action in it. Access the global stage (by making it static in App) from there.