J2me ticker not displayed correctly. Help me to try to solve it - java-me

I'm developing a mobile application with j2me. The configuration is "CLDC 1.1" & "MIDP 2.0". The phone I used for testing purpose is "NOKIA C2-01". The phone is "S40" device.
In that mobile app the data is send to server and perform based on response. I added the ticker to the Displayable (the Displayable may be form, list, etc).
When application runs the ticker is shown sometimes correctly, but sometimes the ticker is not correctly displayed: the space for ticker is appeared above the form/list, but ticker is not displayed.
Please help me to solve it.
I am just assigning the form and list to the object of (Displayable) displayable.
Then I create a new Ticker object and I set the ticker by displayable.setTicker(Ticker ticker) method. Sometimes ticker is shown correctly sometimes ticker not shown.
the following are my conding snippets-some sample only
public class Controller
{
Form loginForm;
List userLit;
Ticker tikcer;
Display display;
Displayable displayable;
public Controller()
{
display=Display.getDisplay(midlet);
displayable=null;
loginForm=new LoginForm("Login");
userList=List("user list", Choice.IMPLICIT);
}
public void showLoginForm()
{
displayable=loginForm;
display.setCurrent(loginForm);
}
public void showUserList()
{
displayable=userList;
display.setCurrent(userList);
}
public void setTickerToDisplayable(String str)
{
ticker=null;
if((str==null)||(str.length()<1))
ticker=null;
else
ticker=new Ticker(str);
displayable.setTicker(ticker);
}
}

I find the solution.Sometimes if application gets more memory means then ticker not displayed correctly.
Now i modified my code with respect to decrease the memory leaks.Now its working

Related

How do I clear the input of a Smart Panel dialog (PXFilter)?

I have created a smart panel in a custom screen to ask for user input that is used to facilitate moving stock from normal inventory into an isolation area. My original smart panel example that I always use is the Copy Order in the SOOrderEntry graph (SO301000). In this case, I need to do a bit of validation, and the user may very well decide to close the smart panel and update the document in the screen before reopening the smart panel again. If the user clicks the cancel button, I need the smart panel to reset back to defaults every time it is opened.
I thought this might be handled in the ASPX screen definition, but I can't find the right setting for the form itself. I use AutoRefresh on selectors to refresh every time they are opened, but I need the form itself to do the same and refresh back to default every time it is opened. The desired behavior DOES occur automatically when I navigate to another record of the graph's primary DAC, but I cannot seem to force the smart panel to refresh automatically every time it is opened. I looked at the various options for the form in ASPX, but I overlooked it if it is there.
Similarly to CopyOrder on SOOrderEntry, here is my code sample from my graph.
public PXFilter<StockParamFilter> stockparamfilter;
#region AddFromStock
public PXAction<MyTag> addFromStock;
[PXUIField(DisplayName = Messages.AddFromStock, MapEnableRights = PXCacheRights.Insert, MapViewRights = PXCacheRights.Insert)]
[PXButton]
protected virtual IEnumerable AddFromStock(PXAdapter adapter)
{
MyTag tag = Tags.Current;
if (tag?.TranRefNbr != null)
{
throw new PXException(Messages.TagAlreadyReceived);
}
MyTagEntry graph = PXGraph.CreateInstance<MyTagEntry>();
WebDialogResult dialogResult = stockparamfilter.AskExt(setStockStateFilter, true);
if (dialogResult == WebDialogResult.OK || (IsContractBasedAPI && dialogResult == WebDialogResult.Yes))
{
// My Business Logic Here
}
return adapter.Get();
}
#endregion
#region CheckStockParams (OK Button in Smart Panel)
public PXAction<MyTag> checkStockParams;
[PXUIField(DisplayName = "OK", MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select)]
[PXLookupButton]
public virtual IEnumerable CheckStockParams(PXAdapter adapter)
{
return adapter.Get();
}
#endregion
#region setStockStateFilter
private void setStockStateFilter(PXGraph aGraph, string ViewName)
{
checkStockStateFilter();
}
#endregion
#region checkStockStateFilter
protected virtual void checkStockStateFilter()
{
// My Business Logic Here to set bool enableStockParams = ???
checkStockParams.SetEnabled(enableStockParams);
}
#endregion
This seems like something I did in the past, but I cannot seem to locate the code. I think it is related to stockparamfilter being a PXFilter instead of a PXSelect (or SelectFrom).
I have tried stockparamfilter.ClearDialog() with no luck. I have tried stockparamfilter.RequestRefresh() with no luck. I even tried stockparamfilter.DeleteCurrent() which seemed to work when I hit Cancel, but then my code did not execute when I hit OK. I also seemed to get the desired results when I used stockparamfilter.Cache.SetDefaultExt<StockParamFilter.locationID>(filter); on every field, until I hit OK which did nothing. It's like every time I try to manipulate the filter, I break the smart panel without any errors in the trace. In fact, here is the list of what I tried unsuccessfully:
StockParamFilter filter = stockparamfilter.Current;
stockparamfilter.View.Clear();
stockparamfilter.View.RequestRefresh();
stockparamfilter.Cache.Clear();
stockparamfilter.View.RequestRefresh();
stockparamfilter.View.RequestFiltersReset();
stockparamfilter.DeleteCurrent();
stockparamfilter.ClearDialog();
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.locationID>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.toLocationID>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.qty>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.lotSerialNbr>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.origRefNbr>(filter);
What is the ASPX code or C# Code that will let me reset the smart panel to defaults?
A big thanks to Hughes Beausejour at Acumatica for the offline assist. Posting solution for anyone else that may have this issue.
First, it is important to understand that AskExt generates 2 passes of the code. The first pass prompts the smart panel. Upon response to the smart panel, the code executes again, but in this second context skips the ask. With that in mind, the reason for my code not working became clear, as Hughes explained to me.
To execute the code when the form is initialized, that code must be executed before the ask occurs. Otherwise, the form is presented and then the initializing code is executed too late. Additionally, it must be conditioned such that it only fires when the smart panel was not given an OK response by the user. (Not realizing the code executes twice, I was unaware that I was resetting the fields on both passes. When I could get the form to reset, the subsequent processing would fail becuase I was resetting it on that pass as well.) Following that code, the AskExt can be used to present the form along with the normal processing of the user response.
My code, to show the working example, is as follows:
StockParamFilter filter = stockparamfilter.Current;
// If the user response is anything except an affirmative, default the fields
if (!(stockparamfilter.View.Answer == WebDialogResult.OK || (IsContractBasedAPI && stockparamfilter.View.Answer == WebDialogResult.Yes)))
{
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.locationID>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.toLocationID>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.qty>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.lotSerialNbr>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.origRefNbr>(filter);
}
// Present the Smart Panel Dialog (happens only on the 1st pass - AskExt causes the code to execute twice)
WebDialogResult dialogResult = stockparamfilter.AskExt(setStockStateFilter, true);
// If the response was affirmative, execute the business logic
if (dialogResult == WebDialogResult.OK || (IsContractBasedAPI && dialogResult == WebDialogResult.Yes))
{
// Do Business Logic Based On User Response In Smart Panel
}

In Orchard, how to query based on current user's content picker field?

I have extended the built-in User ContentType with a Content Picker Field that can be used to select multiple Video ContentItems. This gives me a video multi-picker control on the Edit page of each User.
I love how Orchard CMS makes this so elegantly simple to setup.
Now that I can associate multiple Videos with a User, I'd like to create a Query that will display just the Videos that the currently logged in User has been granted access.
I was hoping to be able to setup a Query using the Projector module, in what I thought was the obvious way (see below), but this returns no results.
This is how I configured the second filter:
Clicked on the + Add a new Filter link on the Edit Query screen
Chose Videos:Ids from the User Content Fields section, like this:
Configured the new filter like this:
What am I doing wrong, or what is the simplest way of diagnosing this issue?
This is how the Content Picker field is defined:
I have spotted my error - it was due to me not having a proper understand of how the filters worked. The Videos:Ids filter in the User Content Fields section does not give access to the current user's list of videos, as I assumed. Instead, it is offering the field to be used in the filter, which would be useful if I were to write a query to produce a list of Users that had access to a specific Video.
It was wishful thinking that it worked the way I wanted, but it's obvious in retrospect how it actually works.
Update: in the hope it's useful for others, here's the custom filter I developed:
public interface IFilterProvider : IEventHandler
{
void Describe(dynamic describe);
}
public class CurrentUserVideosFilter : IFilterProvider
{
private readonly IWorkContextAccessor _workContextAccessor;
public CurrentUserVideosFilter(IWorkContextAccessor workContextAccessor)
{
_workContextAccessor = workContextAccessor;
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
public void Describe(dynamic describe)
{
describe.For("My Filter Category", T("My Filter Category"), T("My Filter Category"))
.Element("Current User's Videos", T("Current User's Videos"), T("Current User's Videos"),
(Action<dynamic>)ApplyFilter,
(Func<dynamic, LocalizedString>)DisplayFilter,
null
);
}
public void ApplyFilter(dynamic context)
{
var query = (IHqlQuery)context.Query;
context.Query = query.ForType("Video")
.Where(x => x.ContentPartRecord<IdentityPartRecord>(), x => x.InG("Id", GetVideoIdsForCurrentUser()));
}
private IList<int> GetVideoIdsForCurrentUser()
{
var currentUser = _workContextAccessor.GetContext().CurrentUser;
if (currentUser == null) return new int[0];
dynamic item = currentUser.ContentItem;
var videoContentItems = (IEnumerable<ContentItem>)item.User.Videos.ContentItems;
return videoContentItems.Select(i => i.Id).ToList();
}
public LocalizedString DisplayFilter(dynamic context)
{
return T("Videos that have been assigned to the currently logged in user");
}
}
I created this class in a new Orchard module, which contains all my customisations for the site I'm building. Once I installed the module, the filter was immediately available. I assume Orchard uses reflection to seek out all types that implement the IFilterProvider interface.
This is how the filter appears on the Add a Filter screen:
Clicking on the filter shows this screen:
Once the filter has been saved, the query works exactly how I'd like - it shows all videos that have been assigned to the currently logged in user.

Background task in C#

public JsonResult GetScore(int StudentID = 0)
{
//fetch the score for the user
//--Call sendReport
//return the score to the calling method
}
public void SendReport(int StudentID = 0)
{
//Logic to get the detaied marks and prepare the report's PDF
//Mail the generated PDF back to student
}
In my web application, while Student clicks for score student will get his/her score on screen and will get detailed report's PDF mailed to his/her registered mail.
Now problem is I would like to run SendReport in background, so student will come to know his/her score immediately without waiting.
I've gone through this question but it gives me error of invalid argument.
public JsonResult GetScore(int StudentID)
{
//fetch the score for the user
Task.Factory.StartNew(() => SendReport(StudentID));
//return the score
}
you could just call it in a new thread
new Thread(SendReport(StudentID)).Start();
If you're looking for a quick and dirty solution to this problem, it's to make your controller look like this:
public JsonResult GetScore(int StudentID = 0)
{
//fetch the score for the user
//return the score to the calling method
}
public JsonResult SendReport(int StudentID = 0)
{
//Logic to get the detaied marks and prepare the report's PDF
//Mail the generated PDF back to student
//Return a JsonResult indicating success
}
... and then make two JQuery calls to your controller. One to get the score and one to kick off the report. You can display the score as soon as you get it, and the report will still be chugging in the background.
Bear in mind, if the report takes longer than a few seconds to generate and email, you really should consider moving that execution to a service that you simply activate via MVC, since running it in a controller method ties up web server resources until it's finished.
See the new MVC async documentation for details on doing this.

Orchard CMS: Do I have to add a new layer for each page when the specific content for each page is spread in different columns?

Lets say I want a different main image for each page, situated above the page title. Also, I need to place page specific images in the left bar, and page specific text in the right bar. In the right and left bars, I also want layer specific content.
I can't see how I can achieve this without creating a layer for each and every page in the site, but then I end up with a glut of layers that only serve one page which seems too complex.
What am I missing?
If there is a way of doing this using Content parts, it would be great if you can point me at tutorials, blogs, videos to help get my head round the issue.
NOTE:
Sitefinity does this sort of thing well, but I find Orchard much simpler for creating module, as well as the fact that it is MVC which I find much easier.
Orchard is free, I understand (and appreciate) that. Just hoping that as the product evolves this kind of thing will be easier?
In other words, I'm hoping for the best of all worlds...
There is a feature in the works for 1.5 to make that easier, but in the meantime, you can already get this to work quite easily with just a little bit of code. You should first add the fields that you need to your content type. Then, you are going to send them to top-level layout zones using placement. Out of the box, placement only targets local content zones, but this is what we can work around with a bit of code by Pete Hurst, a.k.a. randompete. Here's the code:
ZoneProxyBehavior.cs:
=====================
using System;
using System.Collections.Generic;
using System.Linq;
using ClaySharp;
using ClaySharp.Behaviors;
using Orchard.Environment.Extensions;
namespace Downplay.Origami.ZoneProxy.Shapes {
[OrchardFeature("Downplay.Origami.ZoneProxy")]
public class ZoneProxyBehavior : ClayBehavior {
public IDictionary<string, Func<dynamic>> Proxies { get; set; }
public ZoneProxyBehavior(IDictionary<string, Func<dynamic>> proxies) {
Proxies = proxies;
}
public override object GetMember(Func<object> proceed, object self, string name) {
if (name == "Zones") {
return ClayActivator.CreateInstance(new IClayBehavior[] {
new InterfaceProxyBehavior(),
new ZonesProxyBehavior(()=>proceed(), Proxies, self)
});
}
// Otherwise proceed to other behaviours, including the original ZoneHoldingBehavior
return proceed();
}
public class ZonesProxyBehavior : ClayBehavior {
private readonly Func<dynamic> _zonesActivator;
private readonly IDictionary<string, Func<dynamic>> _proxies;
private object _parent;
public ZonesProxyBehavior(Func<dynamic> zonesActivator, IDictionary<string, Func<dynamic>> proxies, object self) {
_zonesActivator = zonesActivator;
_proxies = proxies;
_parent = self;
}
public override object GetIndex(Func<object> proceed, object self, IEnumerable<object> keys) {
var keyList = keys.ToList();
var count = keyList.Count();
if (count == 1) {
// Here's the new bit
var key = System.Convert.ToString(keyList.Single());
// Check for the proxy symbol
if (key.Contains("#")) {
// Find the proxy!
var split = key.Split('#');
// Access the proxy shape
return _proxies[split[0]]()
// Find the right zone on it
.Zones[split[1]];
}
// Otherwise, defer to the ZonesBehavior activator, which we made available
// This will always return a ZoneOnDemandBehavior for the local shape
return _zonesActivator()[key];
}
return proceed();
}
public override object GetMember(Func<object> proceed, object self, string name) {
// This is rarely called (shape.Zones.ZoneName - normally you'd just use shape.ZoneName)
// But we can handle it easily also by deference to the ZonesBehavior activator
return _zonesActivator()[name];
}
}
}
}
And:
ZoneShapes.cs:
==============
using System;
using System.Collections.Generic;
using Orchard.DisplayManagement.Descriptors;
using Orchard;
using Orchard.Environment.Extensions;
namespace Downplay.Origami.ZoneProxy.Shapes {
[OrchardFeature("Downplay.Origami.ZoneProxy")]
public class ZoneShapes : IShapeTableProvider {
private readonly IWorkContextAccessor _workContextAccessor;
public ZoneShapes(IWorkContextAccessor workContextAccessor) {
_workContextAccessor = workContextAccessor;
}
public void Discover(ShapeTableBuilder builder) {
builder.Describe("Content")
.OnCreating(creating => creating.Behaviors.Add(
new ZoneProxyBehavior(
new Dictionary<string, Func<dynamic>> { { "Layout", () => _workContextAccessor.GetContext().Layout } })));
}
}
}
With this, you will be able to address top-level layout zones using Layout# in front of the zone name you want to address, for example Layout#BeforeContent:1.
ADDENDUM:
I have used Bertrand Le Roy's code (make that Pete Hurst's code) and created a module with it, then added 3 content parts that are all copies of the bodypart in Core/Common.
In the same module I have created a ContentType and added my three custom ContentParts to it, plus autoroute and bodypart and tags, etc, everything to make it just like the Orchard Pages ContentType, only with more Parts, each with their own shape.
I have called my ContentType a View.
So you can now create pages for your site using Views. You then use the ZoneProxy to shunt the custom ContentPart shapes (Parts_MainImage, Parts_RightContent, Parts_LeftContent) into whatever Zones I need them in. And job done.
Not quite Sitefinity, but as Bill would say, Good enough.
The reason you have to create your own ContentParts that copy BodyPart instead of just using a TextField, is that all TextFields have the same Shape, so if you use ZoneProxy to place them, they all end up in the same Zone. Ie, you build the custom ContentParts JUST so that you get the Shapes. Cos it is the shapes that you place with the ZoneProxy code.
Once I have tested this, I will upload it as a module onto the Orchard Gallery. It will be called Wingspan.Views.
I am away on holiday until 12th June 2012, so don't expect it before the end of the month.
But essentially, with Pete Hurst's code, that is how I have solved my problem.
EDIT:
I could have got the same results by just creating the three content parts (LeftContent, RightContent, MainImage, etc), or whatever content parts are needed, and then adding them to the Page content type.
That way, you only add what is needed.
However, there is some advantage in having a standard ContentType that can be just used out of the box.
Using placement (Placement.info file) you could use the MainImage content part for a footer, for example. Ie, the names should probably be part 1, part 2, etc.
None of this would be necessary if there was a way of giving the shape produced by the TextField a custom name. That way, you could add as may TextFields as you liked, and then place them using the ZoneProxy code. I'm not sure if this would be possible.

Can't access/read SIM phonebook in Nokia

am trying to access both the Phone's phonebook and SIM phonenook on Nokia 5130c-2 XpressMusic.
The app runs without errors but it only returns the numbers from the phone's Phonebook. When I list the available phonebooks using this code
String[] all_contact_lists=PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
it gives me both the Phonebook and SIM card lists. i.e
1. Phone
2. SIM
I have tried explicitly reading from the SIM card using this code but it still returns nothing(even though I have numbers saved in the SIM card.)
Code:
ContactList clist = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY,
"SIM");
Here's my complete code::
import javax.microedition.midlet.*;
import javax.microedition.pim.*;
import com.sun.lwuit.*;
import java.util.*;
public class contacts extends MIDlet
{
private List my_list=new List();
private String[] names=null;
public void startApp()
{
Display.init(this);
Form my_form=new Form("Contacts List");
String[] all_contact_lists=PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
//Iterate through available phonebooks
for(int db=0; db<all_contact_lists.length; db++)
{
try {
ContactList clist = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY,
all_contact_lists[db]);
Enumeration contacts=clist.items();
while(contacts.hasMoreElements())
{
Contact contact=(Contact)contacts.nextElement();
try{
String phone_contact="";
names=contact.getStringArray(Contact.NAME, 0);
for(int i=0; i<names.length; i++)
{
if(names[i]!=null)
phone_contact+=" "+names[i];
}
//my_list.addItem(phone_contact);
int phone_numbers=contact.countValues(Contact.TEL);
if(phone_numbers>0)
{
String number=contact.getString(Contact.TEL,0);
my_list.addItem(phone_contact+":"+number);
}
else
{
my_list.addItem(phone_contact);
}
//clist.removeContact(contact);
}
catch (Throwable t) {
t.printStackTrace();
}
}
} catch (PIMException ex) {
ex.printStackTrace();
}
}
//my_list.addItem(all_contact_lists);
my_list.setRenderingPrototype("WWWWWWWWWWWWWWWWWWWW");
my_form.addComponent(my_list);
my_form.show();
}
public void pauseApp(){}
public void destroyApp(boolean unconditional){}
}
If you are using the phone number for a text or to call you can do that with only one line of code. Its now evident that phone software issues can affect the way the app accesses the PIM API. Also, if memory in use in the phones contact settings is set to SIM(alone), you can't access contacts in phone memory and vice versa, make sure both are in use. Try this if you still have an issue,
//make a text field in LWUIT that is declared globally
PhnNmbr = new TextField();
//set it to only accept phonenumber
PhnNmbr.setConstraint(TextField.PHONENUMBER);
//tell the user how to access phonebook
PhnNmbr.setHint("Press T9 then 'Search' to search phonebook");
//add a button or command
//that either sends an sms to
//or calls the number in the text field
//or anything else you want to do with it
When the user presses T9, the TextField is considered an LCDUI text field with parameter PHONENUMBER which allows it to search for contacts in both Sim and phone memory, thats why you'll notice a Search command(usually at the bottom center). Also make sure that the memory in use for the phone is set to both Phone and Sim.
An excerpt from PIM javadoc
PIMItems reference its data through fields. A field is a grouping of
data values that all have similar characteristics. An example of a
field is TEL, which indicates data values for that particular field
are telephone numbers. Classes implementing the PIMItem interface
defines the possible fields that for that specific class (e.g TEL is
defined in the Contact interface as a field that a contact may
support).
PIM implementations are not required to support all of the possible
fields defined in the classes implementing the PIMItem interface. This
is because no native PIM databases contain all of the fields defined
in this API. The PIMList that a PIMItem belongs to determines what
fields a PIMItem can support and store (all PIMItems in a particular
PIMList support the same set of fields). The
PIMList.getSupportedFields() method from a particular PIMItem's
PIMList is used to find out what fields are supported within this
item. Since not all possible fields are actually supported in a
particular PIMItem, all fields should be checked for support in the
item's PIMList using PIMList.isSupportedField(int) prior to being used
in any retrieval or storage method.
Each field has the following pieces of information available for it:
Zero or more data values associated with the Field
Attributes for data values for the Field
Descriptive label for the Field
Data Type of the data associated with the Field
Complete PIM javadoc can be read at this link.
Check if the device support's PIM Fields Contact.NAME and Contact.TEL on your device. If not then you need to call PIMList.getSupportedFields() to get the supported field on device and accordingly fetch the name and the telephone number for that device. If I remember correct, the alternative field for name is Contact.FORMATTED_NAME.

Resources