Second Datebtn.setText() inside switch case does not settext the selected date value & Datebtn text continues to show only the current date - settext

I have tried this button.set() in multiple ways by doing this inside dateonset () method and I get a null pointer exception there though the editText4 contains the valid text to set the button. I tried the route of Shared preferences as I suspected the edittext4 is empty. Finally I tried this method to initialize the Datebtn inside the Onclick method from view. Here I don't get a null pointer exception but Datebtn.setText() inside switch case does not settext the selected date value & Datebtn text continues to show only the current date that was set in the onCreateView () method. I think I am missing something trivial.
public class AFragment extends Fragment implements OnClickListener {
private DataManipulator dh;
public Button Datebtn;
private Calendar mCalen;
private int day;
private int month;
private int year;
public String myEditText4;
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
View view = inflater.inflate( R.layout.afragment, container, false );
Button b1 = (Button)view.findViewById( R.id.Button01 );
b1.setOnClickListener( this );
Button Datebtn = (Button)view.findViewById( R.id.datepickerbutton );
mCalen = Calendar.getInstance();
day = mCalen.get( Calendar.DAY_OF_MONTH );
month = mCalen.get( Calendar.MONTH );
year = mCalen.get( Calendar.YEAR );
Datebtn.setText( day + " / " + (month + 1) + " / " + year );
myEditText4 = (String)Datebtn.getText();
Datebtn.setOnClickListener( this );
return view;
}
#SuppressLint( "CutPasteId" )
#Override
public void onClick( View view ) {
Context context = view.getContext();
Button Datebtn = (Button)view.findViewById( R.id.datepickerbutton );
switch( view.getId() ) {
case (R.id.datepickerbutton):
DatePickerFragment newDateFragment = new DatePickerFragment();
newDateFragment.setStyle( 1, 1 );
newDateFragment.show( getFragmentManager(), "DatePicker" );
Datebtn.setText( myEditText4 );
break;
case (R.id.Button01):
View editText1 = (EditText)getView().findViewById( R.id.ppl );
View editText2 = (EditText)getView().findViewById( R.id.litres );
View editText3 = (EditText)getView().findViewById( R.id.odo );
String myEditText1 = ((TextView)editText1).getText().toString();
String myEditText2 = ((TextView)editText2).getText().toString();
String myEditText3 = ((TextView)editText3).getText().toString();
dh = new DataManipulator( context );
if( myEditText1 != "" & myEditText2 != "" & myEditText3 != "" & myEditText4 != "" ) {
dh.insert( myEditText1, myEditText2, myEditText3, myEditText4 );
Toast.makeText( context.getApplicationContext(), "Submit Successful!!!", Toast.LENGTH_LONG ).show();
EditText text1 = (EditText)getView().findViewById( R.id.ppl );
text1.setText( "" );
EditText text2 = (EditText)getView().findViewById( R.id.litres );
text2.setText( "" );
EditText text3 = (EditText)getView().findViewById( R.id.odo );
text3.setText( "" );
} else {
Toast.makeText( context.getApplicationContext(), "Values can not be empty!!!", Toast.LENGTH_LONG ).show();
}
break;
}
}
#SuppressLint( "ValidFragment" )
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog( Bundle savedInstanceState ) {
final Calendar c = Calendar.getInstance();
int year = c.get( Calendar.YEAR );
int month = c.get( Calendar.MONTH );
int day = c.get( Calendar.DAY_OF_MONTH );
return new DatePickerDialog( getActivity(), this, year, month, day );
}
public void onDateSet( DatePicker view, int selectedYear, int selectedMonth, int selectedDay ) {
int year = selectedYear;
int month = selectedMonth;
int day = selectedDay;
myEditText4 = (day + " / " + (month + 1) + " / " + year);
return;
}
}
}

After debugging the state of all variables, I was able to figure out the issue. Here is the solution
1) When I did Datebtn inside the onDateSet method, I was actually trying to get the Datebtn object from the Datepicker view. The Datebtn is not in this fragment and hence it gives null pointer exception
2) I then attempted to get the parent fragment from inside the onDateSet using fragment manager object and findFragmentByTag("AFragment"). This is also returned a null pointer because "AFragment" tag is not defined for the AFragment layout xml or AFragment class
3) Then I tried to get a valid AFragment object from fragment manager object using findFragmentByID (R.id.fragment_container). At this step, I got a valid AFragment object handle in DatePickerFragment class. I was then able to do setText on the Datebtn in AFragment class from DatePickerFragment class
Here is how the working code for DatePickerFragment's onDateSet looks
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
int year = selectedYear;
int month = selectedMonth;
int day = selectedDay;
myEditText4 = (day + " / " + (month + 1) + " / " + year);
FragmentManager fm = this.getFragmentManager();
Fragment parFragment = fm.findFragmentById(R.id.fragment_container);
Button dbtn = (Button) parFragment.getView().findViewById(R.id.datepickerbutton);
dbtn.setText(myEditText4);
return;
}

Related

Emoticons MVC 5

While making my project I stuck on a problem.
I have the following thing:
This is in my PostComment action
comment = Emoticon.Format(comment);
Emoticon is public class.
The Format action return the following:
public static string Format(string input)
{
if (input == null || input.Length == 0)
{
return input;
}
else
{
string result = input;
Emoticon[] all = All;
foreach (Emoticon emoticon in all)
{
string a;
string a_;
int border;
// Decide whether a link is required.
if (emoticon.Url != null && emoticon.Url.Length > 0)
{
a = string.Format("<a href=\"{0}\">", emoticon.Url);
a_ = "</a>";
border = 1;
}
else
{
a = "";
a_ = "";
border = 0;
}
// Replace this emoticon.
string replacement =
string.Format(
"{0}<img src=\"{1}\" alt=\"{2}\" align=\"AbsMiddle\" border=\"{3}\" />{4}",
a,
emoticon.VirtualPath,
HttpUtility.HtmlEncode(emoticon.Title),
border,
a_);
result = result.Replace(emoticon.Shortcut, replacement);
}
return result;
}
}
And from PostComment action I go to view and print the comment:
<div class="panel-body">#comment.Content</div>
But my problem is in string.Format(
"{0}<img src=\"{1}\" alt=\"{2}\" align=\"AbsMiddle\" border=\"{3}\" />{4}", because it returns string and in the view it is a string but my purpose is to be a picture. #comment.Comment is also string.

How to open new class file on click of treeview parent and child item in blackberry?

public class Expandablelistview extends MainScreen {
public Expandablelistview() {
// A separator field between each type of control\
// setTitle("Tree Field Demo");
String parentfield1 = new String("Demo1");
String parentfield2 = new String("Demo2");
String childfield1 = new String("Demo3");
String childfield2 = new String("Demo4");
String parentfield3 = new String("Demo5");
String parentfield4 = new String("Demo6");
String childfield3 = new String("Demo7");
String childfield4 = new String("Demo8");
String childfield5 = new String("Demo9");
String childfield6 = new String("Demo10");
String parentfield5 = new String("Demo11");
String childfield7 = new String("Demo12");
String childfield8 = new String("Demo13");
TreeCallback myCallback = new TreeCallback();
final TreeField myTree = new TreeField(myCallback, Field.FOCUSABLE);
myTree.setDefaultExpanded(false);
int node12 = myTree.addChildNode(0, parentfield5);
int node13 = myTree.addChildNode(node12, childfield7);
int node14 = myTree.addChildNode(node12, childfield8);
// int node7 = myTree.addChildNode(0, parentfield5);
int node6 = myTree.addChildNode(0, parentfield4);
int node11 = myTree.addChildNode(node6, childfield6);
int node10 = myTree.addChildNode(node6, childfield5);
int node8 = myTree.addChildNode(node6, childfield3);
int node9 = myTree.addChildNode(node6, childfield4);
int node5 = myTree.addChildNode(0, parentfield3);
int node2 = myTree.addChildNode(0, parentfield2);
int node3 = myTree.addChildNode(node2, childfield1);
int node4 = myTree.addChildNode(node2, childfield2);
int node1 = myTree.addChildNode(0, parentfield1);
add(myTree);
// myTree.setChangeListener(new myTreeChangeListener());
// HERE I TRIED FOR ITEM CLICK
FieldChangeListener fdbtncalculate = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
int a = myTree.getNodeCount();
System.out.print("mytree" + a);
if (a == 0) {
Dialog.alert("data");
} else if (a == 1) {
Dialog.alert("data");
}
}
};
myTree.setChangeListener(fdbtncalculate);
}
private class TreeCallback implements TreeFieldCallback {
public void drawTreeItem(TreeField _tree, Graphics g, int node, int y,
int width, int indent) {
String text = (String) _tree.getCookie(node);
g.drawText(text, indent, y);
}
}
}
i want to know what i am doing wrong? i want to open my class file on click of parent and child item of treeview for that i used field listener
Instead of using a FieldChangeListener, try this code, which overrides navigationClick():
TreeCallback myCallback = new TreeCallback();
TreeField myTree = new TreeField(myCallback, Field.FOCUSABLE) {
protected boolean navigationClick(int status, int time) {
// We'll only override unvarnished navigation click behavior
if ((status & KeypadListener.STATUS_ALT) == 0 &&
(status & KeypadListener.STATUS_SHIFT) == 0)
{
final int node = getCurrentNode();
if (getFirstChild(node) == -1) {
// Click is on a leaf node.
Dialog.alert("clicked leaf node " + getCookie(node));
return true;
} else {
// Node is a parent node
setExpanded(node, !getExpanded(node));
Dialog.alert("clicked parent node " + getCookie(node));
return true;
}
}
return super.navigationClick(status, time);
}
};
I'm not sure what you mean by "open new class file", but whatever you want to do after the user clicks a part of the tree, you would do it where I have the Dialog.alert() code above.

how can i remove a field from the manager in blackberry

first , please try to understand my problem because i know their are too many questions related to this , but in my case no-one is working
why i dont know , please see my code .
this is working
public final class MyScreen extends MainScreen implements FieldChangeListener
{
private combine enter_in;
private manager_s ms , ms_1 ;
private Bitmap img;
LabelField lb_1 , lb_2 , lb_3 ;
public MyScreen()
{
setTitle("MyTitle");
img = Bitmap.getBitmapResource("icon.png");
//Bitmap img_1 = Bitmap.getBitmapResource("icon.png");
enter_in = new combine ( Field.FOCUSABLE , img );
enter_in.setChangeListener(this);
ms = new manager_s( 0 , 4 );
ms.add(enter_in);
lb_1 = new LabelField("Menu") ;
lb_2 = new LabelField("Favorites") ;
lb_3 = new LabelField("Reserved") ;
ms.add(lb_1);
ms.add(lb_2);
ms.add(lb_3);
add(ms);
}
}
but when i am implementing FieldChangedListener , at that time ms.delete(lb_1) is not working but delete(ms) is working , please help solve this problem
public void fieldChanged(Field field, int context)
{
if ( field == enter_in )
{
ms.delete(lb_1);
}
}
so , i am asking that is , there any reason for ms.delete(lb_1) not working under MyScreen class .
see this is my manager_class which i am using as , Manager ( custom_manager ) and this manager is extended by my class , for adding the fields inside the screen
public class manager_s extends Manager
{
int col ;
int w_1 = 20 ;
protected manager_s(long style , int col )
{
super(style);
this.col = col ;
}
protected void sublayout(int width, int height)
{
for ( int i = 0 ; i < col ; i ++ )
{
Field field = getField (i);
layoutChild( field , 130 , 100 );
}
for ( int i = 0 ; i < col ; i ++ )
{
Field field = getField (i);
setPositionChild ( field , w_1 , 20 );
w_1 = w_1 + 135 ;
setExtent ( width , 200 );
}
}
}
and the error is INDEX_OUT_OF_BOUND_EXCEPTION , thats my question that , because every one on internet ( as a resource ) is saying that remove the field , but i my case nothing is working .
try this -
setTitle("MyTitle");
final ButtonField enter_in=new ButtonField("enter_in");
add(enter_in);
lb_1 = new LabelField("Menu") ;
lb_2 = new LabelField("Favorites") ;
lb_3 = new LabelField("Reserved") ;
final HorizontalFieldManager ms=new HorizontalFieldManager();
ms.add(lb_1);
lb_1.setMargin(0,50,0,0);//Here you can set the spacing between the Fields.
ms.add(lb_2);
lb_2.setMargin(0,50,0,0);//Here you can set the spacing between the Fields.
ms.add(lb_3);
add(ms);
FieldChangeListener listener=new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if(field==enter_in){
ms.delete(lb_1);
ms.invalidate();
}
}
};
enter_in.setChangeListener(listener);
In place of my ButtonField , you can use your combine.

myReverseGeocode is not starting.

In below code when i call myReverseGeocode address = new myReverseGeocode(latitude, longitude); , gpsData.append(address.temp); always show "null"
public HelloBlackBerryScreen() {
super( MainScreen.VERTICAL_SCROLL | MainScreen.VERTICAL_SCROLLBAR );
setTitle( "Get Address" );
ButtonField buttonField_1 = new ButtonField( "Get GPS", ButtonField.CONSUME_CLICK | ButtonField.FIELD_RIGHT );
add( buttonField_1 );
buttonField_1.setChangeListener( new FieldChangeListener() {
public void fieldChanged( Field arg0, int arg1 ) {
Criteria c = new Criteria();
try {
LocationProvider lp = LocationProvider.getInstance(c);
if( lp!=null )
{
lp.setLocationListener(new LocationListenerImpl(), 3, 1, 1);
myReverseGeocode address = new myReverseGeocode(latitude, longitude);
gpsData.append(address.temp);
myloc = gpsData.toString();
}
} catch (LocationException le) {
;
}
myReverseGeocode.java
package mypackage;
import javax.microedition.location.AddressInfo;
import javax.microedition.location.Landmark;
import net.rim.device.api.lbs.Locator;
import net.rim.device.api.lbs.LocatorException;
public class myReverseGeocode {
private Thread reverseGeocode;
public AddressInfo addrInfo = null;
String temp;
public myReverseGeocode(final double lt, final double ln)
{
Runnable thread = new Runnable()
{
public void run()
{
int latitude = (int)(lt * 100000);
int longitude = (int)(ln * 100000);
try
{
Landmark[] results = Locator.reverseGeocode(latitude, longitude, Locator.ADDRESS );
if ( results != null && results.length > 0 )
temp = "inside if";
else
temp = "in else";
}
catch ( LocatorException lex )
{
}
}
};
reverseGeocode = new Thread(thread);
reverseGeocode.setPriority(Thread.MIN_PRIORITY);
reverseGeocode.start();
}
}
You always get temp as null because you ask for it almost immediatelly after the Thread (that is started in constructor of the myReverseGeocode) has been started. You need to redesign your myReverseGeocode to udate the UI of the screen after an actual temp value is got.

2nd Line is not getting displayed in the ListField (text wrapping is not happening) ... please advice

Here is the sample code:
class MailBoxSampleListField extends MainScreen implements FolderListener, StoreListener {
private static final int COLUMN_WIDTH_STATUS = 10;
private static final int COLUMN_WIDTH_DATE = 150;
private static final int COLUMN_WIDTH_NAME = 150;
public ListField myList;
private ListCallback myCallback;
public Vector sampleList = new Vector();
public Vector sampleVector;
private class ListCallback implements ListFieldCallback {
public Vector myVector = new Vector();
public Bitmap LIST_IMAGE = Bitmap.getBitmapResource("New.PNG");
public void drawListRow (ListField list, Graphics g, int index, int y,int w) {
displayList(g,0,y,w,(( Message )myVector.elementAt( index )), LIST_IMAGE); // for drawing the list row
for( int ii = 0; ii < sampleVector.size(); ii++) {
String text = ( String )sampleVector.elementAt(ii);
int liney = y + ( ii * list.getFont().getHeight() );
g.drawText( text, LIST_IMAGE.getWidth() + 5, liney, Graphics.ELLIPSIS, w );
}
}
public Object get( ListField list, int index ) {
return myVector.elementAt(index);
}
public int indexOfList( ListField list,String p, int s ) {
return myVector.indexOf(p,s);
}
public int getPreferredWidth ( ListField list ) {
return Graphics.getScreenWidth();
}
public void insert(Message _message, int index) {
myVector.addElement(_message);
}
public void erase () {
myVector.removeAllElements();
}
}
MailBoxSampleListField() {
ListCallback myCallback = new ListCallback();
try {
Store store = null;
store = Session.getDefaultInstance().getStore();
store.addStoreListener( this );
// retrieve Folder object fow which we want to receive message notification
try {
Folder[] folders = store.list();
Folder[] f1 = store.findFolder( "inbox" );
Folder vinbox = f1[0];
for (int i =0; i < f1.length; i++) {
f1[i].addFolderListener( this );
}
Message[] vmessages = vinbox.getMessages();
for ( int j = 0; j < vmessages.length; ++j ) {
if(vmessages[j] != null){
sampleList.addElement( vmessages[j] );
}
}
myList = new ListField(); // initialize the ListField
for ( int k = 0; k < sampleList.size(); k++ ) {
myList.insert(k);
myCallback.insert(vmessages[k], k);
}
myList.setCallback( myCallback );
add( myList );
}
catch( Exception e ){
}
}
catch ( Exception se ) {
}
}
public void displayList( Graphics g, int x, int y, int width, Message _message, Bitmap LIST_IMAGE ) {
g.drawBitmap(0, y, LIST_IMAGE.getWidth(), LIST_IMAGE.getHeight(), LIST_IMAGE, 0, 0);
sampleVector = new Vector();
Date d = _message.getReceivedDate();
Calendar c = Calendar.getInstance();
c.setTime(d);
StringBuffer sb = new StringBuffer();
sb.append( c.get( Calendar.MONTH ) );
sb.append('-');
int digit = c.get( Calendar.DAY_OF_MONTH );
if ( digit < 10 ) sb.append(0);
sb.append( digit );
sb.append(' ');
sb.append( c.get( Calendar.HOUR_OF_DAY ) );
sb.append(':');
digit = c.get( Calendar.MINUTE );
if ( digit < 10 ) sb.append( 0 );
sb.append( digit );
sb.append( ' ');
x += LIST_IMAGE.getWidth()+5;
x += COLUMN_WIDTH_DATE;
try {
String name = "<noname>";
if ( _message.isInbound() ) {
Address a = _message.getFrom();
if ( a != null )
{
name = a.getName();
if ( name == null || name.length() == 0 ) name = a.getAddr();
}
}
else
{
//get the first Recipient address
Address[] set = _message.getRecipients(Message.RecipientType.TO);
if ( set != null && set.length > 0 )
{
name = set[0].getName();
if ( name == null || name.length() == 0 ) name = set[0].getAddr();
}
}
sampleVector.addElement(name +" " + sb.toString());
} catch (MessagingException e) {
System.err.println(e);
}
x += COLUMN_WIDTH_NAME;
int remainingColumnWidth = Graphics.getScreenWidth() - x;
//get the subject, or if that doesn't exist, the first line of the body
String textToDisplay = _message.getSubject();
if ( null == textToDisplay) //no subject! get the first line of the body if present
{
Object o = _message.getContent();
if ( o instanceof String )
{
textToDisplay = (String)o;
}
else if ( o instanceof Multipart )
{
Multipart mp = (Multipart)o;
int count = mp.getCount();
for (int i = 0; i < count; ++i)
{
BodyPart p = mp.getBodyPart(i);
if ( p instanceof TextBodyPart )
{
textToDisplay = (String)p.getContent();
}
}
}
}
sampleVector.addElement(textToDisplay);
} public void messagesAdded(FolderEvent e) {} public void messagesRemoved(FolderEvent e) { } public void batchOperation( StoreEvent se) { }
}
I'm not sure what you mean, could you please post a screenshot so that we can see the problem?
I'll try to help out the best I can. In my limited experience, I have noticed that in a listfield, if you have not set the row height (with setRowHeight()) to a big enough height, graphics (including text) that overflow over the size of the row will not be displayed. Have you tried setting the row height to 2 * list.getFont().getHeight() or more?
If not all rows are displayed, then I think you've missed to call myList.setSize(myVector.size());
I'm not sure what you mean by "wrapping not happening"...
The drawListRow() will be called repeatedly (for the amount of times set by the setSize() that I've suggested above).
In your current code you iterate through the whole myVector on each drawListRow() call - this is wrong.
You must use the value y which is declare in drawListRow (ListField list, Graphics g, int index, int y,int w)
like
g.drawText( text, LIST_IMAGE.getWidth() + 5, y+liney, Graphics.ELLIPSIS, w )
I am facing this issue for long time finally i got the solution.
As Alex say, you need to implement your own wrapper class, something that looks like:
TextWrapper theWrapper = new TextWrapper();
String[] wrappedText = theWrapper.textWrap(longText, wrappingWidth , 2);
//
// now draw text line by line
//
g.drawText(wrappedText[0], x, y, DrawStyle.LEFT, width);
if (wrappedText.length > 1) {
g.drawText(wrappedText[1], x, y + textFont.getHeight(), DrawStyle.LEFT | DrawStyle.ELLIPSIS, width);
}
where
public class TextWrapper {
... // put here methods used by textWrap method
//
// textWrap splits input String in lines having width as maxWidth
//
public String[] textWrap(String s, int maxWidth, int maxLines)
{
String[] result;
... // do here the wrap job on input string s
return result;
}
}

Resources