Cursor problem

Problems with WiFi, SQLite ,Bluetooth, WiMax, Proxies, etc...

Cursor problem

Postby davidtweaver » Sat Dec 19, 2009 5:17 pm

Hello.

I'm relatively new to SQlite databases. I tried modifying the notepad2 tutorial that came with the SDK. I modified so that it would load an existing database using the file reader. The code below always throws errors and the process stops unexpectedly. I have absolutely no idea why as the SQL seems to be fine. If anyone can help then I'd be most grateful.

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package com.allergycookbook;
  3.  
  4.  
  5.  
  6. import java.io.IOException;
  7.  
  8.  
  9.  
  10. import android.app.ListActivity;
  11.  
  12. import android.database.Cursor;
  13.  
  14. import android.database.SQLException;
  15.  
  16. import android.os.Bundle;
  17.  
  18. import android.widget.SimpleCursorAdapter;
  19.  
  20. import android.widget.Toast;
  21.  
  22.  
  23.  
  24. public class AllergyCookBook extends ListActivity {
  25.  
  26.     /** Called when the activity is first created. */
  27.  
  28.     //@Override
  29.  
  30.    
  31.  
  32.     private DataBaseHelper myDbHelper;
  33.  
  34.     private Cursor mNotesCursor;
  35.  
  36.     private static final String DATABASE_TABLE = "recipes";
  37.  
  38.    
  39.  
  40.     public void onCreate(Bundle savedInstanceState) {
  41.  
  42.         super.onCreate(savedInstanceState);
  43.  
  44.        
  45.  
  46.         //set to main if there's problems
  47.  
  48.         setContentView(R.layout.recipe_list);
  49.  
  50.        
  51.  
  52.         DataBaseHelper myDbHelper = new DataBaseHelper(getBaseContext());
  53.  
  54.         myDbHelper = new DataBaseHelper(getBaseContext());
  55.  
  56.        
  57.  
  58.        
  59.  
  60.         try {
  61.  
  62.                  
  63.  
  64.                 myDbHelper.createDataBase();
  65.  
  66.                
  67.  
  68.                 Toast.makeText(AllergyCookBook.this, "Database creation success", Toast.LENGTH_SHORT).show();
  69.  
  70.                 } catch (IOException ioe) {
  71.  
  72.                        
  73.  
  74.                 throw new Error("Unable to create database");
  75.  
  76.                
  77.  
  78.                 }
  79.  
  80.  
  81.  
  82.                
  83.  
  84.  
  85.  
  86.        
  87.  
  88.         // Get all of the rows from the database and create the item list
  89.  
  90.        
  91.  
  92.        
  93.  
  94.    
  95.  
  96.         myDbHelper.openDataBase();
  97.  
  98.         fillData();
  99.  
  100.     registerForContextMenu(getListView());
  101.  
  102.  
  103.  
  104.     }
  105.  
  106.    
  107.  
  108.         //comment out everything below and it works
  109.  
  110.    
  111.  
  112.  
  113.  
  114.    
  115.  
  116.    
  117.  
  118.        
  119.  
  120.         private void fillData()
  121.  
  122.         {
  123.  
  124.                
  125.  
  126.         //the problem is definitely here
  127.  
  128.                
  129.  
  130.         // Get all of the rows from the database and create the item list
  131.  
  132.         mNotesCursor = myDbHelper.fetchAllNotes();
  133.  
  134.         startManagingCursor(mNotesCursor);
  135.  
  136.        
  137.  
  138.         // Create an array to specify the fields we want to display in the list (only TITLE)
  139.  
  140.         String[] from = new String[]{DataBaseHelper.KEY_TITLE};
  141.  
  142.        
  143.  
  144.         // and an array of the fields we want to bind those fields to (in this case just text1)
  145.  
  146.         int[] to = new int[]{R.id.text1};
  147.  
  148.        
  149.  
  150.         // Now create a simple cursor adapter and set it to display
  151.  
  152.         SimpleCursorAdapter notes =
  153.  
  154.                     new SimpleCursorAdapter(this, R.layout.recipe_row, mNotesCursor, from, to);
  155.  
  156.        setListAdapter(notes);
  157.  
  158.         }
  159.  
  160.        
  161.  
  162. ///////////////////////////////////////////////////////////////////////////////////////////
  163.  
  164.  
  165.  
  166. package com.allergycookbook;
  167.  
  168.  
  169.  
  170. import java.io.FileOutputStream;
  171.  
  172. import java.io.IOException;
  173.  
  174. import java.io.InputStream;
  175.  
  176. import java.io.OutputStream;
  177.  
  178.  
  179.  
  180. import android.content.Context;
  181.  
  182. import android.database.Cursor;
  183.  
  184. import android.database.SQLException;
  185.  
  186. import android.database.sqlite.SQLiteDatabase;
  187.  
  188. import android.database.sqlite.SQLiteException;
  189.  
  190. import android.database.sqlite.SQLiteOpenHelper;
  191.  
  192.  
  193.  
  194.  
  195.  
  196.         public class DataBaseHelper extends SQLiteOpenHelper{
  197.  
  198.                  
  199.  
  200.             //The Android's default system path of your application database.
  201.  
  202.             private static String DB_PATH = "/data/data/com.allergycookbook/databases/";
  203.  
  204.          
  205.  
  206.             private static String DB_NAME = "cookbook";
  207.  
  208.          
  209.  
  210.          
  211.  
  212.            
  213.  
  214.             public static final String KEY_TITLE = "recipe_name";
  215.  
  216.             public static final String KEY_ROWID = "_id";
  217.  
  218.             private static final String DATABASE_TABLE = "recipes";
  219.  
  220.            
  221.  
  222.            
  223.  
  224.             private SQLiteDatabase myDataBase;
  225.  
  226.          
  227.  
  228.             private final Context myContext;
  229.  
  230.            
  231.  
  232.            
  233.  
  234.            
  235.  
  236.             //
  237.  
  238.             /**
  239.  
  240.              * Constructor
  241.  
  242.              * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
  243.  
  244.              * @param context
  245.  
  246.              */
  247.  
  248.             public DataBaseHelper(Context context) {
  249.  
  250.          
  251.  
  252.                 super(context, DB_NAME, null, 1);
  253.  
  254.                 this.myContext = context;
  255.  
  256.             }  
  257.  
  258.          
  259.  
  260.           /**
  261.  
  262.              * Creates a empty database on the system and rewrites it with your own database.
  263.  
  264.              * */
  265.  
  266.             public void createDataBase() throws IOException{
  267.  
  268.          
  269.  
  270.  
  271.  
  272.                 // create new
  273.  
  274.                
  275.  
  276.                 //this.getReadableDatabase();
  277.  
  278.                
  279.  
  280.                 /*myDataBase.execSQL("CREATE TABLE IF NOT EXISTS "
  281.  
  282.                     + DATABASE_TABLE
  283.  
  284.                     + " (_id INTEGER PRIMARY KEY, recipe_name TEXT,"
  285.  
  286.                     + " ingredients TEXT, method TEXT);");*/
  287.  
  288.                
  289.  
  290.                
  291.  
  292.                 boolean dbExist = checkDataBase();
  293.  
  294.          
  295.  
  296.                 if(dbExist){
  297.  
  298.                         //do nothing - database already exist
  299.  
  300.                        
  301.  
  302.                        
  303.  
  304.                 }else{
  305.  
  306.          
  307.  
  308.                         //By calling this method and empty database will be created into the default system path
  309.  
  310.                        //of your application so we are gonna be able to overwrite that database with our database.
  311.  
  312.                         this.getReadableDatabase();
  313.  
  314.          
  315.  
  316.                         try {
  317.  
  318.                                
  319.  
  320.                                 copyDataBase();
  321.  
  322.          
  323.  
  324.                 } catch (IOException e) {
  325.  
  326.          
  327.  
  328.                                 throw new Error("Error copying database");
  329.  
  330.          
  331.  
  332.                         }
  333.  
  334.                 }
  335.  
  336.          
  337.  
  338.             }
  339.  
  340.          
  341.  
  342.             /**
  343.  
  344.              * Check if the database already exist to avoid re-copying the file each time you open the application.
  345.  
  346.              * @return true if it exists, false if it doesn't
  347.  
  348.              */
  349.  
  350.             private boolean checkDataBase(){
  351.  
  352.          
  353.  
  354.                 SQLiteDatabase checkDB = null;
  355.  
  356.          
  357.  
  358.                 try{
  359.  
  360.                         String myPath = DB_PATH + DB_NAME;
  361.  
  362.                         checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
  363.  
  364.          
  365.  
  366.                 }catch(SQLiteException e){
  367.  
  368.          
  369.  
  370.                         //database does't exist yet.
  371.  
  372.          
  373.  
  374.                 }
  375.  
  376.          
  377.  
  378.                 if(checkDB != null){
  379.  
  380.          
  381.  
  382.                         checkDB.close();
  383.  
  384.          
  385.  
  386.                 }
  387.  
  388.          
  389.  
  390.                 return checkDB != null ? true : false;
  391.  
  392.             }
  393.  
  394.          
  395.  
  396.             /**
  397.  
  398.              * Copies your database from your local assets-folder to the just created empty database in the
  399.  
  400.              * system folder, from where it can be accessed and handled.
  401.  
  402.              * This is done by transfering bytestream.
  403.  
  404.              * */
  405.  
  406.             private void copyDataBase() throws IOException{
  407.  
  408.          
  409.  
  410.                 /*myDataBase.execSQL("CREATE TABLE IF NOT EXISTS "
  411.  
  412.                     + DATABASE_TABLE
  413.  
  414.                     + " (_id INTEGER PRIMARY KEY, recipe_name TEXT,"
  415.  
  416.                     + " ingredients TEXT, method TEXT);");
  417.  
  418.                
  419.  
  420.                  ContentValues values = new ContentValues();
  421.  
  422.                  values.put("recipe_name", "pancakes");
  423.  
  424.                  //values.put("field2", "value_for_field2");
  425.  
  426.                  myDataBase.insert(DATABASE_TABLE, null, values);*/
  427.  
  428.                
  429.  
  430.                
  431.  
  432.                 //Open your local db as the input stream
  433.  
  434.                 InputStream myInput = myContext.getAssets().open("cookbook");
  435.  
  436.          
  437.  
  438.                 // Path to the just created empty db
  439.  
  440.                 String outFileName = DB_PATH + DB_NAME;
  441.  
  442.          
  443.  
  444.                 //Open the empty db as the output stream
  445.  
  446.                 OutputStream myOutput = new FileOutputStream(outFileName);
  447.  
  448.          
  449.  
  450.                 //transfer bytes from the inputfile to the outputfile
  451.  
  452.                 byte[] buffer = new byte[1024];
  453.  
  454.                 int length;
  455.  
  456.                 while ((length = myInput.read(buffer))>0){
  457.  
  458.                         myOutput.write(buffer, 0, length);
  459.  
  460.                 }
  461.  
  462.          
  463.  
  464.                 //Close the streams
  465.  
  466.                 myOutput.flush();
  467.  
  468.                 myOutput.close();
  469.  
  470.                 myInput.close();
  471.  
  472.                 //Toast.makeText(DataBaseHelper.this, "Database copying success", Toast.LENGTH_SHORT).show();
  473.  
  474.                        
  475.  
  476.             }
  477.  
  478.          
  479.  
  480.             public void openDataBase() throws SQLException{
  481.  
  482.          
  483.  
  484.                 //Open the database
  485.  
  486.                 String myPath = DB_PATH + DB_NAME;
  487.  
  488.                 myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
  489.  
  490.                
  491.  
  492.          
  493.  
  494.             }
  495.  
  496.          
  497.  
  498.             @Override
  499.  
  500.                 public synchronized void close() {
  501.  
  502.          
  503.  
  504.                     if(myDataBase != null)
  505.  
  506.                             myDataBase.close();
  507.  
  508.          
  509.  
  510.                     super.close();
  511.  
  512.          
  513.  
  514.                 }
  515.  
  516.          
  517.  
  518.                 @Override
  519.  
  520.                 public void onCreate(SQLiteDatabase db) {
  521.  
  522.          
  523.  
  524.                 }
  525.  
  526.          
  527.  
  528.                 @Override
  529.  
  530.                 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  531.  
  532.          
  533.  
  534.                 }
  535.  
  536.          
  537.  
  538.                 // Add your public helper methods to access and get content from the database.
  539.  
  540.                // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
  541.  
  542.                // to you to create adapters for your views.
  543.  
  544.                
  545.  
  546.                 //start of my additions
  547.  
  548.             public Cursor fetchAllNotes(){
  549.  
  550.                 try{
  551.  
  552.                 return myDataBase.query(DATABASE_TABLE, new String[] {"_id", "recipe_name"}, null, null, null, null,null);
  553.  
  554.  
  555.  
  556.                 }catch(SQLiteException e){
  557.  
  558.                          
  559.  
  560.                         return null;
  561.  
  562.                         //database does't exist yet.
  563.  
  564.          
  565.  
  566.                 }
  567.  
  568.                 //return myDataBase.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE},null,null,null,null,null);
  569.  
  570.             }
  571.  
  572.  
  573.  
  574.             /**
  575.  
  576.              * Return a Cursor positioned at the note that matches the given rowId
  577.  
  578.              *
  579.  
  580.              * @param rowId id of note to retrieve
  581.  
  582.              * @return Cursor positioned to matching note, if found
  583.  
  584.              * @throws SQLException if note could not be found/retrieved
  585.  
  586.              */
  587.  
  588.             public Cursor fetchNote(long rowId) throws SQLException {
  589.  
  590.  
  591.  
  592.                 Cursor mCursor =
  593.  
  594.  
  595.  
  596.                         myDataBase.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
  597.  
  598.                                 KEY_TITLE}, KEY_ROWID + "=" + rowId, null,
  599.  
  600.                                 null, null, null, null);
  601.  
  602.                 if (mCursor != null) {
  603.  
  604.                     mCursor.moveToFirst();
  605.  
  606.                 }
  607.  
  608.                 return mCursor;
  609.  
  610.  
  611.  
  612.             }
  613.  
  614.             //end of my additions        
  615.  
  616.         }
  617.  
  618.  
  619.  
  620. }
Parsed in 0.061 seconds, using GeSHi 1.0.8.4
Last edited by davidtweaver on Sun Dec 20, 2009 10:01 pm, edited 1 time in total.
davidtweaver
Freshman
Freshman
 
Posts: 5
Joined: Sat Dec 19, 2009 5:01 pm

Top

Postby qlimax » Sat Dec 19, 2009 7:52 pm

I suggest you to use the
logcat
the_application_-und-lttask_name-und-gt_has_stopped_unexpectedly-t3452.html

and the java syntax highlighting function of the forum...

bye
¯`·.¸¸.><((((º>¯`·.¸¸. ><((((º>
User avatar
qlimax
Master Developer
Master Developer
 
Posts: 271
Joined: Mon Aug 31, 2009 10:54 am
Location: Swiss

Postby davidtweaver » Sun Dec 20, 2009 9:59 pm

The logcat messages are below:

12-20 20:50:30.918: ERROR/AndroidRuntime(721): Uncaught handler: thread main exiting due to uncaught exception
12-20 20:50:30.938: ERROR/AndroidRuntime(721): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.allergycookbook/com.allergycookbook.AllergyCookBook}: java.lang.NullPointerException
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2401)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at android.app.ActivityThread.access$2100(ActivityThread.java:116)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at android.os.Handler.dispatchMessage(Handler.java:99)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at android.os.Looper.loop(Looper.java:123)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at android.app.ActivityThread.main(ActivityThread.java:4203)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at java.lang.reflect.Method.invokeNative(Native Method)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at java.lang.reflect.Method.invoke(Method.java:521)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at dalvik.system.NativeStart.main(Native Method)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): Caused by: java.lang.NullPointerException
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at com.allergycookbook.AllergyCookBook.fillData(AllergyCookBook.java:111)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at com.allergycookbook.AllergyCookBook.onCreate(AllergyCookBook.java:65)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): ... 11 more

I can see that it's a null pointer exception but I don't know *why* that should be the case. I pulled the databse from the device using eclipses DDMS persepective. The database definetly exists and has data in it (and presumably therefore shouldn't be returning null when it is queried?)
davidtweaver
Freshman
Freshman
 
Posts: 5
Joined: Sat Dec 19, 2009 5:01 pm

Postby achie1266 » Tue Dec 22, 2009 7:11 am

ofcourse

12-20 20:50:30.938: ERROR/AndroidRuntime(721): at com.allergycookbook.AllergyCookBook.fillData(AllergyCookBook.java:111)
12-20 20:50:30.938: ERROR/AndroidRuntime(721): at com.allergycookbook.AllergyCookBook.onCreate(AllergyCookBook.java:65)

That is where your nullPointerException is coming from.

And if I am right with the line numbers it should be coming from this line in your fillData method
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. mNotesCursor = myDbHelper.fetchAllNotes();
Parsed in 0.031 seconds, using GeSHi 1.0.8.4
That is because your global variable myDbHelper has never been initialized. You are creating another DataBaseHelper myDbHelper in your onCreate method
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. DataBaseHelper myDbHelper = new DataBaseHelper(getBaseContext());
Parsed in 0.034 seconds, using GeSHi 1.0.8.4
. you may want to change the code to remove creating another variable and using the global one itself. Or you can assign the local myDbHelper to the global one.
achie
User avatar
achie1266
Master Developer
Master Developer
 
Posts: 223
Joined: Mon Nov 09, 2009 10:56 pm
Location: Denver

Top

Return to Networking & Database Problems

Who is online

Users browsing this forum: No registered users and 8 guests