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
Contributor
Posts: 43
Registered: ‎07-22-2012
My Device: curve
My Carrier: syudent
Accepted Solution

connection with sqlite not work

i have 3 classes

first class

public class MyApp extends UiApplication {
	/**
	 * Entry point for application
	 * 
	 * @param args
	 *            Command line arguments (not used)
	 */
	public static void main(String[] args) {
		// Create a new instance of the application and make the currently
		// running thread the application's event dispatch thread.
		MyApp theApp = new MyApp();
		theApp.enterEventDispatcher();
	}

	/**
	 * Creates a new MyApp object
	 */
	public MyApp() {
		// Push a screen onto the UI stack for rendering.
		DBAdapter db=new DBAdapter();
		db.openOrCreateDatabase();
		pushScreen(new MyScreen());
	}
}

 second class

public final class MyScreen extends MainScreen implements FieldChangeListener
{
    /**
     * Creates a new MyScreen object
     */
	private ButtonField addButton = new ButtonField("Add Records",
			ButtonField.CONSUME_CLICK | Field.FIELD_HCENTER);
	private ButtonField deleteButton = new ButtonField("Delete Records",
			ButtonField.CONSUME_CLICK | Field.FIELD_HCENTER);
    public MyScreen()
    {        
        // Set the displayed title of the screen       
        setTitle("MyTitle");
        HorizontalFieldManager hfm = new HorizontalFieldManager();
		addButton.setChangeListener(this);
		deleteButton.setChangeListener(this);
		hfm.add(addButton);
		hfm.add(deleteButton);
		add(hfm);
    }
	public void fieldChanged(Field field, int context) {
		// TODO Auto-generated method stub
		if (field == addButton) {
			DBAdapter db=new DBAdapter();
	        db.insertTableData();
	        String[] data=db.getCat();
		}
	}
}

 third class

public class DBAdapter {

	private static String DB_NAME = "test.db";
	public Database db;
	public void openOrCreateDatabase() {
		boolean sdCardPresent = false;
		String root = null;
		Enumeration e = FileSystemRegistry.listRoots();
		while (e.hasMoreElements()) {
			root = (String) e.nextElement();
			if (root.equalsIgnoreCase("sdcard/")) {
				sdCardPresent = true;
			}
		}
		if (!sdCardPresent) {
			UiApplication.getUiApplication().invokeLater(new Runnable() {
				public void run() {
					Dialog.alert("This application requires an SD card to be present. Exiting application...");
					System.exit(0);
				}
			});
		} else {
			try {
				
				String dbLocation = "/SDCard/databases/";
				// Create URI
				URI uri = URI.create(dbLocation + DB_NAME);

				// Open or create a plain text database. This will create the
				// directory and file defined by the URI (if they do not already
				// exist).
				db = DatabaseFactory.openOrCreate(uri);
				createDatabaseSchema();
			} catch (Exception ae) {
				Dialog.alert("Error,database not created...");
			}
		}
	}

	private void createDatabaseSchema() {
		Statement st = null;
		try {
			st = db.createStatement("CREATE TABLE IF NOT EXISTS 'People' ( 'Name' TEXT, 'Age' INTEGER )");
			st.prepare();
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				st.close();
			} catch (DatabaseException e) {
			}
		}
	}

	public void insertTableData() {
		Statement st = null;
		try {
			st = db.createStatement("INSERT INTO People(Name,Age) VALUES (?,?)");
			st.prepare();
			Hashtable ht = new Hashtable(5);
			ht.put("Joe", new Integer(6));
			ht.put("Mike", new Integer(7));
			ht.put("Marie", new Integer(12));
			ht.put("Dennis", new Integer(14));
			ht.put("Richard", new Integer(12));
			Enumeration names = ht.keys();
			Enumeration ages = ht.elements();
			while (names.hasMoreElements()) {
				String strName = (String) names.nextElement();
				Integer iAge = (Integer) ages.nextElement();
				st.bind(1, strName);
				st.bind(2, iAge.intValue());
				st.execute();
				st.reset();
				Dialog.alert("ok");
			}
		} catch (Exception e) {
			Dialog.alert("Error");
		} finally {
			try {
				st.close();
			} catch (DatabaseException e) {
				Dialog.alert("Error");
			}
		}
	}

	public String[] getCat() {
		String[] data = {};
		if (db == null) {
			return data;
		}
		Statement st = null;
		try {
			st = db.createStatement("SELECT Id,Name FROM Cat");
			st.prepare();
			Cursor c = st.getCursor();
			if (c == null) {
				return data;
			}
			Row r;
			int i = 0;

			while (c.next()) {
				r = c.getRow();
				data[i] = r.getString(1);
				i++;
				// recordList.insert(0, r.getString(0) + " - " +
				// r.getInteger(1)+ " years old");
			}
			if (i == 0) {
				return data;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				st.close();
			} catch (Exception e) {
			}
		}
		return data;
	}
}

 there is problem please help me

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

Re: connection with sqlite not work

It would be helpful if you described where the problem is, what you expect it to do, and what it is actually doing?  Have you stepped through the code?  Is this happening on the Simulator or a real device?  What OS are you testing with?  People only have a limited time to help - if you describe the problem better then they will spend less time figuring out what the problem is and more time helping you fix it.  . 

Contributor
Posts: 43
Registered: ‎07-22-2012
My Device: curve
My Carrier: syudent

Re: connection with sqlite not work

it doesn't work database created and tables but when insert data make error but i can't find why this

Contributor
Posts: 43
Registered: ‎07-22-2012
My Device: curve
My Carrier: syudent

Re: connection with sqlite not work

sorry i 'm new
Developer
Posts: 434
Registered: ‎07-23-2012
My Device: Blackberry 10
My Carrier: Orange

Re: connection with sqlite not work

Walkthrough your code and found that if u have SD card than only you are creating database.

  1. Check you device has SD card or not
  2. Test with simulator, add SD card and check you folder @ your local system you must found .db file there if u found then you are able to make database.
Thanks
-------------------------------------------------------------------------------------
Press the Accept as solution Button when u got the Solution
Press Kudo to say thank to developer.
-------------------------------------------------------------------------------------.
Developer
Posts: 19,636
Registered: ‎07-14-2008
My Device: Not Specified

Re: connection with sqlite not work

Also re  "when insert data make error ".  What is the error? Which line is it occuring on?

Contributor
Posts: 43
Registered: ‎07-22-2012
My Device: curve
My Carrier: syudent

Re: connection with sqlite not work

[ Edited ]

the database created and i found it in the path i selected but when call insert method he get error on select statement so make error but i can't why

Developer
Posts: 713
Registered: ‎05-31-2010
My Device: 8520
My Carrier: Movistar

Re: connection with sqlite not work

How do you set the "db" instance in the screen ?

Developer
Posts: 434
Registered: ‎07-23-2012
My Device: Blackberry 10
My Carrier: Orange

Re: connection with sqlite not work

 

Few points

  1. Where is you commit??
  2. Try with db.beginTransaction(); and db.commitTransaction();

 

Your code will be looks like this

        String Query = "INSERT INTO People(Name,Age) VALUES (?,?)";

                                Statement st = null;

                                try {

                                                st = db.createStatement(Query);

                                                db.beginTransaction();

                                                st.prepare();

                                                Hashtable ht = new Hashtable(5);

                                                ht.put("Joe", new Integer(6));

                                                ht.put("Mike", new Integer(7));

                                                ht.put("Marie", new Integer(12));

                                                ht.put("Dennis", new Integer(14));

                                                ht.put("Richard", new Integer(12));

                                                Enumeration names = ht.keys();

                                                Enumeration ages = ht.elements();

                                                while (names.hasMoreElements()) {

                                                                String strName = (String) names.nextElement();

                                                                Integer iAge = (Integer) ages.nextElement();

                                                                st.bind(1, strName);

                                                                st.bind(2, iAge.intValue());

                                                                st.execute();

                                                                st.reset();

                                                                Dialog.alert("ok");

                                                }

                                } catch (Exception e) {

                                                Dialog.alert("Error");

                                } finally {

                                                try {

                                                                st.close();

                                                                db.commitTransaction();

                                                    st = null;

                                                } catch (DatabaseException e) {

                                                                Dialog.alert("Error");

                                                }

                                }

 

 

 

Thanks
-------------------------------------------------------------------------------------
Press the Accept as solution Button when u got the Solution
Press Kudo to say thank to developer.
-------------------------------------------------------------------------------------.
Contributor
Posts: 43
Registered: ‎07-22-2012
My Device: curve
My Carrier: syudent

Re: connection with sqlite not work

make error also i think that i open database in main so when i call methods in other class db object will be empty so make error what i do ??