Strange behaviour when trying to assign tags to instantiated unity UI game objects - user-interface

When I call functions LikeFrame1(),LikeFrame2(),LikeFrame3() once (That is, click the button that call the function it for the first time) a random tag is assigned to the instantiated gameobject (The tag is coming from the other functions where I am doing the same thing, LikeFrame1(),LikeFrame2(),LikeFrame3() respectively)
When I click the button to call it a second time it will assign the proper tag.
I have tried to change where I call assigning the new tag in the function
Here is script with my functions that instantiate the Gameobject and assign the tags:
public class InventoryCreateButton : MonoBehaviour
{
public Button Button;
public void AddItemz1()
{
Button go = Instantiate(Button, new Vector3(0, 0, 0),
Quaternion.identity) as Button;
Button.tag = "poop";
go.transform.parent =
GameObject.Find("ButtonListContent1").transform;
Debug.Log("AddItemz1");
}
public void AddItemz2()
{
Button go = Instantiate(Button, new Vector3(0, 0, 0),
Quaternion.identity) as Button;
Button.tag = "poop2";
go.transform.parent =
GameObject.Find("ButtonListContent1").transform;
Debug.Log("AddItemz2");
}
I call them from this script like so:
public class ChooseFrame : MonoBehaviour
{
public GameObject currentInterObj = null;
public InteractionObject currentInterObjScript = null;
public Inventory inventory;
public InventoryCreateButton inventorycreateButton;
public InventoryButtonGetImage inventoryButtonGetImage;
public void LikeFrame1()
{
currentInterObj = frame1;
if (currentInterObj && _soundOn1)
{
inventorycreateButton.AddItemz1();
_soundOn1 = false;
Debug.Log(_soundOn1);
}
else
{
SoundOn1(); //method that can turn the sound on
_soundOn1 = true;
Debug.Log(_soundOn1);
}
}
// Update is called once per frame
void SoundOn1()
{
Destroy(GameObject.FindWithTag("poop"));
}
public void LikeFrame2()
{
currentInterObj = frame2;
if (currentInterObj && _soundOn2)
{
inventorycreateButton.AddItemz2();
_soundOn2 = false;
Debug.Log(_soundOn2);
}
else
{
SoundOn2(); //method that can turn the sound on
_soundOn2 = true;
Debug.Log(_soundOn2);
}
}
// Update is called once per frame
void SoundOn2()
{
Destroy(GameObject.FindWithTag("poop2"));
}
public void LikeFrame3()
{
currentInterObj = frame3;
if (currentInterObj && _soundOn3)
{
inventorycreateButton.AddItemz3();
_soundOn3 = false;
}
else
{
SoundOn3(); //method that can turn the sound on
_soundOn3 = true;
}
}
// Update is called once per frame
void SoundOn3()
{
Destroy(GameObject.FindWithTag("poop3"));
}
No error message and I would expect that the proper tag would be assigned to my instantiated gameobject upon calling the function the first time, not the second time.

Related

Code Error. The modifier public is not valid. Why?

I am making a 2D game in Unity and am trying to make my moveable character stop every time dialogue appears on screen.
I am using the Fungus extension for my dialogue as I'm a newbie to coding. Every thing I try however I run in to problems.
My current issue is that the modifier 'public' is not valid for this item.
Anyone know how this can be fixed? I have attached the code below. I assume the issue is with the public void CantMove() and public void CanMove() lines.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
public Rigidbody2D theRB;
public float jumpForce;
private bool isGrounded;
public Transform groundCheckPoint;
public LayerMask whatIsGround;
private bool canDoubleJump;
private bool canMove = true;
private Animator anim;
private SpriteRenderer theSR;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
theSR = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
if(!canMove)
{
theRB.velocity = new Vector2(0, 0);
}
else
{
theRB.velocity = new Vector2(moveSpeed * Input.GetAxis("Horizontal"), theRB.velocity.y);
}
public void CantMove()
{
canMove = false;
}
public void CanMove()
{
canMove = true;
}
//theRB.velocity = new Vector2(moveSpeed * Input.GetAxis("Horizontal"), theRB.velocity.y);
isGrounded = Physics2D.OverlapCircle(groundCheckPoint.position, .2f, whatIsGround);
if(isGrounded)
{
canDoubleJump = true;
}
if(Input.GetButtonDown("Jump"))
{
if (isGrounded)
{
theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
}
else
{
if(canDoubleJump)
{
theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
canDoubleJump = false;
}
}
}
if(theRB.velocity.x > 0)
{
theSR.flipX = true;
} else if(theRB.velocity.x < 0)
{
theSR.flipX = false;
}
anim.SetFloat("moveSpeed", Mathf.Abs( theRB.velocity.x));
anim.SetBool("isGrounded", isGrounded);
}
}
'''
Your problem is that your two functions defined for CanMove and CantMove are declared inside of the Update function body... which makes them locally scoped functions which means they can never have public access and can only be called from within the Update function itself.
Move these two functions outside of the Update function body like this...
void Update() {
...
}
public void CantMove() {
canMove = false;
}
public void CanMove() {
canMove = true;
}

Xamarin Forms MessagingCenter Subscribe called two times

I'm clicking on a product item in listview in product page viewmodel to show a popup(using rg.plugin popup) for selecting one of the product variants.After selecting variant,i am sending the selected variant to product page using messagingcenter from variant popup page viewmodel,subscribed in product page viewmodel constructor. working fine there.when i navigate to the previous page and then came back to this product page for adding one or more variant to the
same previously selected product,Messagingcenter subscribe called twice and product value increased twice.Tried to subscribe in the product page onappearing and unsubscribe in disappearing method.still calling two times? How to solve this issue?
calling popup:
var result = await dataService.Get_product_variant(store_id, product_id);
if (result.status == "success")
{
ind_vis = false;
OnPropertyChanged("ind_vis");
App.Current.Properties["product_variant_result"] = result;
App.Current.Properties["cartitems"] = purchaselist;
App.Current.Properties["selected_product"] = product_List2 ;
await PopupNavigation.Instance.PushAsync(new Popup_variant());
}
popup viewmodel: sending message
public Popup_variant_vm()
{
Radio_btn = new Command<Product_variant_list2>(Radio_stk_tapped);
product_variant_list = new List<Product_variant_list2>();
purchaselist = new ObservableCollection<Product_list2>();
show_variants();
}
internal void Confirm_variant()
{
if(App.Current.Properties.ContainsKey("selected_variant"))
{
MessagingCenter.Send<Popup_variant_vm, object>(this, "selected_variant", App.Current.Properties["selected_variant"]); //Message send from popup to product page
}
else
{
DependencyService.Get<IToast>().LongAlert("Please select any size");
}
}
product page viewmodel: subscribed here..called twice when navigating from previous page to this
public Store_page()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
var vm = new store_page_vm();
vm.Navigation = Navigation;
BindingContext = vm;
MessagingCenter.Unsubscribe<Popup_variant_vm, object>(this, "selected_variant");
MessagingCenter.Subscribe<Popup_variant_vm, object>(this, "selected_variant",async (sender, selected_variant) =>
{
var vm1 = BindingContext as store_page_vm;
vm1?.Addcart2(selected_variant);// called twice
});
}
unsubscribed in product cs page
protected override void OnDisappearing()
{
var vm = BindingContext as store_page_vm;
vm?.Save_cart();
MessagingCenter.Unsubscribe<Popup_variant_vm>(this, "selected_variant");
}
Your unsubscription should look something like below and it should work :
MessagingCenter.Unsubscribe<Popup_variant_vm, object>(this, "selected_variant");
https://stackoverflow.com/a/44753021/10937160
try this, and make sure you do not call Subscribe more than once.
My solution:
put unsubscribe sentence into subscribe body !!
MessagingCenter.Subscribe<object, string>(this, "IdSearch", (sender, arg) =>
{
listView.ItemsSource = arg;
MessagingCenter.Unsubscribe<object, string>(this, "IdSearch");
}, BindingContext);
I have created static counter variable in my app the in subscriber I have done this:
public static class Constants
{
public static int msgCenterSubscribeCounter { get; set; } = 0;
}
MessagingCenter.Subscribe<object, string>(this, "hello", (sender, arg) =>
{
Constants.msgCenterSubscribeCounter++;
if (arg.Equals("hello") && Constants.msgCenterSubscribeCounter == 1)
{
// handle your logic here
}
});
Reset counter in OnDisappearing() method from where you have called Send.
Changing Messagingcenter in to single subscription.
public class Messagingcenter_singleton
{
private static Messagingcenter_singleton _instance;
private bool isActivated = false;
private Action<string> callBackFun = null;
public static Messagingcenter_singleton Instance()
{
if (_instance == null)
{
_instance = new Messagingcenter_singleton();
}
return _instance;
}
public void setCallBack(Action<string> eventCallBack)
{
callBackFun = eventCallBack;
}
public void startSubscribe()
{
if (!isActivated)
{
isActivated = true;
MessagingCenter.Subscribe<string, string>(this, "Name", eventCallBack);
}
}
private void eventCallBack(string arg1, string arg2)
{
if (callBackFun != null)
{
InvokeMethod(new Action<string>(callBackFun), arg2);
}
}
public static object InvokeMethod(Delegate method, params object[] args)
{
return method.DynamicInvoke(args);
}
}
Use Below Code in you view model class
public void initSubscribe()
{
Messagingcenter_singleton.Instance().startSubscribe();
Messagingcenter_singleton.Instance().setCallBack(eventCallBack)
}
public void eventCallBack(string arg2)
{
// write your code here
}

Vala GTK+. Issue with customized widget

I need to create a gtk.Entry which accepts only numbers. but I can't overwrite the key_press_event event in an heredited class. It only works if I use the original Entry by means of connect function.
What am I doing wrong?
using Gtk;
public class NumberEntry : Entry {
public void NumberEntry(){
add_events (Gdk.EventMask.KEY_PRESS_MASK);
}
//With customized event left entry editing is not possible
public override bool key_press_event (Gdk.EventKey event) {
string numbers = "0123456789.";
if (numbers.contains(event.str)){
return false;
} else {
return true;
}
}
}
public class Application : Window {
public Application () {
// Window
this.title = "Entry Issue";
this.window_position = Gtk.WindowPosition.CENTER;
this.destroy.connect (Gtk.main_quit);
this.set_default_size (350, 70);
Grid grid = new Grid();
grid.set_row_spacing(8);
grid.set_column_spacing(8);
Label label_1 = new Label ("Customized Entry, useless:");
grid.attach (label_1,0,0,1,1);
//Customized Entry:
NumberEntry numberEntry = new NumberEntry ();
grid.attach(numberEntry, 1, 0, 1, 1);
Label label_2 = new Label ("Working only numbers Entry:");
grid.attach (label_2,0,1,1,1);
//Normal Entry
Entry entry = new Entry();
grid.attach(entry, 1, 1, 1, 1);
this.add(grid);
//With normal Entry this event works well:
entry.key_press_event.connect ((event) => {
string numbers = "0123456789.";
if (numbers.contains(event.str)){
return false;
} else {
return true;
}
});
}
}
public static int main (string[] args) {
Gtk.init (ref args);
Application app = new Application ();
app.show_all ();
Gtk.main ();
return 0;
}
The key_press_event of the superclass is no longer being called. You need to call the base class and return true when you have consumed the key.
public override bool key_press_event (Gdk.EventKey event) {
string numbers = "0123456789.";
if (numbers.contains(event.str)){
return base.key_press_event (event);
} else {
return true;
}
}
If you return false in a signal, this can be passed to an alternate handler, but only if you use connect and not override the signal method.

Fragment with update of detail layout

I have programmed an Android App with fragments. A ListView fragment and a detail fragment.
What I wanna do is, if someone clicks inside the detail activity, a layout which is "View.Gone" should be "View.Visible". The code works without errors but nothing changed on the screen.
You can see it in Detail fragment code where a clik event on the ImageButton btn is.
What do i wrong?
What is the best way to update the detail screen? If someone has a small example or could write me where in my code I have to change what, it makes me happy :-)
Thanks a lot
Tom
The FragmentActivity:
public class CacheFragment extends SherlockFragmentActivity {
CacheListFragment f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_cachelist);
f = new CacheListFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
f.setArguments(args);
}
Here's the Detail Fragment, where you can see whatt should happen if someone clicks on the Imagebutton:
public class CacheDetailsFragment extends SherlockFragment implements OnClickListener {
private CacheDetailsLoading cdLoad= new CacheDetailsLoading();
private static GeocacheDetails _cacheDetails = new GeocacheDetails();
private static GCRatingTyp _cacheVote = new GCRatingTyp();
private CacheDetailsUsing cdUsing = new CacheDetailsUsing();
private Activity _context;
private static CacheDetailsFragment f;
private View view;
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static CacheDetailsFragment newInstance(int index ) {
f = new CacheDetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
public void setCacheDetail(GeocacheDetails cacheDetails)
{
_cacheDetails = cacheDetails;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
Bundle bundle=getArguments();
_cacheVote= bundle.getParcelable("cacheVote");
int index = bundle.getInt("index");
_cacheDetails=StaticCacheListByGroup.getCacheList().get(index);
_context = getActivity();
_context.setTheme(R.style.Theme_Sherlock_Light_DarkActionBar);
view = inflater.inflate(R.layout.list_cachedetails, container,false);
((RelativeLayout) view.findViewById(R.id.relativeLoggingInfo)).setVisibility(View.GONE);
((RelativeLayout) view.findViewById(R.id.relativeKategorienInfo)).setVisibility(View.GONE);
ImageButton btn = (ImageButton) view.findViewById(R.id.description_expand);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if(((RelativeLayout) getActivity().findViewById(R.id.relativeDescriptionInfo)).getVisibility() == View.GONE)
{
((ImageButton) getActivity().findViewById(R.id.description_expand)).setBackgroundResource(R.drawable.navigation_collapse_dark);
((RelativeLayout) getActivity().findViewById(R.id.relativeDescriptionInfo)).setVisibility(View.VISIBLE);
}
else
{
((ImageButton) getActivity().findViewById(R.id.description_expand)).setBackgroundResource(R.drawable.navigation_expand_dark);
((RelativeLayout) getActivity().findViewById(R.id.relativeDescriptionInfo)).setVisibility(View.GONE);
}
});
return view;
}
}
Now the Listfragment:
public class CacheListFragment extends SherlockListFragment {
boolean isDualPane;
int mCurCheckPosition = 0;
private CacheListArrayAdapter _adapter;
private SharedPrefs _sp= new SharedPrefs();
private double latitude=0;
private double longitude=0;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
latitude =Double.parseDouble(_sp.getSharedPrefs(getActivity(), LibraryDefaults.PROGRAMMNAME, "Latitude", "0"));
longitude =Double.parseDouble(_sp.getSharedPrefs(getActivity(), LibraryDefaults.PROGRAMMNAME, "Longitude", "0"));
// Check to see if we have a frame in which to embed the details
// fragment directly in the containing UI.
View detailsFrame = getActivity().findViewById(R.id.details);
isDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if(!isDualPane)
{
Bundle bundle = getActivity().getIntent().getExtras();
if(bundle != null && bundle.containsKey("Titel"))
((TextView) getActivity().findViewById(R.id.listtitle)).setText(bundle.getString("Titel"));
else
((TextView) getActivity().findViewById(R.id.listtitle)).setText(this.getResources().getString(R.string.caches_listtitle));
}
if (StaticCacheListByGroup.getCacheList() != null)
{
GeocachingCompass gc = new GeocachingCompass(getActivity());
_adapter = new CacheListArrayAdapter(getActivity(), StaticCacheListByGroup.getCacheList(), longitude,latitude);
_adapter.setActualCoordinates(new LatLng(latitude,longitude));
_adapter.setActualHeading(gc.getBearing(latitude,longitude));
if (_adapter != null)
setListAdapter(_adapter);
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setSoundEffectsEnabled(true);
getListView().setSmoothScrollbarEnabled(true);
getListView().setDrawSelectorOnTop(false);
getListView().setCacheColorHint(R.color.transparentBlack);
getListView().setDivider(getResources().getDrawable( R.color.divider));
getListView().setDividerHeight(5);
if (isDualPane) {
// In dual-pane mode, the list view highlights the selected item.
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetails(mCurCheckPosition);
}
}
}
#Override
public void onResume() {
super.onResume();
GeocachingCompass gc = new GeocachingCompass(getActivity());
_adapter = new CacheListArrayAdapter(getActivity(), StaticCacheListByGroup.getCacheList(), longitude,latitude);
_adapter.setActualCoordinates(new LatLng(latitude,longitude));
_adapter.setActualHeading(gc.getBearing(latitude,longitude));
if (_adapter != null)
setListAdapter(_adapter);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
/**
* Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
* whole new activity in which it is displayed.
*/
void showDetails(int index) {
mCurCheckPosition = index;
ReadGCVote getVote = new ReadGCVote();
GeocacheDetails cacheDetails = new GeocacheDetails();
cacheDetails=StaticCacheListByGroup.getCacheList().get(index);
if (isDualPane) {
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
getListView().setItemChecked(index, true);
// Check what fragment is currently shown, replace if needed.
CacheDetailsFragment details = (CacheDetailsFragment)
getActivity().getSupportFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = CacheDetailsFragment.newInstance(index);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
// Otherwise we need to launch a new activity to display
Intent intent = new Intent();
intent.setClass(getActivity(), CacheDetailsActivity.class);
intent.putExtra("index", index);
intent.putExtra("cacheDetails",cacheDetails);
intent.putExtra("cacheVote",getVote.getGCVoteByCacheGuid( StaticGCVoteList.getCacheList(), cacheDetails.GetGUID()));
startActivity(intent);
}
}
}
I found the bug :-)
In the code snippet of the Detail Fragment ...
public void onClick(View v)
{
if(((RelativeLayout) getActivity().findViewById(R.id.relativeDescriptionInfo)).getVisibility() == View.GONE)
}
...you shouldn't use "getActivity()" use "view" from "view = inflater.inflate(R.layout.list_cachedetails, container,false);"
Then it will work

Blackberry - Loading/Wait screen with animation

Is there a way to show "Loading" screen with animation in blackberry?
Options:
PME animation content
multithreading + set of images + timer/counter
standard rim api
some other way
Any of this?
Thanks!
Fermin, Anthony +1. Thanks to all, you gave me the part of answer.
My final solution:
1.Create or generate (free Ajax loading gif generator) animation and add it to project.
2.Create ResponseCallback interface (see Coderholic - Blackberry WebBitmapField) to receive thread execution result:
public interface ResponseCallback {
public void callback(String data);
}
3.Create a class to handle your background thread job. In my case it was http request:
public class HttpConnector
{
static public void HttpGetStream(final String fileToGet,
final ResponseCallback msgs) {
Thread t = new Thread(new Runnable() {
public void run() {
HttpConnection hc = null;
DataInputStream din = null;
try {
hc = (HttpConnection) Connector.open("http://" + fileToGet);
hc.setRequestMethod(HttpsConnection.GET);
din = hc.openDataInputStream();
ByteVector bv = new ByteVector();
int i = din.read();
while (-1 != i) {
bv.addElement((byte) i);
i = din.read();
}
final String response = new String(bv.toArray(), "UTF-8");
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
msgs.callback(response);
}
});
}
catch (final Exception e) {
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
msgs.callback("Exception (" + e.getClass() + "): "
+ e.getMessage());
}
});
}
finally {
try {
din.close();
din = null;
hc.close();
hc = null;
}
catch (Exception e) {
}
}
}
});
t.start();
}
}
4.Create WaitScreen (a hybrid of FullScreen and AnimatedGIFField with ResponseCallback interface):
public class WaitScreen extends FullScreen implements ResponseCallback
{
StartScreen startScreen;
private GIFEncodedImage _image;
private int _currentFrame;
private int _width, _height, _xPos, _yPos;
private AnimatorThread _animatorThread;
public WaitScreen(StartScreen startScreen) {
super(new VerticalFieldManager(), Field.NON_FOCUSABLE);
setBackground(
BackgroundFactory.createSolidTransparentBackground(
Color.WHITE, 100));
this.startScreen = startScreen;
EncodedImage encImg =
GIFEncodedImage.getEncodedImageResource("ajax-loader.gif");
GIFEncodedImage img = (GIFEncodedImage) encImg;
// Store the image and it's dimensions.
_image = img;
_width = img.getWidth();
_height = img.getHeight();
_xPos = (Display.getWidth() - _width) >> 1;
_yPos = (Display.getHeight() - _height) >> 1;
// Start the animation thread.
_animatorThread = new AnimatorThread(this);
_animatorThread.start();
UiApplication.getUiApplication().pushScreen(this);
}
protected void paint(Graphics graphics) {
super.paint(graphics);
// Draw the animation frame.
graphics
.drawImage(_xPos, _yPos, _image
.getFrameWidth(_currentFrame), _image
.getFrameHeight(_currentFrame), _image,
_currentFrame, 0, 0);
}
protected void onUndisplay() {
_animatorThread.stop();
}
private class AnimatorThread extends Thread {
private WaitScreen _theField;
private boolean _keepGoing = true;
private int _totalFrames, _loopCount, _totalLoops;
public AnimatorThread(WaitScreen _theScreen) {
_theField = _theScreen;
_totalFrames = _image.getFrameCount();
_totalLoops = _image.getIterations();
}
public synchronized void stop() {
_keepGoing = false;
}
public void run() {
while (_keepGoing) {
// Invalidate the field so that it is redrawn.
UiApplication.getUiApplication().invokeAndWait(
new Runnable() {
public void run() {
_theField.invalidate();
}
});
try {
// Sleep for the current frame delay before
// the next frame is drawn.
sleep(_image.getFrameDelay(_currentFrame) * 10);
} catch (InterruptedException iex) {
} // Couldn't sleep.
// Increment the frame.
++_currentFrame;
if (_currentFrame == _totalFrames) {
// Reset back to frame 0
// if we have reached the end.
_currentFrame = 0;
++_loopCount;
// Check if the animation should continue.
if (_loopCount == _totalLoops) {
_keepGoing = false;
}
}
}
}
}
public void callback(String data) {
startScreen.updateScreen(data);
UiApplication.getUiApplication().popScreen(this);
}
}
5.In the end, create Start screen to call HttpConnector.HttpGetStream and to show WaitScreen:
public class StartScreen extends MainScreen
{
public RichTextField text;
WaitScreen msgs;
public StartScreen() {
text = new RichTextField();
this.add(text);
}
protected void makeMenu(Menu menu, int instance) {
menu.add(runWait);
super.makeMenu(menu, instance);
}
MenuItem runWait = new MenuItem("wait", 1, 1) {
public void run() {
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
getFile();
}
});
}
};
public void getFile() {
msgs = new WaitScreen(this);
HttpConnector.HttpGetStream(
"stackoverflow.com/faq", msgs);
}
//you should implement this method to use callback data on the screen.
public void updateScreen(String data)
{
text.setText(data);
}
}
UPDATE: another solution naviina.eu: A Web2.0/Ajax-style loading popup in a native BlackBerry application
The basic pattern for this kind of thing is:
Have a thread running a loop that updates a variable (such as the frame index of the animated image) and then calls invalidate on a Field which draws the image (and then sleeps for a period of time). The invalidate will queue a repaint of the field.
In the field's paint method, read the variable and draw the appropriate frame of the image.
Pseudo code (not totally complete, but to give you the idea):
public class AnimatedImageField extends Field implements Runnable {
private int currentFrame;
private Bitmap[] animationFrames;
public void run() {
while(true) {
currentFrame = (currentFrame + 1) % animationFrames.length;
invalidate();
Thread.sleep(100);
}
}
protected void paint(Graphics g) {
g.drawBitmap(0, 0, imageWidth, imageHeight, animationFrames[currentFrame], 0, 0);
}
}
Note also here I used an array of Bitmaps, but EncodedImage lets you treat an animated gif as one object, and includes methods to get specific frames.
EDIT: For completeness: Add this to a PopupScreen (as in Fermin's answer) or create your own dialog by overriding Screen directly. The separate thread is necessary because the RIM API is not thread-safe: you need to do everything UI related on the event thread (or while holding the event lock, see BlackBerry UI Threading - The Very Basics
This is simple code for loading screen ....
HorizontalFieldManager popHF = new HorizontalFieldManager();
popHF.add(new CustomLabelField("Pls wait..."));
final PopupScreen waitScreen = new PopupScreen(popHF);
new Thread()
{
public void run()
{
synchronized (UiApplication.getEventLock())
{
UiApplication.getUiApplication().pushScreen(waitScreen);
}
//Here Some Network Call
synchronized (UiApplication.getEventLock())
{
UiApplication.getUiApplication().popScreen(waitScreen);
}
}
}.start();
If it's just an animation could you show an animated gif on a popup and close it when loading operation is complete?
Easiest way is probably to use the standard GaugeField, setting style GaugeField.PERCENT. This will give you a progress bar. Add this to a PopupScreen and it will sit on top of your content. Something like..
private GaugeField _gaugeField;
private PopupScreen _popup;
public ProgressBar() {
DialogFieldManager manager = new DialogFieldManager();
_popup = new PopupScreen(manager);
_gaugeField = new GaugeField(null, 0, 100, 0, GaugeField.PERCENT);
manager.addCustomField(_gaugeField);
}
Then have an update method which will use _gaugeField.setValue(newValue); to update the progress bar.
I normally have this called from whichever thread is doing the work (loading in your case, everytime an operation is complete the progress bar is updated.
I would suggest to take a look at this simple implementation. I liked this but never used it. May be helpful to you.
link text
ActivityIndicator is a good option if you are working with at least BB OS 6.0.
http://www.brighthub.com/mobile/blackberry-platform/articles/94258.aspx
http://docs.blackberry.com/en/developers/deliverables/17966/Screen_APIs_1245069_11.jsp

Resources