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
Regular Contributor
Posts: 95
Registered: ‎07-16-2010
My Device: 8520
My Carrier: bsnl

simple json and xml file parsing

///////////////////////////mainsrc.java/////////////////////////////

 

import net.rim.device.api.ui.UiApplication;


public class mainsrc extends UiApplication{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
         new mainsrc().enterEventDispatcher();
    }
    public mainsrc()
    {
        pushScreen(new uiscreen());
    }

}

///////////////////////////////////////uiscreen.java/////////////////////////

 


import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.lcdui.List;

import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.system.ControlledAccessException;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class uiscreen extends MainScreen implements ListFieldCallback
{
    Vector datastore;
    EditField adField,emailField;
    dataintro dnt;
    public static PersistentObject myStore;
    static {
        myStore = PersistentStore.getPersistentObject(0x12237A75);
    }
    public uiscreen()
    {
        setTitle("First Page");
        adField=new EditField("Name: ","");
        emailField=new EditField("email: ","");
        String _xmlFileName = "/bookstore.xml";
        ListField li=new ListField(0)
        {
            protected boolean invokeAction(int action) {
                
                return true;
            }
        };
        li.setRowHeight(30);
        synchronized (myStore) {

            datastore=(Vector) myStore.getContents();
        }




        if(datastore!=null)
        {
            li.setSize(datastore.size());
            for (int i = 0; i < datastore.size(); i++)
            {
                dnt = (dataintro) datastore.elementAt(i);
            }
        }
        else
        {
            li.setEmptyString("threre is no Data", 0);
            
        }
        //li.setSize(3);
        li.setCallback(this);
        try
        {
            InputStream is = getClass().getResourceAsStream( _xmlFileName );
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputStream inputStream = getClass().getResourceAsStream( _xmlFileName );
            Document document = builder.parse( inputStream );
            Document document_1;
            Element rootElement = document.getDocumentElement();
            rootElement.normalize();

            document_1=document;

            NodeList list=document.getElementsByTagName("Book");


            String node=new String();
            String element = new String();
            for (int check=0;check<list.getLength();check++)
            {
                Node value=list.item(check).getChildNodes().item(0);
                node=list.item(check).getNodeName();
                element=value.getNodeValue();


            }
        }
        catch ( Exception e )
        {
            System.out.println( e.toString() );
        }
        ////////////////////////////////////////////json parser example/////////////////////////////////////////////

        try {
            InputStream inStream = this.getClass().getResourceAsStream("/testjson.txt");
            byte bytes[] = IOUtilities.streamToBytes(inStream);
            String filestring = new String(bytes);

            String str1="";

            try {

                JSONArray outerArray = new JSONArray(filestring);
                //      str=str+"[\t\n";
                JSONObject inner;

                for (int i = 0; i < outerArray.length(); i++)
                {       
                    inner = new JSONObject(outerArray.getString(i).toString());

                    str1=(inner.getString("id"));
                    str1=(inner.getString("type"));
                    str1=(inner.getString("name"));
                    str1=(inner.getString("ppu"));

                    JSONObject better;

                    better=new JSONObject(inner.getString("batters"));

                    JSONArray beter = new JSONArray(better.getString("batter"));

                    JSONObject inerbeter;

                    for (int j = 0; j < beter.length(); j++)
                    {       
                        inerbeter = new JSONObject(beter.getString(j).toString());

                        str1=(inerbeter.getString("id"));
                        str1=(inerbeter.getString("type"));

                    }

                    beter = new JSONArray(inner.getString("topping"));

                    for (int j = 0; j < beter.length(); j++)
                    {       
                        inerbeter = new JSONObject(beter.getString(j).toString());

                        str1=(inerbeter.getString("id"));
                        str1=(inerbeter.getString("type"));

                    }
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (IOException e) {
            Status.show("error while file reading");
            e.printStackTrace();
        }

        ButtonField btnOk=new ButtonField("Add",FIELD_HCENTER)
        {
            protected boolean invokeAction(int action) {

                dataintro d=new dataintro();

                d.setName(adField.getText());
                d.setEmail(emailField.getText());
                try {
                    synchronized (myStore) {

                        datastore=new Vector();
                        datastore=(Vector) myStore.getContents();



                        datastore.addElement(d);

                        myStore.setContents(datastore);
                        myStore.commit();


                    }
                } catch (ControlledAccessException e) {
                    Dialog.alert("error  "+e);
                    e.printStackTrace();
                }
                return true;
            }
        };

        add(adField);
        add(emailField);
        add(li);
        add(btnOk);
    }
    public void drawListRow(ListField listField, Graphics graphics,
            int index, int y, int width) {
        dnt = (dataintro) datastore.elementAt(index);
        
        graphics.setColor(Color.BLACK);
        graphics.setFont(Font.getDefault().derive(Font.BOLD,20));
        graphics.drawText(dnt.getName(),10, y+5);
        //graphics.drawText("data"+index,10,y+5);

    }
    public Object get(ListField listField, int index) {
        // TODO Auto-generated method stub
        return null;
    }
    public int getPreferredWidth(ListField listField) {
        // TODO Auto-generated method stub
        return 0;
    }
    public int indexOfList(ListField listField, String prefix, int start) {
        // TODO Auto-generated method stub
        return 0;
    }
}

//////////////////////testjson.txt/////////////////////

 

[{"id": "0001","type": "donut","name": "Cake","ppu": 0.55,"batters":{"batter":[{ "id": "1001", "type": "Regular" },{ "id": "1002", "type": "Chocolate" },{ "id": "1003", "type": "Blueberry" },{ "id": "1004", "type": "Devil's Food" }]},"topping":[{ "id": "5001", "type": "None" },{"id": "5002", "type": "Glazed" },{ "id": "5005", "type": "Sugar" },{ "id": "5007", "type": "Powdered Sugar" },{ "id": "5006", "type": "Chocolate with Sprinkles" },{ "id": "5003", "type": "Chocolate" },{ "id": "5004", "type": "Maple" }]},{"id": "0002","type": "donut","name": "Raised","ppu": 0.55,"batters":{"batter":[{ "id": "1001", "type": "Regular" }]},"topping":[{ "id": "5001", "type": "None" },{ "id": "5002", "type": "Glazed" },{ "id": "5005", "type": "Sugar" },{ "id": "5003", "type": "Chocolate" },{ "id": "5004", "type": "Maple" }]},{"id": "0003","type": "donut","name": "Old Fashioned","ppu": 0.55,"batters":{"batter":[{ "id": "1001", "type": "Regular" },{ "id": "1002", "type": "Chocolate" }]},"topping":[{ "id": "5001", "type": "None" },{ "id": "5002", "type": "Glazed" },{ "id": "5003", "type": "Chocolate" },{ "id": "5004", "type": "Maple" }]}]

 

 

///////////////////////////bookstore.xml///////////////////

 

<BookStore>
  <Book>
    <Title>The Origin of Species</Title>
    <Author>
      <LastName>auther1</LastName>
      <FirstName>auther11</FirstName>
    </Author>
    <ISBN>0785819111</ISBN>
    <Price>111</Price>
  </Book>
 
  <Book>
    <Title>The Origin of Species</Title>
    <Author>
      <LastName>auther2</LastName>
      <FirstName>auther22</FirstName>
    </Author>
    <ISBN>0785819222</ISBN>
    <Price>222</Price>
  </Book>
 
  <Book>
    <Title>Just Java 2</Title>
    <Author>
      <LastName>auther3</LastName>
      <FirstName>auther33</FirstName>
    </Author>
    <ISBN>0131482333</ISBN>
    <NumPages>1152</NumPages>
    <Price>333</Price>
  </Book>
 
  This is some more text.
 
</BookStore>

///////////////////////////////////////////////////////////

Contributor
Posts: 13
Registered: ‎08-23-2011
My Device: Developer
My Carrier: Developer

Re: simple json and xml file parsing

dataintro dnt;

 

I get error in the above line.... plz help me.......

 

Developer
Posts: 17,019
Registered: ‎07-29-2008
My Device: Z10 LE, Z30, Passport
My Carrier: O2 Germany

Re: simple json and xml file parsing

don't use blocking code, like a network connection, xml parsing etc, on the event thread. use a separate thread.
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Contributor
Posts: 13
Registered: ‎08-23-2011
My Device: Developer
My Carrier: Developer

Re: simple json and xml file parsing

Thanx for the reply Simon.I am a new BB developer

The thingh is i just wants to test the JSON parser for my future use.So i try that code snippet.Can u please help me to find the right data type as dataintro type cannot be resovled.Pls 

Thanks in advance

Developer
Posts: 19,636
Registered: ‎07-14-2008
My Device: Not Specified

Re: simple json and xml file parsing

Couple of things

 

Firstly you can't mix up Midlet and BlackBerry UI classes.  So you shouldnot have this import:

 

import javax.microedition.lcdui.List;

as this is importing a Midlet UI class

 

Secondly, if you code this statement:

 

dataintro dnt;

 

then you are telling the compiler that you wish to reference an Object of type dataintro, using the name dnt.  If the compiler is objecting to this, then it is because it can't find this class.  So you need to look for it or correct your packageme names or imports so that the compiler can find it.  It appears this is not a BlackBerry problem, it is a Java problem. 

Contributor
Posts: 13
Registered: ‎08-23-2011
My Device: Developer
My Carrier: Developer

Re: simple json and xml file parsing

Thx for the reply.....

Actually i search for Dataintro but i m not able to resolve it. Can you please help me for this...

Developer
Posts: 17,019
Registered: ‎07-29-2008
My Device: Z10 LE, Z30, Passport
My Carrier: O2 Germany

Re: simple json and xml file parsing

most likely it is a custom bean class to store the retreived information.

just remove it from the code and be done with it.

using sample code without understanding it may not be the best way to start development.
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Contributor
Posts: 13
Registered: ‎08-23-2011
My Device: Developer
My Carrier: Developer

Re: simple json and xml file parsing

Thx for the reply.....................