Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Highlighted
Contributor
Posts: 42
Registered: ‎10-23-2011
My Device: curve 8520
My Carrier: george najem

ActiveTextField Submit to search field -BIG JOB

Hello , I have this blackberry app im making.. I am a new to blackberry and verry stuck. If you could please help me I'd really appriciate it.

 

This is what my app does. If you dont get it at 1st. u are welcome to run it on Eclipse to see what i mean:

1) you click a button it opens a camera and It scans a barcode > 


2) after that camera closes and on a second screen it tells the users what the embedded data was in a new screen, by a string of text


3) the string of text becomes hyperlinked (Activetextfield) so when u click on it it takes you to BLANK screen where that string appears again.

 

My problem is that i want the string of text that is clicked  to appear in a search field in another class i made.

 

The followingwing file is step 1 and 2

package com.george.scanner;

import java.util.*;
import net.rim.device.api.amms.control.camera.*;
import net.rim.device.api.barcodelib.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import com.google.zxing.*;


public final class BlackBerryScan extends UiApplication
{    //as always the Entry point for the application(static void main)
     
    public static void main(String[] args)
    {
        new BlackBerryScan().enterEventDispatcher();
    }

     //Creates a new blackberryscan object
    public BlackBerryScan()
    {
        pushScreen(new ScanScreen());
    }
}
 //A UI screen to display the camera display and buttons

final class ScanScreen extends MainScreen
{
    private ImageScanner thescanner;
    private MainScreen viewfindScreen;
    private ButtonField theQRButton;
    private ButtonField theUPCButton;
    private ButtonField thedataMatrixButton;
    private ButtonField the128Button;

    
      //The following wii creates a new ScanScreen object
    public ScanScreen()
    {
        // Set the title of the screen
        setTitle("George's BarCode Scanner");
        buildUi();
    }

     // the Builds the user interface. Adds buttons and registers MyFieldListeners for each.
     
    private void buildUi()
    {

        theQRButton = new MyButtonField("Please Scan a QR code", ButtonField.CONSUME_CLICK | Field.FIELD_HCENTER);
        theQRButton.setChangeListener(new MyFieldListener());

        thedataMatrixButton = new MyButtonField("Please Scan DataMatrix Code", ButtonField.CONSUME_CLICK 
                        | Field.FIELD_HCENTER);
        thedataMatrixButton.setChangeListener(new MyFieldListener());

        theUPCButton = new MyButtonField("Please Scan a UPC Button", ButtonField.CONSUME_CLICK | Field.FIELD_HCENTER);
        theUPCButton.setChangeListener(new MyFieldListener());

        the128Button = new MyButtonField("Please Scan a 128 Code", ButtonField.CONSUME_CLICK 
                        | Field.FIELD_HCENTER );
        the128Button.setChangeListener(new MyFieldListener());

        add(theQRButton);
        add(thedataMatrixButton);
        add(theUPCButton);
        add(the128Button);
    }

    
    //Allows for larger than normal ButtonFields
    
    private class MyButtonField extends ButtonField
    {
        public MyButtonField(String label, long style)
        {
            super(label, style);
        }


        
        //Note 2 SELF : not sure as of now but i think the below retreives the buttons perferred width (60% of Display.getWidth())
         //and returns The preferred width of the button
        
        public int getPreferredWidth()
        {
            return (int) (Display.getWidth() * 0.60);
        }
    }


    
     //Displays the decoded barcode text and the type of barcode that was just
    // scanned.
     
     //displays the results from scanning a barcode
     
    public void inform(Result result)
    {
        // Close the viewfinder first
        UiApplication.getUiApplication().popScreen(viewfindScreen);

        MainScreen resultsScreen = new MainScreen();

       // LabelField text = new LabelField("Barcode Text: " + result.getText());
       //text.setPadding(4, 4, 4, 4);
       
       //This section wont work
        System.out.println(">>>>>>>>Result = "+result);
       ActiveAutoTextEditField activeField = new ActiveAutoTextEditField("enter some food: ", null);
       String strBarCode = result.toString();
       activeField.insert(strBarCode, 0, true, true);
        activeField.setPadding(4, 4, 4, 4);
         //activeField.setFocus(); 
        
        

        EditField type = new EditField("Barcode Type: " + result.getBarcodeFormat().toString(), null);
        type.setPadding(4, 4, 4, 4);

        TransitionContext context = new TransitionContext(TransitionContext.TRANSITION_SLIDE);
        context.setIntAttribute(TransitionContext.ATTR_DIRECTION, TransitionContext.KIND_OUT);

        Ui.getUiEngineInstance().setTransition(null, resultsScreen, UiEngineInstance.TRIGGER_PUSH, context);

        resultsScreen.add(activeField);
        resultsScreen.add(type);

        UiApplication.getUiApplication().pushScreen(resultsScreen);
    }


    
     //Initializes the camara to begin scanning the barcode
    //The listner that is gonna be used to tell when the barcode is scanned
    //returns- it returns a initialized Viewfinder screen to be displayed
    private Field initializeCamera(ImageDecoder decoder, ImageDecoderListener listener)
    {
        try
        {
            // Check if the ImageScanner has already been initialized. If it has,
            // make sure to close its player, so that a new one can be created/taken.
            if(thescanner != null)
            {
                thescanner.getPlayer().close();
            }
            
            thescanner = new ImageScanner(decoder, listener);
            thescanner.getVideoControl().setDisplayFullScreen(true);
            thescanner.startScan();
            return thescanner.getViewfinder();
        }
        catch(Exception e)
        {
        }
        return null;
    }


    
    // the following handles field change events
    
    private class MyFieldListener implements FieldChangeListener
    {

        final ImageDecoderListener theimageDecoderListener = new ImageDecoderListener()
        {

            public void imageDecoded(final Object decoded)
            {
                UiApplication.getUiApplication().invokeLater(new Runnable()
                {
                    public void run()
                    {
                        inform((Result)decoded);
                    }
                });
            }
        };

         //Listens for when a button is pressed
    
        public void fieldChanged(Field field, int context)
        {
            Vector formats = new Vector();

            // The following will find out what button was pressed and add its format(s) to the vector
            if (field == theQRButton)
            {
                System.out.println("QR button");
                formats.addElement(BarcodeFormat.QR_CODE);
            }
            else  if (field == thedataMatrixButton)
            {
                formats.addElement(BarcodeFormat.DATAMATRIX);
            }
            else if (field == theUPCButton)
            {
                formats.addElement(BarcodeFormat.UPC_A);
                formats.addElement(BarcodeFormat.UPC_E);
                formats.addElement(BarcodeFormat.EAN_13);
                formats.addElement(BarcodeFormat.EAN_8);
            }
            else if (field == the128Button)
            {
                formats.addElement(BarcodeFormat.CODE_128);
            }

            // Allows for the decoder to look for a specific type of barcode.
            // Can increase the decoders speed or accuracy.      
            Hashtable hints = new Hashtable();
            hints.put(DecodeHintType.POSSIBLE_FORMATS, formats);

            

            // Initialize the camera object and video field 
            Field cameraField = initializeCamera(new BarcodeDecoder(hints), theimageDecoderListener);

            // If the field was constructed successfully, create the UI
            if(cameraField != null)
            {
                viewfindScreen = new MainScreen();
                viewfindScreen.add(cameraField);
                UiApplication.getUiApplication().pushScreen(viewfindScreen);
            }
        }
    }
}

 

The following code is the activetextfield 

package foodtextfield;

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.blackberry.api.stringpattern.*;
import net.rim.blackberry.api.menuitem.*; 
import java.util.*;
import java.io.*;
//import com.rim.george.device.keywords.KeywordsofFoodScreen;
import net.rim.device.api.io.*;



public final class FoodTextField extends UiApplication
{
    private static ApplicationMenuItem[] themenuItem = new ApplicationMenuItem[1];
    private static RichTextField foodtrans; 
   // private KeywordFilterField _keywordFilterField;   
    
    
   
    
    public static void main(String[] args)
    {        
        if(args != null && args.length > 0)
        {
            // When device starts it registers the regular expression in 
            // the PatternRepository.
            if (args[0].equals("autostartup"))
            {
                // Assigns menu items to ApplicationMenuItem array.
                themenuItem[0] = thefoodItem;          
                
              /*  
              * 1)First we create an ApplicationDescriptor referencing this
              * application. 
              * 2)Then it will register a regular expression and associate
              * our ApplicationDescriptor along with  menu item. When aspecified food
              *  is typed in an active text field the matched pattern
              * will be highlighted and the additional menu item will be
              * available. 
              * 3)The menu items will launch an instance of this
              * appplication when invoked.
              */ 
                ApplicationDescriptor appDesc = new ApplicationDescriptor(ApplicationDescriptor.currentApplicationDescriptor(),"Active Text Fields",new String[]{"pattern-recognized"});
                PatternRepository.addPattern(appDesc,"[Egg,Rice,Beef,Milk,Pasta,Cheese,Bread,Butter,Lamb,Bean,Honey,Rocket,Cream,Prawn,Apple,Salmon,Noodle,Chicken]{3,7}",PatternRepository.PATTERN_TYPE_REGULAR_EXPRESSION,themenuItem);           
            }
            
            // This block will execute when  application menu item is invoked.  
            else if(args[0].equals("pattern-recognized"))
            {
                // this kinda throws up a screen displaying food information.  Therefore it passes false into
                // the constructor. 
            	FoodTextField app = new FoodTextField(false);                       
                app.enterEventDispatcher();
            }
        }
        
        // This block will execute if the user starts this application from
        // the desktop.
        else 
        { 
            // application is lauched and passed true to constructor.
        	FoodTextField app = new FoodTextField(true);           
            app.enterEventDispatcher();
        } 
    }    
    
    
   // isFoodApp Flag  is used to indicate whether application was invoked explicitly from the desktop or by invoking a menu item
    
    public FoodTextField(boolean isfoodApp)
    {        
        // Display a MainScreen that simply allows user to type ingredient into an ActiveAutoTextEditField which enforces pattern recognition
        // functionality. 
        if(isfoodApp)
        {
        	ThefirstScreen entertextScreen = new ThefirstScreen();
            pushScreen(entertextScreen);        
        }
        
       // If the user invoked one of the application menu items it should display the following MainScreen providing food information. 
        else
        {
            
            HandlerScreen handlerScreen = new HandlerScreen();
            pushScreen(handlerScreen);
            
            // When this application is launched  it is made visible by bringing it to the foreground. 
            ApplicationManager.getApplicationManager().requestForeground(getProcessId());
        }
    }
    
    // Anonymous inner classes to extend abstract class ApplicationMenuItem.
    
    
    private static ApplicationMenuItem thefoodItem = new ApplicationMenuItem(0x230020) 
    {
       
         //Sets the label and text in the display fields of the handler screen
         
        //  The String representation of the context object is displayed
         	
    	
   
        public Object run(Object context)
        {
        
            foodtrans.setLabel("Hello, You have just scanned: ");
            foodtrans.setText(context.toString());
            
            return null;
        }
        public String toString()
        {
            return "Food Database";   //The menu button title
        }
    };   
    
    
    
     //The screen that is displayed when one of our application menu items is invoked.
    
    private static final class HandlerScreen extends MainScreen 
    {
       
       //below is the Createation of a new HandlerScreen object
       
       public HandlerScreen()
       {           
    	    
           // Set the screen title
          // setTitle("Active Text Fields Handler");
            
           // These are the fields that will display the ton the second screen
           foodtrans = new RichTextField();            
           add(foodtrans);
               
           
           /* This part will not work
           HandlerScreen screen = new HandlerScreen();
           KeywordFilterField _keywordFilterField = null; 
           screen.setTitle(_keywordFilterField.getKeywordField());
           screen.add(_keywordFilterField);
           */
           
       }                    
    }      
}

//BELOW IS GONNA BE THE MAIN SCREEN 
final class ThefirstScreen extends MainScreen 
{    
    ///create a Thefirstscreen object
	ThefirstScreen()
    {        
        // Set the screen title
        setTitle("George's Food Text first Screen");
        
       
                    
        // Add an ActiveAutoTextEditField
        ActiveAutoTextEditField activeField = new ActiveAutoTextEditField("Food Type: ", null);
        add(activeField);
        activeField.setFocus();            
    }
    
    // The following code must be included in every blackberry proj it Prevents the save dialog from being displayed
     
    public boolean onSavePrompt()
    {
        return true;
    }                  
}  

 The following is where the Search field is :

package com.rim.george.device.keywords;

import net.rim.device.api.ui.*;
import net.rim.device.api.io.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.system.*;
import java.util.*;
import java.io.*;


public final class KeywordsofFood extends UiApplication
{
    private KeywordFilterField _keywordFilterField;    
    private thefoodList _thefoodList;
    private Vector _foods; 
    

    //once again the Entry point for the application.
      
    public static void main( String[] args )
    {
        // Create a new instance of the application        
    	KeywordsofFood app = new KeywordsofFood();
        
        // Makes the currently running thread the application's event
        // dispatch thread and begin processing events.
        app.enterEventDispatcher();
    }

    
     //Creates a new keywordsoffood object
     
    public KeywordsofFood()
    {      
        // Populate vector with data from file.
        _foods = getDataFromFile();
        
        if(_foods != null)
        {
            // Create an instance of our SortedReadableList class. 
            _thefoodList = new thefoodList(_foods);        
            
            // Add our list to a KeywordFilterField object.
           _keywordFilterField = new KeywordFilterField();                   
           _keywordFilterField.setSourceList(_thefoodList, _thefoodList);      ////Makes list of results appear
                       
            
            // Create main screen. 
            KeywordsofFoodScreen screen = new KeywordsofFoodScreen(this);
                        
            // We need to explicitly add the search/title field via MainScreen.setTitle().
           screen.setTitle(_keywordFilterField.getKeywordField());     /////////THIS ONE       
        
            
            // Adds a KeywordFilterField to the screen and push the screen onto the stack.
           screen.add(_keywordFilterField);
            pushScreen(screen);
        } 
        else
        {
            UiApplication.getUiApplication().invokeLater(new Runnable()
            {
                public void run()
                {
                    Dialog.alert("Error reading data file.");
                    System.exit(0);
                }
            });
        }       
    }   
    
   
     //allows access 2 the KeywordFilterField object.
     
    KeywordFilterField getKeywordFilterField()
    {
        return _keywordFilterField;
    }   
   
    // Method populates and returns a vector of food objects containing data read from text file.
     
    private Vector getDataFromFile()
    {   
        Vector foods = new Vector();
        
        // Get an input stream from the file.
        InputStream stream = getClass().getResourceAsStream("/Data/recipes.txt");
        
        if(stream != null)
        {                   
            LineReader lineReader = new LineReader(stream);                               
            
             //Each line is parsed to extract data used to construct Food objects.            
            for(;;)
            {
                try
                {
                    String line = new String(lineReader.readLine());
                 
                    // Parse the current line.
                    int comma1 = line.indexOf(',');
                    String food = line.substring(0,comma1);                        
                    int comma2 = line.indexOf(',',comma1+1);
                    String ingredients = line.substring(comma1+1,comma2);                       
                    String instructions = line.substring(comma2+1,line.length());                      
                    
                    // Creates a new object with data from current line.                        
                   foods.addElement(new Food(food,ingredients,instructions));                    
                }
                catch(EOFException eof)
                {
                   
                    break;
                }
                catch(final IOException ioe)
                {
                    UiApplication.getUiApplication().invokeLater(new Runnable()
                    {
                        public void run()
                        {
                            Dialog.alert("LineReader#readLine() threw " + ioe.toString());
                        }                
                    });

                    return null;
                }                
            }                                       
            return foods;           
        }
        else
        {
            System.out.println("Could not find resource");
            return null;                
        }
    } 
       
    
     //Adds a new element and updates the food list. 
     
    void addElementToList(Food food)
    {       
         _thefoodList.addElement(food);
        _keywordFilterField.updateList();       
    }   
    
    
    // Inner Class: A custom keyword input field for the KeywordFilterField.
     
    final static class CustomKeywordField extends BasicEditField
    {   
        // Contructor
        CustomKeywordField()
        {
            // Custom style.
            super(USE_ALL_WIDTH|NON_FOCUSABLE|NO_LEARNING|NO_NEWLINE); 
            
            setLabel("Search: ");
        } 
        
        
    }
}