I'm building an app were i add tablerows to a view programmatically. I add a deletebutton to every row that is an ImageButton. Now i have a few questions.
Can i use an ImageButton for this?
How do i get the tablerow id
where the deletebutton was clicked?
How can i convert the eventargs
from a clickhandler into MenuItemOnMenuItemClickEventArgs or vice
versa?
How should my clickhandler look like?
Here is my sourcecode:
public class CalculatorSide2 : Activity
{
private Button stepButton;
private IntentHelper intentHelper = new IntentHelper();
private string age;
private string estLife;
private string estPens;
private string[] pensions;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
intentHelper.IntentSide2(Intent, out age, out estLife,out estPens);
SetContentView(Resource.Layout.calculatorside2);
TableLayout tl_layout = FindViewById<TableLayout>(Resource.Id.tableLayout1);
ImageView plusButton = FindViewById<ImageView>(Resource.Id.plusButton);
stepButton = FindViewById<Button>(Resource.Id.cside2stepButton);
plusButton.Click += (sender, e) =>
{
PopupMenu popupMenu = new PopupMenu(this, plusButton);
popupMenu.Inflate(Resource.Menu.popupmenu);
fillPopupMenu(popupMenu);
popupMenu.Show();
popupMenu.MenuItemClick += (s1, arg) =>
{
string info = arg.Item.TitleFormatted.ToString();
string id = arg.Item.ItemId.ToString();
var inputDialog = new AlertDialog.Builder(this);
EditText userInput = new EditText(this);
userInput.InputType = (Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);
inputDialog.SetTitle(info);
inputDialog.SetView(userInput);
inputDialog.SetPositiveButton("Ok", (ss, ee) =>
{
TextView rowInfo = new TextView(this);
rowInfo.SetLines(2);
rowInfo.TextSize = 20;
rowInfo.SetTextColor(Android.Graphics.Color.Black);
rowInfo.Text = info + ": \n" + userInput.Text + "€";
ImageButton delete = new ImageButton(this);
delete.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.delete_icon));
TableRow row = new TableRow(this);
row.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
row.SetBackgroundColor(Android.Graphics.Color.Rgb(255, 153, 0));
row.SetPadding(0, 0, 0, 30);
row.AddView(rowInfo);
row.AddView(delete);
tl_layout.AddView(row);
});
inputDialog.SetNegativeButton("Cancel", (se, es) => { });
inputDialog.Show();
};
};
stepButton.Click += (object sender, EventArgs e) =>
{
var step = new Intent(this, typeof(CalculatorSide3));
step.PutExtra("Age", age);
step.PutExtra("EstPens", estPens);
step.PutExtra("EstLife", estLife);
step.PutStringArrayListExtra("Pensions", pensions);
StartActivity(step);
};
}
private void fillPopupMenu(PopupMenu menu)
{
int groupId = 0;
int i = 0;
int menuItemId = Android.Views.Menu.First;
int menuItemOrder = Android.Views.Menu.None;
foreach (var item in Enum.GetNames(typeof(PopupMenuItems)))
{
string itemString = item.ToString();
menu.Menu.Add(groupId, menuItemId + i, menuItemOrder + i, itemString.Replace("_", " "));
i++;
}
}
}
I hope someone understands what i mean, bc english is not my native language.
public class CalculatorSide2 : Activity
{
private Button stepButton;
private IntentHelper intentHelper = new IntentHelper();
private string age;
private string estLife;
private string estPens;
private string[] pensions;
private Dictionary<int,string> temp;
private TableLayout tl_layout;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
intentHelper.IntentSide2(Intent, out age, out estLife,out estPens);
SetContentView(Resource.Layout.calculatorside2);
tl_layout = FindViewById<TableLayout>(Resource.Id.tableLayout1);
ImageView plusButton = FindViewById<ImageView>(Resource.Id.plusButton);
stepButton = FindViewById<Button>(Resource.Id.cside2stepButton);
temp = new Dictionary<int,string>();
int i = 0;
plusButton.Click += (sender, e) =>
{
PopupMenu popupMenu = new PopupMenu(this, plusButton);
popupMenu.Inflate(Resource.Menu.popupmenu);
fillPopupMenu(popupMenu);
popupMenu.Show();
popupMenu.MenuItemClick += (s1, arg) =>
{
string info = arg.Item.TitleFormatted.ToString();
string id = arg.Item.ItemId.ToString();
var inputDialog = new AlertDialog.Builder(this);
EditText userInput = new EditText(this);
userInput.InputType = (Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);
inputDialog.SetTitle(info);
inputDialog.SetView(userInput);
inputDialog.SetPositiveButton("Ok", (ss, ee) =>
{
TextView rowInfo = new TextView(this);
rowInfo.SetLines(2);
rowInfo.TextSize = 20;
rowInfo.SetTextColor(Android.Graphics.Color.Black);
rowInfo.Text = info + ": \n" + userInput.Text + "€";
ImageButton delete = new ImageButton(this);
delete.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.delete_icon));
delete.Focusable = false;
delete.Clickable = false;
TableRow row = new TableRow(this);
row.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
row.SetBackgroundColor(Android.Graphics.Color.Rgb(255, 153, 0));
row.SetPadding(0, 0, 0, 30);
row.Id = 10 + i;
row.Click += new EventHandler(HandleClick);
row.AddView(rowInfo);
row.AddView(delete);
tl_layout.AddView(row);
temp.Add(row.Id,userInput.Text);
i++;
});
inputDialog.SetNegativeButton("Cancel", (se, es) => { });
inputDialog.Show();
};
};
stepButton.Click += (object sender, EventArgs e) =>
{
if (temp.Count != 0)
{
pensions = new string[temp.Count];
var j = 0;
foreach (KeyValuePair<int, string> pair in temp)
{
pensions[j] = pair.Value;
j++;
}
}
else
{
pensions = new string[0];
}
var step = new Intent(this, typeof(CalculatorSide3));
step.PutExtra("Age", age);
step.PutExtra("EstPens", estPens);
step.PutExtra("EstLife", estLife);
step.PutStringArrayListExtra("Pensions", pensions);
StartActivity(step);
};
}
private void fillPopupMenu(PopupMenu menu)
{
int groupId = 0;
int i = 0;
int menuItemId = Android.Views.Menu.First;
int menuItemOrder = Android.Views.Menu.None;
foreach (var item in Enum.GetNames(typeof(PopupMenuItems)))
{
string itemString = item.ToString();
menu.Menu.Add(groupId, menuItemId + i, menuItemOrder + i, itemString.Replace("_", " "));
i++;
}
}
public void HandleClick(object sender, EventArgs e)
{
var clickedTR = sender as TableRow;
int trId = clickedTR.Id;
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Löschen");
builder.SetMessage("Möchten Sie den Eintrag wirklich löschen?");
builder.SetPositiveButton("Ja", (ssr,args) => {
temp.Remove(trId);
tl_layout.RemoveView(clickedTR);
});
builder.SetNegativeButton("Nein",(sse,arge) => { });
builder.SetCancelable(false);
builder.Show();
}
}
Related
I'm using MpAndroidChart for my app. I can create piechart successfully but I have a question. I want an event listener to handle item clicked when user touched one of piechart item.How can I do it?
My Code is as below;
>
int[] ydata = { 5, 2, 3, 1 };
string[] xdata= { "one","two","three","four" };
PieChart pieChart;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
pieChart = FindViewById<PieChart>(Resource.Id.chart1);
pieChart.RotationEnabled = true;
pieChart.HoleRadius = 0;
pieChart.SetTransparentCircleAlpha(0);
pieChart.SetCenterTextSize(20);
pieChart.SetDrawEntryLabels(true);
pieChart.SetUsePercentValues(false);
pieChart.AnimateX(1000, Easing.EasingOption.EaseInOutCubic);
pieChart.Description.Text = "test";
addDataSet();
pieChart.SetTouchEnabled(true);
}
private void addDataSet()
{
List<PieEntry> yEntry = new List<PieEntry>();
List<string> xEntry = new List<string>();
for (int i = 0; i < ydata.Length; i++)
{
yEntry.Add(new PieEntry(ydata[i],xdata[i]));
}
for (int i = 0; i < xdata.Length; i++)
{
xEntry.Add(xdata[i]);
}
PieDataSet piedataset = new PieDataSet(yEntry, "test");
piedataset.SliceSpace = 0;
piedataset.ValueTextSize = 20;
int[] colors= { Color.Blue,Color.Red,Color.Green,Color.White};
piedataset.SetColors(colors);
Legend legend = pieChart.Legend;
legend.Form=Legend.LegendForm.Circle;
PieData pieData = new PieData(piedataset);
//pieData.SetValueFormatter(new int);
pieData.SetValueTextColor(Color.White);
pieChart.Data = (pieData);
pieChart.Invalidate();
}
You could use SetOnChartValueSelectedListener to set a ChartValueSelectedListener.
For example, in onCreate():
pieChart.SetOnChartValueSelectedListener(new MyListener(this));
And the listener:
public class MyListener : Java.Lang.Object, IOnChartValueSelectedListenerSupport
{
Context mContext;
public MyListener(Context context) {
this.mContext = context;
}
public void OnNothingSelected()
{
// throw new NotImplementedException();
}
public void OnValueSelected(Entry e, Highlight h)
{
PieEntry pe = (PieEntry)e;
Toast.MakeText(mContext, pe.Label+ " is clicked, value is "+ pe.Value, ToastLength.Short).Show();
}
}
The result is:
I am getting an error of 1084 in flash builder project. I want to share the file which I am getting an error.
package com.bykd.g4m.lobby.data
{
import com.bykd.xcom.data.DataObject;
import flash.utils.Dictionary;
import com.bykd.xcom.data.Room;
import com.bykd.xcom.data.User;
import com.bykd.g4m.lobby.GameManager;
public class GameInfo extends DataObject
{
public static const INIT_STATUS:Number = 1;
public static const BET_OPTION:String = "BET";
public static const EMPTY_STATUS:Number = 0;
public static const STATUS_ELEMENT:String = "STATUS";
public static const DRAW_OPTION:String = "DRAW";
public static const WINROUNDS_OPTION:String = "WINROUNDS";
public static const CREATE_STATUS:Number = 2;
public static const GAME_ELEMENT:String = "GAME";
public static const OPTIONS_ELEMENT:String = "OPTIONS";
public static const OBJECT_ELEMENT:String = "GAMEINFO";
public static const TIME_OPTION:String = "TIME";
public static const CREATOR_ELEMENT:String = "CREATOR";
public static const READY_STATUS:Number = 3;
public static const SCORE_OPTION:String = "SCORE";
public static const OPPONENT_ELEMENT:String = "OPPONENT";
private var __id:uint;
public var gameStatus:Number;
public var gameOptions:Dictionary;
public var gameRoom:Room;
public var gameOpponent:User;
public var gameCreator:User;
public var gameJoined:Boolean;
public function GameInfo(id:uint = 0, status:Number = 0, creator:User = null)
{
super();
__id = id;
gameStatus = status;
gameCreator = creator;
gameOptions = new Dictionary();
gameJoined = false;
}
public static function parseHeader(xml:XML) : Object
{
var nodeName:String = xml.localName();
var nodeParts:Array = nodeName.split("_",2);
return {
"element":nodeParts[0],
"id":parseInt(nodeParts[1])
};
}
override public function toXML() : XML
{
return new XML("<" + (OBJECT_ELEMENT + "_" + ID) + "/>");
}
override public function toXMLData(full:Boolean = true) : XML
{
var dataXML:XML = null;
var key:* = null;
var xml:XML = toXML();
if(full)
{
if(!isNaN(gameStatus))
{
dataXML = new XML("<" + STATUS_ELEMENT + "/>");
dataXML.appendChild(gameStatus.toString());
xml.appendChild(dataXML);
}
if(gameCreator != null)
{
dataXML = new XML("<" + CREATOR_ELEMENT + "/>");
dataXML.appendChild(gameCreator.toXML());
xml.appendChild(dataXML);
}
if(gameOptions != null)
{
dataXML = new XML("<" + OPTIONS_ELEMENT + "/>");
for(key in gameOptions)
{
**dataXML.appendChild(new XML("<" + key + ">" + ({gameOptions[key]}) + "</" + key + ">"));**
}
xml.appendChild(dataXML);
}
if(gameOpponent != null)
{
dataXML = new XML("<" + OPPONENT_ELEMENT + "/>");
dataXML.appendChild(gameOpponent.toXML());
xml.appendChild(dataXML);
}
if(gameRoom != null)
{
dataXML = new XML("<" + GAME_ELEMENT + "/>");
dataXML.appendChild(gameRoom.toXML());
xml.appendChild(dataXML);
}
}
return xml;
}
public function get ID() : uint
{
return __id;
}
override public function fromXML(xml:XML) : void
{
var dataXML:XML = null;
var userXML:XML = null;
var roomXML:XML = null;
var gameManager:GameManager = null;
var node:XML = null;
var key:String = null;
var header:Object = parseHeader(xml);
if(header.element == OBJECT_ELEMENT)
{
__id = header.id;
gameManager = GameManager.getInstance();
dataXML = xml.elements(STATUS_ELEMENT)[0];
if(dataXML != null)
{
gameStatus = Number(dataXML.toString());
}
dataXML = xml.elements(CREATOR_ELEMENT)[0];
if(dataXML != null)
{
userXML = dataXML.elements(User.OBJECT_ELEMENT)[0];
if(userXML != null && User.checkID(userXML))
{
gameCreator = gameManager.userService.getUserEntity(User.parseID(userXML));
}
}
dataXML = xml.elements(OPTIONS_ELEMENT)[0];
if(dataXML != null)
{
gameOptions = new Dictionary();
for each(node in dataXML.elements())
{
key = node.localName();
gameOptions[key] = node.toString();
}
}
dataXML = xml.elements(OPPONENT_ELEMENT)[0];
if(dataXML != null && dataXML.hasOwnProperty(User.OBJECT_ELEMENT))
{
userXML = dataXML.elements(User.OBJECT_ELEMENT)[0];
if(userXML != null && User.checkID(userXML))
{
gameOpponent = gameManager.userService.getUserEntity(User.parseID(userXML));
}
}
dataXML = xml.elements(GAME_ELEMENT)[0];
if(dataXML != null && dataXML.hasOwnProperty(Room.OBJECT_ELEMENT))
{
roomXML = dataXML.elements(Room.OBJECT_ELEMENT)[0];
if(roomXML != null && Room.checkID(roomXML))
{
gameRoom = gameManager.roomService.getRoomEntity(Room.parseID(roomXML));
}
}
}
}
}
}
The problem is in this line according to the flash builder:
dataXML.appendChild(new XML("<" + key + ">" + ({gameOptions[key]}) + "</" + key + ">"));
the program says that multiple markers at this line.
it is a syntax error . thanks in advance.
I have an entry field at the bottom of the screen in one of my projects. However, on iOS, when you click the entry field, the keyboard is displayed over top the entry field and obscures the vision of it. Therefore, people can't see what they're typing.
How can I solve this problem? Is there a way that I can move the entry field so it is displayed above the keyboard when in focus?
//NOTE: the entry field that needs to be moved is userEntry
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using CloudClubv1._2_;
using Backend;
using Xamarin.Forms;
using System.Collections.ObjectModel;
namespace FrontEnd
{
public class ClubChatPage : ContentPage
{
public static ObservableCollection<FrontComment> CurrentCommentsList;
ObservableCollection<FrontComment> commentsList;
ColorHandler ch;
Entry userEntry;
ParentFrontClub club;
bool isMember;
Image bBack, bSettings;
public static ListView listView;
TapGestureRecognizer settingsTgr, backButtonTgr;
public ClubChatPage(ParentFrontClub club, List<DBItem> chatList, List<Account> commentUsers, List<Account> requestUsersList, bool isMember)
{
this.isMember = isMember;
settingsTgr = new TapGestureRecognizer();
settingsTgr.Tapped += SettingsTgr_Tapped;
backButtonTgr = new TapGestureRecognizer();
backButtonTgr.Tapped += BackButtonTgr_Tapped;
this.club = club;
ch = new ColorHandler();
this.BackgroundColor = Color.Black;
this.Title = club.Title;
NavigationPage.SetHasNavigationBar(this, false);
this.commentsList = new ObservableCollection<FrontComment>();
int clubRequestCount = 0;
System.Diagnostics.Debug.WriteLine(chatList.Count.ToString());
chatList.Reverse();
for (int i = 0; i < chatList.Count; i++)
{
if (chatList[i].GetType() == typeof(Comment))
{
if (commentUsers[i] != null)
{
this.commentsList.Add(new FrontComment((Comment)chatList[i], commentUsers[i - clubRequestCount]));
}
}
else if (chatList[i].GetType() == typeof(ClubRequest))
{
this.commentsList.Add(new FrontComment((ClubRequest)chatList[i], requestUsersList[clubRequestCount], this.isMember));
clubRequestCount++;
}
}
CurrentCommentsList = this.commentsList;
updatePage();
}
private void updatePage()
{
bBack = new Image
{
Source = FileImageSource.FromFile("arrow_back.png"),
WidthRequest=30,
// Scale = ,
HorizontalOptions = LayoutOptions.StartAndExpand,
VerticalOptions = LayoutOptions.Center,
HeightRequest = 30,
Aspect = Aspect.AspectFill
};
bBack.GestureRecognizers.Add(backButtonTgr);
var actionBarLabel = new Label
{
Text = this.club.Title,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.Center,
TextColor = ch.fromStringToColor("white"),
FontSize = 22,
FontAttributes = FontAttributes.Bold
};
bSettings = new Image
{
Source = ImageSource.FromFile("settings.png"),
Scale = .8,
HorizontalOptions = LayoutOptions.EndAndExpand,
VerticalOptions = LayoutOptions.Center
};
bSettings.GestureRecognizers.Add(settingsTgr);
var actionBarLayout = new StackLayout
{
Children =
{
bBack,
actionBarLabel,
bSettings
},
HeightRequest= 30,
Orientation = StackOrientation.Horizontal,
BackgroundColor = ch.fromStringToColor(this.club.clubColor),
VerticalOptions = LayoutOptions.Center,
Padding = new Thickness(10,10,0,10)
};
listView = new ListView
{
ItemsSource = CurrentCommentsList,
ItemTemplate = new DataTemplate(typeof(CommentViewCell)),
HasUnevenRows = true,
SeparatorVisibility = SeparatorVisibility.None,
SeparatorColor = ch.fromStringToColor("white"),
BackgroundColor = ch.fromStringToColor("white")
};
if (CurrentCommentsList.Count != 0) {
listView.ScrollTo (CurrentCommentsList [CurrentCommentsList.Count () - 1], ScrollToPosition.End, false);
}
listView.ItemTapped += ListView_ItemTapped;
MessagingCenter.Subscribe<CommentViewCell, FrontComment>(this, "hi", async (sender, args) =>
{
var comment = (FrontComment)args;
var answer = await DisplayAlert("Report User", "Do you really want to report " + comment.AuthorUsername + "?", "Yes", "No");
if (answer)
{
await App.dbWrapper.CreateBan(comment.AuthorId, comment.Id, App.dbWrapper.GetUser().Id);
comment.ShowReport = false;
comment.UpdateProperty("ShowReport");
}
else
{
}
//updatePage();
});
userEntry = new Entry
{
BackgroundColor = ch.fromStringToColor("white"),
TextColor = ch.fromStringToColor("black"),
VerticalOptions = LayoutOptions.End,
IsEnabled = isMember,
Placeholder = "Tap to chat"
};
userEntry.Completed += UserEntry_Completed;
userEntry.Focused += UserEntry_Focused;
Label lEmptyChat = new Label
{
Text = "There are no messages. Type below!",
FontSize = 38,
TextColor = ch.fromStringToColor("black"),
XAlign = TextAlignment.Center,
YAlign = TextAlignment.Center,
VerticalOptions = LayoutOptions.FillAndExpand
};
if (CurrentCommentsList.Count != 0)
{
Content = new StackLayout
{
Children =
{
actionBarLayout,
listView,
userEntry
},
BackgroundColor = ch.fromStringToColor("lightGray"),
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
}
else
{
Content = new StackLayout
{
Children =
{
actionBarLayout,
lEmptyChat,
userEntry
},
BackgroundColor = ch.fromStringToColor("lightGray"),
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
}
}
private void UserEntry_Focused(object sender, FocusEventArgs e)
{
}
private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
var item = (FrontComment)e.Item;
for(int i = 0; i < CurrentCommentsList.Count; i++)
{
if (CurrentCommentsList[i].ShowReport==true)
{
CurrentCommentsList[i].ShowReport = false;
CurrentCommentsList[i].UpdateProperty("ShowReport");
}
}
for (int i = 0; i < CurrentCommentsList.Count; i++)
{
if (CurrentCommentsList[i].Id == item.Id && CurrentCommentsList[i].ClubRequestBool == false)
{
CurrentCommentsList[i].ShowReport = true;
CurrentCommentsList[i].UpdateProperty("ShowReport");
}
}
// updatePage();
}
private async void UserEntry_Completed(object sender, EventArgs e)
{
if (userEntry.Text != "")
{
// var joinClub = await App.dbWrapper.JoinClub(club.Id);
var commentOutput = await App.dbWrapper.CreateComment(userEntry.Text, club.Id);
//System.Diagnostics.Debug.WriteLine("OUTPUT: "+joinClub);
userEntry.Text = "";
listView.ScrollTo(CurrentCommentsList[CurrentCommentsList.Count() - 1], ScrollToPosition.End, false);
// updatePage();
}
}
private async void BackButtonTgr_Tapped(object sender, EventArgs e)
{
await App.dbWrapper.RemoveCurrentClubId();
var btn = sender as Image;
btn.IsEnabled = false;
await Navigation.PopAsync();
btn.IsEnabled = true;
}
private async void SettingsTgr_Tapped(object sender, EventArgs e)
{
//var btn = sender as TapGestureRecognizer;
//btn.Tapped -= SettingsTgr_Tapped;
// bSettings.GestureRecognizers.Remove(settingsTgr);
var tagsList = await App.dbWrapper.GetTags(club.Id);
var usersList = await App.dbWrapper.GetClubMembers(club.Id);
var frontClubMemberList = new List<FrontClubMember>();
var isMember = await App.dbWrapper.IsMember(club.Id);
var founderAccount = await App.dbWrapper.GetAccount(club.founderId);
var prevRating = await App.dbWrapper.GetUserRating(club.Id);
var myFriendRequests = await App.dbWrapper.GetFriendRequests();
for (int i = 0; i < usersList.Count; i++)
{
var storedFriendship = await App.dbWrapper.GetFriendship(usersList[i].Id);
if(storedFriendship == 1) //Indicates request was sent from either user
{
// var accReq = App.dbWrapper.GetAccountFriendRequests(usersList[i].Id);
storedFriendship = 3;
var accReq = new List<FriendRequest>();
for (int j = 0; j < myFriendRequests.Count; j++)
{
if (myFriendRequests[j].AuthorId == usersList[i].Id)
{
storedFriendship = 1;//indicates request was sent by other acc
}
}
}
if (usersList[i].Id == App.dbWrapper.GetUser().Id) storedFriendship= 4;
frontClubMemberList.Add(new FrontClubMember(usersList[i], storedFriendship));
}
var btn = sender as Image;
btn.GestureRecognizers.Remove(settingsTgr);
btn.InputTransparent = true;
await Navigation.PushAsync(new ChatInfoPage(tagsList, club, frontClubMemberList, isMember, founderAccount.Username, prevRating));
btn.GestureRecognizers.Add(settingsTgr);
btn.InputTransparent = false;
}
//used by backend push notifications to scroll to new comments
public static void ScrollToCurrent(){
listView.ScrollTo(CurrentCommentsList[CurrentCommentsList.Count() - 1], ScrollToPosition.End, false);
}
}
}
Simply wrap the content in a ScrollView - this will allow the Entry fields to be moved when the Keyboard appears.
I have made list view with checkboxes. I have read similar articles n many people have suggested to do changes in drawlistRow but it is not happening. Can u suggest me where should i change to make it a multi line list.The code snippet is :
Updated: I updated my code and it is still not working
public class CheckboxListField extends MainScreen implements ListFieldCallback, FieldChangeListener {
int mCheckBoxesCount = 5;
private Vector _listData = new Vector();
private ListField listField;
private ContactList blackBerryContactList;
private BlackBerryContact blackBerryContact;
private Vector blackBerryContacts;
private MenuItem _toggleItem;
ButtonField button;
BasicEditField mEdit;
CheckboxField cb;
CheckboxField[] chk_service;
HorizontalFieldManager hm4;
CheckboxField[] m_arrFields;
boolean mProgrammatic = false;
public static StringBuffer sbi = new StringBuffer();
VerticalFieldManager checkBoxGroup = new VerticalFieldManager();
LabelField task;
//A class to hold the Strings in the CheckBox and it's checkbox state (checked or unchecked).
private class ChecklistData
{
private String _stringVal;
private boolean _checked;
ChecklistData()
{
_stringVal = "";
_checked = false;
}
ChecklistData(String stringVal, boolean checked)
{
_stringVal = stringVal;
_checked = checked;
}
//Get/set methods.
private String getStringVal()
{
return _stringVal;
}
private boolean isChecked()
{
return _checked;
}
private void setStringVal(String stringVal)
{
_stringVal = stringVal;
}
private void setChecked(boolean checked)
{
_checked = checked;
}
//Toggle the checked status.
private void toggleChecked()
{
_checked = !_checked;
}
}
CheckboxListField()
{
_toggleItem = new MenuItem("Change Option", 200, 10)
{
public void run()
{
//Get the index of the selected row.
int index = listField.getSelectedIndex();
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index);
//Invalidate the modified row of the ListField.
listField.invalidate(index);
if (index != -1 && !blackBerryContacts.isEmpty())
{
blackBerryContact =
(BlackBerryContact)blackBerryContacts.
elementAt(listField.getSelectedIndex());
ContactDetailsScreen contactDetailsScreen =
new ContactDetailsScreen(blackBerryContact);
UiApplication.getUiApplication().pushScreen(contactDetailsScreen);
}
}
};
listField = new ListField();
listField.setRowHeight(getFont().getHeight() * 2);
listField.setCallback(this);
reloadContactList();
//CheckboxField[] cb = new CheckboxField[blackBerryContacts.size()];
for(int count = 0; count < blackBerryContacts.size(); ++count)
{
BlackBerryContact item =
(BlackBerryContact)blackBerryContacts.elementAt(count);
String displayName = getDisplayName(item);
CheckboxField cb = new CheckboxField(displayName, false);
cb.setChangeListener(this);
add(cb);
listField.insert(count);
}
blackBerryContacts.addElement(cb);
add(checkBoxGroup);
}
protected void makeMenu(Menu menu, int instance)
{
menu.add(new MenuItem("Get", 2, 2) {
public void run() {
for (int i = 0; i < checkBoxGroup.getFieldCount(); i++) {
//for(int i=0; i<blackBerryContacts.size(); i++) {
CheckboxField checkboxField = (CheckboxField)checkBoxGroup
.getField(i);
if (checkboxField.getChecked()) {
sbi.append(checkboxField.getLabel()).append("\n");
}
}
Dialog.inform("Selected checkbox text::" + sbi);
}
});
super.makeMenu(menu, instance);
}
private boolean reloadContactList()
{
try {
blackBerryContactList =
(ContactList)PIM.getInstance().openPIMList
(PIM.CONTACT_LIST, PIM.READ_ONLY);
Enumeration allContacts = blackBerryContactList.items();
blackBerryContacts = enumToVector(allContacts);
listField.setSize(blackBerryContacts.size());
return true;
} catch (PIMException e)
{
return false;
}
}
//Convert the list of contacts from an Enumeration to a Vector
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()) {
v.addElement(contactEnum.nextElement());
}
return v;
}
public void drawListRow(ListField list, Graphics graphics, int index, int y, int w)
{
ChecklistData currentRow = (ChecklistData)this.get(list, index);
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked())
{
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else
{
rowString.append(Characters.BALLOT_BOX);
}
//Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
//graphics.drawText("ROW", 0, y, 0, w);
//String rowNumber = "one";
//Draw the text.
graphics.drawText(rowString.toString(), 0, y, 0, w);
/*graphics.drawText("ROW " + rowNumber, y, 0, w);
graphics.drawText("ROW NAME", y, 20, w);
graphics.drawText("row details", y + getFont().getHeight(), 20, w); */
}
public void drawRow(Graphics g, int x, int y, int width, int height) {
// Arrange the cell fields within this row manager.
layout(width, height);
// Place this row manager within its enclosing list.
setPosition(x, y);
// Apply a translating/clipping transformation to the graphics
// context so that this row paints in the right area.
g.pushRegion(getExtent());
// Paint this manager's controlled fields.
subpaint(g);
g.setColor(0x00CACACA);
g.drawLine(0, 0, getPreferredWidth(), 0);
// Restore the graphics context.
g.popContext();
}
public static String getDisplayName(Contact contact)
{
if (contact == null)
{
return null;
}
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
if (displayName != null) {
final String namePrefix = name[Contact.NAME_PREFIX];
if (namePrefix != null) {
displayName = namePrefix + " " + displayName;
}
return displayName;
}
}
return displayName;
}
//Returns the object at the specified index.
public Object get(ListField list, int index)
{
return _listData.elementAt(index);
/*if (listField == list)
{
//If index is out of bounds an exception will be thrown,
//but that's the behaviour we want in that case.
//return blackBerryContacts.elementAt(index);
_listData = (Vector) blackBerryContacts.elementAt(index);
return _listData.elementAt(index);
}
return null;*/
}
//Returns the first occurence of the given String, bbeginning the search at index,
//and testing for equality using the equals method.
public int indexOfList(ListField list, String p, int s)
{
//return listElements.getSelectedIndex();
//return _listData.indexOf(p, s);
return -1;
}
//Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list)
{
return Graphics.getScreenWidth();
//return Display.getWidth();
}
public void fieldChanged(Field field, int context) {
boolean mProgrammatic = false;
if (!mProgrammatic) {
mProgrammatic = true;
CheckboxField cbField = (CheckboxField) field;
int index = blackBerryContacts.indexOf(cbField);
if (cbField.getChecked())
{
for(int i=0;i<blackBerryContacts.size();i++)
{
Dialog.inform("Selected::" + cbField.getLabel());
sbi=new StringBuffer();
sbi.append(cbField.getLabel());
}
}
mProgrammatic = false;
}
}
This code may be improved with:
Using ListField instead of VerticalFieldManager + CheckboxField array (ListField is much more faster, 100+ controls may slow down UI)
Using simple array instead of vector in list data (it's faster)
Moving contacts load from UI thread (we should aware of blocking UI thread with heavy procedures like IO, networking or work with contact list)
Actually using ListField with two line rows has one issue: we have to set the same height for all rows in ListField. So there always will be two lines per row, no matter if we will use second line or not. But it's really better than UI performance issues.
See code:
public class CheckboxListField extends MainScreen implements
ListFieldCallback {
private ChecklistData[] mListData = new ChecklistData[] {};
private ListField mListField;
private Vector mContacts;
private MenuItem mMenuItemToggle = new MenuItem(
"Change Option", 0, 0) {
public void run() {
toggleItem();
};
};
private MenuItem mMenuItemGet = new MenuItem("Get", 0,
0) {
public void run() {
StringBuffer sbi = new StringBuffer();
for (int i = 0; i < mListData.length; i++) {
ChecklistData checkboxField = mListData[i];
if (checkboxField.isChecked()) {
sbi.append(checkboxField.getStringVal())
.append("\n");
}
}
Dialog.inform("Selected checkbox text::\n"
+ sbi);
}
};
// A class to hold the Strings in the CheckBox and it's checkbox state
// (checked or unchecked).
private class ChecklistData {
private String _stringVal;
private boolean _checked;
ChecklistData(String stringVal, boolean checked) {
_stringVal = stringVal;
_checked = checked;
}
// Get/set methods.
private String getStringVal() {
return _stringVal;
}
private boolean isChecked() {
return _checked;
}
// Toggle the checked status.
private void toggleChecked() {
_checked = !_checked;
}
}
CheckboxListField() {
// toggle list field item on navigation click
mListField = new ListField() {
protected boolean navigationClick(int status,
int time) {
toggleItem();
return true;
};
};
// set two line row height
mListField.setRowHeight(getFont().getHeight() * 2);
mListField.setCallback(this);
add(mListField);
// load contacts in separate thread
loadContacts.run();
}
protected Runnable loadContacts = new Runnable() {
public void run() {
reloadContactList();
// fill list field control in UI event thread
UiApplication.getUiApplication().invokeLater(
fillList);
}
};
protected Runnable fillList = new Runnable() {
public void run() {
int size = mContacts.size();
mListData = new ChecklistData[size];
for (int i = 0; i < mContacts.size(); i++) {
BlackBerryContact item = (BlackBerryContact) mContacts
.elementAt(i);
String displayName = getDisplayName(item);
mListData[i] = new ChecklistData(
displayName, false);
}
mListField.setSize(size);
}
};
protected void toggleItem() {
// Get the index of the selected row.
int index = mListField.getSelectedIndex();
if (index != -1) {
// Get the ChecklistData for this row.
ChecklistData data = mListData[index];
// Toggle its status.
data.toggleChecked();
// Invalidate the modified row of the ListField.
mListField.invalidate(index);
BlackBerryContact contact = (BlackBerryContact) mContacts
.elementAt(mListField
.getSelectedIndex());
// process selected contact here
}
}
protected void makeMenu(Menu menu, int instance) {
menu.add(mMenuItemToggle);
menu.add(mMenuItemGet);
super.makeMenu(menu, instance);
}
private boolean reloadContactList() {
try {
ContactList contactList = (ContactList) PIM
.getInstance()
.openPIMList(PIM.CONTACT_LIST,
PIM.READ_ONLY);
Enumeration allContacts = contactList.items();
mContacts = enumToVector(allContacts);
mListField.setSize(mContacts.size());
return true;
} catch (PIMException e) {
return false;
}
}
// Convert the list of contacts from an Enumeration to a Vector
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()) {
v.addElement(contactEnum.nextElement());
}
return v;
}
public void drawListRow(ListField list,
Graphics graphics, int index, int y, int w) {
Object obj = this.get(list, index);
if (obj != null) {
ChecklistData currentRow = (ChecklistData) obj;
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked()) {
rowString
.append(Characters.BALLOT_BOX_WITH_CHECK);
} else {
rowString.append(Characters.BALLOT_BOX);
}
// Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
// Draw the text.
graphics.drawText(rowString.toString(), 0, y,
0, w);
String secondLine = "Lorem ipsum dolor sit amet, "
+ "consectetur adipiscing elit.";
graphics.drawText(secondLine, 0, y
+ getFont().getHeight(),
DrawStyle.ELLIPSIS, w);
} else {
graphics.drawText("No rows available.", 0, y,
0, w);
}
}
public static String getDisplayName(Contact contact) {
if (contact == null) {
return null;
}
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(
Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
if (displayName != null) {
final String namePrefix = name[Contact.NAME_PREFIX];
if (namePrefix != null) {
displayName = namePrefix + " "
+ displayName;
}
return displayName;
}
}
return displayName;
}
// Returns the object at the specified index.
public Object get(ListField list, int index) {
Object result = null;
if (mListData.length > index) {
result = mListData[index];
}
return result;
}
// Returns the first occurrence of the given String,
// beginning the search at index, and testing for
// equality using the equals method.
public int indexOfList(ListField list, String p, int s) {
return -1;
}
// Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list) {
return Graphics.getScreenWidth();
// return Display.getWidth();
}
}
Have a nice coding!
Below is my application code. i want alarm to ring on my blackberry on every 6 of this month whether this apllication is running or not. please guide me in details i am a beginner.
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
import net.rim.device.api.util.*;
import java.util.*;
import java.lang.String.*;
public class ListChk extends UiApplication
{
String getFirstName;
String getLastName;
String getEmail;
String getGender;
String getStatus;
String getCompany;
/*declaring text fields for user input*/
private AutoTextEditField firstName;
private AutoTextEditField lastName;
private AutoTextEditField company;
private EmailAddressEditField email;
/*declaring choice field for user input*/
private ObjectChoiceField gender;
/*declaring check box field for user input*/
private CheckboxField status;
//Declaring button fields
private ButtonField save;
private ButtonField close;
private ButtonField List;
private ButtonField search;
/*declaring vector*/
private static Vector _data;
/*declaring persistent object*/
private static PersistentObject store;
/*creating an entry point*/
public static void main(String[] args)
{
ListChk objListChk = new ListChk();
objListChk.enterEventDispatcher();
}//end of main of ListChk
public ListChk()
{
/*Creating an object of the main screen class to use its functionalities*/
MainScreen mainScreen = new MainScreen();
//setting title of the main screen
mainScreen.setTitle(new LabelField("Enter Your Data"));
//creating text fields for user input
firstName = new AutoTextEditField("First Name: ", "");
lastName= new AutoTextEditField("Last Name: ", "");
email= new EmailAddressEditField("Email:: ", "");
company = new AutoTextEditField("Company: ", "");
//creating choice field for user input
String [] items = {"Male","Female"};
gender= new ObjectChoiceField("Gender",items);
//creating Check box field
status = new CheckboxField("Active",true);
//creating Button fields and adding functionality using listeners
// A button that saves the the user data persistently when it is clicked
save = new ButtonField("Save",ButtonField.CONSUME_CLICK);
save.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
save();
}
});
// a button which closes the entire application when clicked
close = new ButtonField("Close",ButtonField.CONSUME_CLICK);
close.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
onClose();
}
});
// A button that shows the List of all Data being stored persistently
List = new ButtonField("List",ButtonField.CONSUME_CLICK);
List.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context){
// pushing the next screen
pushScreen(new ListScreen());
}
});
search = new ButtonField("Search",ButtonField.CONSUME_CLICK);
search.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
pushScreen(new SearchScreen());
}
});
//adding the input fields to the main screen
mainScreen.add(firstName);
mainScreen.add(lastName);
mainScreen.add(email);
mainScreen.add(company);
mainScreen.add(gender);
mainScreen.add(status);
// Addning horizontal field manager
HorizontalFieldManager horizontal = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
//adding buttons to the main screen in Horizontal field manager
horizontal.add(close);
horizontal.add(save);
horizontal.add(List);
horizontal.add(search);
//Adding the horizontal field manger to the screen
mainScreen.add(horizontal);
//adding menu items
mainScreen.addMenuItem(saveItem);
mainScreen.addMenuItem(getItem);
mainScreen.addMenuItem(Deleteall);
//pushing the main screen
pushScreen(mainScreen);
}
private MenuItem Deleteall = new MenuItem("Delete all",110,10)
{
public void run()
{
int response = Dialog.ask(Dialog.D_YES_NO,"Are u sure u want to delete entire Database");
if(Dialog.YES == response){
PersistentStore.destroyPersistentObject(0xdec6a67096f833cL);
Dialog.alert("Closing Application");
onClose();
}
else
Dialog.inform("Thank God");
}
};
//adding functionality to menu item "saveItem"
private MenuItem saveItem = new MenuItem("Save", 110, 10)
{
public void run()
{
//Calling save method
save();
}
};
//adding functionality to menu item "saveItem"
private MenuItem getItem = new MenuItem("Get", 110, 11)
{
//running thread for this menu item
public void run()
{
//synchronizing thread
synchronized (store)
{
//getting contents of the persistent object
_data = (Vector) store.getContents();
try{
for (int i = _data.size()-1; i >-1; i--)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
getFirstName = (info.getElement(StoreInfo.NAME));
getLastName = (info.getElement(StoreInfo.LastNAME));
getEmail = (info.getElement(StoreInfo.EMail));
getGender = (info.getElement(StoreInfo.GenDer));
getStatus = (info.getElement(StoreInfo.setStatus));
getCompany = (info.getElement(StoreInfo.setCompany));
//calling the show method
show();
}
}
}
catch(Exception e){}
}
}
};
public void save()
{
//creating an object of inner class StoreInfo
StoreInfo info = new StoreInfo();
//getting the test entered in the input fields
info.setElement(StoreInfo.NAME, firstName.getText());
info.setElement(StoreInfo.LastNAME,lastName.getText());
info.setElement(StoreInfo.EMail, email.getText());
info.setElement(StoreInfo.setCompany, company.getText());
info.setElement(StoreInfo.GenDer,gender.toString());
if(status.getChecked())
info.setElement(StoreInfo.setStatus, "Active");
else
info.setElement(StoreInfo.setStatus, "In Active");
//adding the object to the end of the vector
_data.addElement(info);
//synchronizing the thread
synchronized (store)
{
store.setContents(_data);
store.commit();
}
//resetting the input fields
Dialog.inform("Success!");
firstName.setText(null);
lastName.setText(null);
email.setText("");
company.setText(null);
gender.setSelectedIndex("Male");
status.setChecked(true);
}
//coding for persistent store
static {
store =
PersistentStore.getPersistentObject(0xdec6a67096f833cL);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new Vector());
store.commit();
}
}
_data = new Vector();
_data = (Vector) store.getContents();
}
//new class store info implementing persistable
private static final class StoreInfo implements Persistable
{
//declaring variables
private Vector _elements;
public static final int NAME = 0;
public static final int LastNAME = 1;
public static final int EMail= 2;
public static final int GenDer = 3;
public static final int setStatus = 4;
public static final int setCompany = 5;
public StoreInfo()
{
_elements = new Vector(6);
for (int i = 0; i < _elements.capacity(); ++i)
{
_elements.addElement(new String(""));
}
}
public String getElement(int id)
{
return (String) _elements.elementAt(id);
}
public void setElement(int id, String value)
{
_elements.setElementAt(value, id);
}
}
//details for show method
public void show()
{
Dialog.alert("Name is "+getFirstName+" "+getLastName+"\nGender is "+getGender+"\nE-mail: "+getEmail+"\nStatus is "+getStatus);
}
public void list()
{
Dialog.alert("haha");
}
//creating save method
//overriding onClose method
public boolean onClose()
{
System.exit(0);
return true;
}
class ListScreen extends MainScreen
{
String getUserFirstName;
String getUserLastName;
String getUserEmail;
String getUserGender;
String getUserStatus;
String getUserCompany;
String[] setData ;
String getData = new String();
String collectData = "";
ObjectListField fldList;
int counter = 0;
private ButtonField btnBack;
public ListScreen()
{
setTitle(new LabelField("Showing Data",LabelField.NON_FOCUSABLE));
//getData = myList();
//Dialog.alert(getData);
// setData = split(getData,"$");
// for(int i = 0;i<setData.length;i++)
// {
// add(new RichTextField(setData[i]+"#####"));
// }
showList();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK|ButtonField.FIELD_HCENTER);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field,int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void showList()
{
HorizontalFieldManager hfManager = new HorizontalFieldManager(HorizontalFieldManager.HORIZONTAL_SCROLLBAR|HorizontalFieldManager.HORIZONTAL_SCROLL);
//SeparatorField spManager = new SeparatorField();
LabelField lblcheck = new LabelField("check",LabelField.NON_FOCUSABLE);
getData = myList();
setData = split(getData,"$");
fldList = new ObjectListField(ObjectListField.MULTI_SELECT);
fldList.set(setData);
//fldList.setEmptyString("heloo", 12);
//hfManager.add(lblcheck);
hfManager.add(fldList);
//hfManager.add(spManager);
add(hfManager);
addMenuItem(new MenuItem("Select", 100, 1) {
public void run() {
int selectedIndex = fldList.getSelectedIndex();
String item = (String)fldList.get(fldList, selectedIndex);
pushScreen(new ShowDataScreen(item));
}
});
}
public String[] split(String inString, String delimeter) {
String[] retAr;
try {
Vector vec = new Vector();
int indexA = 0;
int indexB = inString.indexOf(delimeter);
while (indexB != -1) {
vec.addElement(new String(inString.substring(indexA, indexB)));
indexA = indexB + delimeter.length();
indexB = inString.indexOf(delimeter, indexA);
}
vec.addElement(new String(inString.substring(indexA, inString
.length())));
retAr = new String[vec.size()];
for (int i = 0; i < vec.size(); i++) {
retAr[i] = vec.elementAt(i).toString();
}
} catch (Exception e) {
String[] ar = { e.toString() };
return ar;
}
return retAr;
}//end of Split Method
public String myList()
{
_data = (Vector) store.getContents();
try
{
for (int i = _data.size()-1; i >-1; i--,counter++)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
//StoreInfo info = (StoreInfo)_data.lastElement();
getUserFirstName = (info.getElement(StoreInfo.NAME));
getUserLastName = (info.getElement(StoreInfo.LastNAME));
//getUserEmail = (info.getElement(StoreInfo.EMail));
//getUserGender = (info.getElement(StoreInfo.GenDer));
//getUserStatus = (info.getElement(StoreInfo.setStatus));
getUserCompany = (info.getElement(StoreInfo.setCompany));
collectData = collectData + getUserFirstName+" "+getUserLastName+" "+getUserCompany+ "$";
}
}
}
catch(Exception e){}
return collectData;
}//end of myList method
public boolean onClose()
{
System.exit(0);
return true;
}
}//end of class ListScreen
class ShowDataScreen extends MainScreen
{
String getFirstName;
String getLastName;
String getCompany;
String getEmail;
String getGender;
String getStatus;
String[] getData;
public ShowDataScreen(String data)
{
getData = split(data," ");
getFirstName = getData[0];
getLastName = getData[1];
getCompany = getData[2];
_data = (Vector) store.getContents();
try
{
for (int i = _data.size()-1; i >-1; i--)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
if (!_data.isEmpty())
{
if((getFirstName.equalsIgnoreCase(info.getElement(StoreInfo.NAME))) && (getLastName.equalsIgnoreCase(info.getElement(StoreInfo.LastNAME))) && (getCompany.equalsIgnoreCase(info.getElement(StoreInfo.setCompany))))
{
getEmail = info.getElement(StoreInfo.EMail);
getGender = info.getElement(StoreInfo.GenDer);
getStatus = info.getElement(StoreInfo.setStatus);
HorizontalFieldManager hfManager = new HorizontalFieldManager(HorizontalFieldManager.NON_FOCUSABLE);
AutoTextEditField name = new AutoTextEditField("Name: ",getFirstName+" "+getLastName);
AutoTextEditField email = new AutoTextEditField("Email: ",getEmail);
AutoTextEditField company = new AutoTextEditField("Company: ",getCompany);
AutoTextEditField Gender = new AutoTextEditField("Gender: ",getGender);
AutoTextEditField status = new AutoTextEditField("Status: ",getStatus);
add(name);
add(email);
add(company);
add(Gender);
add(status);
}
}
}//end of for loop
}//end of try
catch(Exception e){}
//Dialog.alert("fname is "+getFirstName+"\nlastname = "+getLastName+" company is "+getCompany);
}
public String[] split(String inString, String delimeter) {
String[] retAr;
try {
Vector vec = new Vector();
int indexA = 0;
int indexB = inString.indexOf(delimeter);
while (indexB != -1) {
vec.addElement(new String(inString.substring(indexA, indexB)));
indexA = indexB + delimeter.length();
indexB = inString.indexOf(delimeter, indexA);
}
vec.addElement(new String(inString.substring(indexA, inString
.length())));
retAr = new String[vec.size()];
for (int i = 0; i < vec.size(); i++) {
retAr[i] = vec.elementAt(i).toString();
}
} catch (Exception e) {
String[] ar = { e.toString() };
return ar;
}
return retAr;
}//end of Split Method
}
class SearchScreen extends MainScreen
{
private ButtonField btnFirstName;
private ButtonField btnLastName;
private ButtonField btnSearch;
private ButtonField btnEmail;
private SeparatorField sp;
String userName;
HorizontalFieldManager hr = new HorizontalFieldManager();
public AutoTextEditField searchField;
public SearchScreen()
{
sp = new SeparatorField();
setTitle(new LabelField("your Search Options"));
add(new RichTextField("Search by : "));
btnFirstName = new ButtonField("First Name",ButtonField.CONSUME_CLICK);
hr.add(btnFirstName);
btnFirstName.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//HorizontalFieldManager hrs = new HorizontalFieldManager();
searchField = new AutoTextEditField("First Name: ","ali");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new FirstnameScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
//hrs.add(sp);
}
});
btnLastName = new ButtonField("Last Name",ButtonField.CONSUME_CLICK);
hr.add(btnLastName);
btnLastName.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int Context)
{
searchField = new AutoTextEditField("Last Name: ","");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new LastnameScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
}
});
btnEmail = new ButtonField("Email",ButtonField.CONSUME_CLICK);
hr.add(btnEmail);
btnEmail.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int Context)
{
searchField = new AutoTextEditField("Email: ","");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new EmailScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
}
});
add(hr);
}
void myShow()
{
Dialog.alert(searchField.getText());
}
}
class FirstnameScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public FirstnameScreen(String name)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+name));
userName = name;
searchFirstName();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void searchFirstName()
{
ButtonField btnDelete;
if (null != mGrid && null != mGrid.getManager())
mGrid.getManager().delete(mGrid);
int colWidth = net.rim.device.api.system.Display.getWidth() / 4;
mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField("Name"));
mGrid.add(new LabelField("E-Mail"));
mGrid.add(new LabelField("Gender"));
mGrid.add(new LabelField("Active"));
//mGrid.add(new ButtonField("Delete"));
//SeparatorField sps = new SeparatorField();
//mGrid.add(sps);
add(mGrid);
_data = (Vector) store.getContents();
try {
for (int i = _data.size() - 1; i > -1; i--) {
StoreInfo info = (StoreInfo) _data.elementAt(i);
// checking for empty object
if (!_data.isEmpty()) {
firstUserName = (info.getElement(StoreInfo.NAME));
if(firstUserName.equalsIgnoreCase(userName))
{
// if not empty
// create a new object of Store Info class
// stored information retrieved in strings
lastUserName = (info.getElement(StoreInfo.LastNAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
final int sn = i;
// calling the listAll method
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField(firstUserName + " "
+ lastUserName));
mGrid.add(new LabelField(userEmail));
mGrid.add(new LabelField(userGender));
mGrid.add(new LabelField(userStatus));
btnDelete = new ButtonField("Delete",ButtonField.CONSUME_CLICK);
btnDelete.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
_data.removeElementAt(sn);
}
});
add(btnDelete);
// SeparatorField sps1 = new SeparatorField();
//mGrid.add(sps1);
}
}
}
} catch (Exception e) {
}
}
}
class LastnameScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public LastnameScreen(String name)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+name));
userName = name;
searchLastName();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void searchLastName()
{
ButtonField btnDelete;
if (null != mGrid && null != mGrid.getManager())
mGrid.getManager().delete(mGrid);
int colWidth = net.rim.device.api.system.Display.getWidth() / 4;
mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField("Name"));
mGrid.add(new LabelField("E-Mail"));
mGrid.add(new LabelField("Gender"));
mGrid.add(new LabelField("Active"));
//mGrid.add(new ButtonField("Delete"));
//SeparatorField sps = new SeparatorField();
//mGrid.add(sps);
add(mGrid);
_data = (Vector) store.getContents();
try {
for (int i = _data.size() - 1; i > -1; i--) {
StoreInfo info = (StoreInfo) _data.elementAt(i);
// checking for empty object
if (!_data.isEmpty()) {
lastUserName = (info.getElement(StoreInfo.LastNAME));
if(lastUserName.equalsIgnoreCase(userName))
{
// if not empty
// create a new object of Store Info class
// stored information retrieved in strings
firstUserName = (info.getElement(StoreInfo.NAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
final int sn = i;
// calling the listAll method
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField(firstUserName + " "
+ lastUserName));
mGrid.add(new LabelField(userEmail));
mGrid.add(new LabelField(userGender));
mGrid.add(new LabelField(userStatus));
btnDelete = new ButtonField("Delete",ButtonField.CONSUME_CLICK);
btnDelete.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
_data.removeElementAt(sn);
}
});
add(btnDelete);
// SeparatorField sps1 = new SeparatorField();
//mGrid.add(sps1);
}
}
}
} catch (Exception e) {
}
}
}
class EmailScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public EmailScreen(String mail)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+mail));
userName = mail;
searchEmail();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBa
What are the benefits of integrating with the built-in alarm application? Would it be better for your application to place an event in the device's calendar and make the event show a reminder?
If you have to have a more prominent alarm, why not do it yourself? An alarm is an action the phone does (either make a sound and/or vibrate) that shows on the screen why it is taking that action and the action stops when someone responds to it.
Can you just make an app that starts in the background, checks the day, and makes a sound/vibrates on that day?
The default Alarm app on my phone only supports one time to ring. If I set it to wake me up at 4 a.m., but your app reschedules the alarm on my phone for 8 a.m., you would instantly lose a customer (after I wake up 4 hours too late).