My idea was to download the xml only one when the application was opened for the first time.
I have implemented this in this way
Using java Syntax Highlighting
- public class Main extends Activity{
- static final int PROGRESS_DIALOG = 0;
- Button button;
- ProgressDialog progressDialog;
- ProgressDialog myProgressDialog = null;
- MyDbAdapter adapter;
- final String employeeURL = http://MY_EMPLOYEE_XML_URL;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- adapter = openDb();
- adapter.createAchieTable();
- boolean dbInitialized = adapter.initDatabase();
- // checks if the database has been successfully initialized
- if(dbInitialized){
- //database has been initialized
- int i = adapter.getFlag(ACHIE_STATE);
- if(i == 1){
- //ACHIE_STATE == 1; means that the database is already available.
- button = (Button)findViewById(R.id.show_employees);
- button.setOnClickListener(new OnClickListener(){
- public void onClick(View v){
- // Display an indeterminate Progress-Dialog
- myProgressDialog = ProgressDialog.show(Main.this, "Please wait", "Loading Data...", true);
- Intent intent = new Intent(Main.this, EmployeeList.class);
- adapter.close();
- myProgressDialog.dismiss();
- startActivity(intent);
- }
- });
- }else{
- // ACHIE_STATE < 1; means database hasn't been downloaded yet. Create tables and download data.
- Log.v(this.getClass().getName(), " download employees");
- adapter.createEmployeesTable();
- button = (Button)findViewById(R.id.show_employees);
- button.setOnClickListener(new OnClickListener(){
- public void onClick(View v){
- // Display an indeterminate Progress-Dialog
- myProgressDialog = ProgressDialog.show(Main.this, "Message", "Downloading Employee Data", true);
- if(adapter.getFlag(ACHIE_STATE) < 1){
- new Thread() {
- public void run() {
- try{
- Log.v("Main: ", "Start database check");
- Thread.sleep(2000);
- downloadTables(employeeURL);
- Log.v("Main: ", "downloaded Employees");
- Thread.sleep(2000);
- } catch (Exception e) { }
- // Dismiss the Dialog
- Intent i = new Intent(Main.this, EmployeeList.class);
- myProgressDialog.dismiss();
- startActivity(i);
- }
- }.start();
- }else if (adapter.getFlag(EMPLOYEES_STATE) >= 1){
- Intent i = new Intent(Main.this, EmployeeList.class);
- myProgressDialog.dismiss();
- startActivity(i);
- }
- }
- });
- }
- }else{
- // database has not been initialized. Try to initialize it. App should not reach here in normal circumstances.
- Log.v(this.getClass().getName(), " Initialize database");
- }
- }
- private MyDbAdapter openDb(){
- adapter = new MyDbAdapter(this);
- adapter.open();
- return adapter;
- }
- public int downloadTables(String xmlUrl){
- int downloadStatus = 0;
- try{
- URL url = new URL(xmlUrl);
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser parser = factory.newSAXParser();
- XMLReader reader = parser.getXMLReader();
- MyHandler handler = new MyHandler(adapter);
- reader.setContentHandler(handler);
- reader.parse(new InputSource(url.openStream()));
- }catch(Exception e){
- Log.e("Error: ", "" + e.getMessage());
- System.exit(0);
- }finally{
- downloadStatus = 1;
- }
- return downloadStatus;
- }
- protected void onPause(){
- Log.v("progress bar view: ", "onPause method called");
- super.onPause();
- }
- protected void onRestart(){
- adapter.close();
- adapter = openDb();
- super.onRestart();
- }
- protected void onStop(){
- adapter.close();
- Log.v("progress bar view: ", "onStop method called");
- super.onStop();
- }
- protected void onDestroy(){
- adapter.close();
- Log.v("progress bar view: ", "onDestroy method called");
- super.onDestroy();
- }
- }
Parsed in 0.048 seconds, using GeSHi 1.0.8.4
EmployeeList to show the list of employees downloaded
Using java Syntax Highlighting
- package com.achie.test;
- import android.app.ListActivity;
- import android.database.Cursor;
- import android.os.Bundle;
- import android.util.Log;
- import android.widget.SimpleCursorAdapter;
- public class EmployeeList extends ListActivity{
- MyDbAdapter adapter;
- Cursor cursor;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.employees);
- adapter = new MyDbAdapter(this);
- try{
- adapter.open();
- cursor = adapter.fetchEmployees();
- startManagingCursor(cursor);
- showEmployees(cursor);
- }finally {
- adapter.close();
- }
- }
- protected void onPause(){
- Log.v("Employee List: ", "onPause method called");
- super.onPause();
- }
- protected void onStop(){
- Log.v("Employee list: ", "onStop method called");
- cursor.close();
- adapter.close();
- super.onStop();
- }
- public void showEmployees(Cursor cursor){
- int[] TO = new int[]{R.id.name};
- String[] FROM = new String[]{"employee"};
- SimpleCursorAdapter cAdapter = new SimpleCursorAdapter(this, R.layout.item_all, cursor, FROM, TO);
- setListAdapter(cAdapter);
- }
- }
Parsed in 0.035 seconds, using GeSHi 1.0.8.4
My database adapter
Using java Syntax Highlighting
- package com.achie.test;
- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.util.Log;
- import java.lang.String;
- import static com.achie.test.Constants.*;
- import static android.content.Context.*;
- public class MyDbAdapter {
- private SQLiteDatabase db;
- private Context context;
- public MyDbAdapter(Context c){
- this.context = c;
- }
- public boolean deleteDatabase(){
- return context.deleteDatabase(DATABASE);
- }
- public SQLiteDatabase open(){
- db = context.openOrCreateDatabase(DATABASE, MODE_PRIVATE, null);
- return db;
- }
- public void close(){
- if(db.isOpen()){
- db.close();
- }
- }
- //*****************Application specific*********
- public void createAchieTable(){
- db.execSQL("CREATE TABLE IF NOT EXISTS " + ACHIE_TABLE + " ("
- + ACHIE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
- + ACHIE_STATE + " INTEGER, "
- + EMPLOYEES_STATE + " INTEGER );");
- }
- public boolean initDatabase(){
- Log.v("Database: ", "in initDatabase");
- Cursor c = db.rawQuery("SELECT COUNT(_id) as count_x FROM "+ACHIE_TABLE , null);
- c.moveToFirst();
- int count = c.getInt(c.getColumnIndex("count_x"));
- Log.v("Database: ", "in initDatabase "+c.moveToFirst()+" count: "+c.getInt(c.getColumnIndex("count_x"))+" : ::"+count+": "+count);
- if(count < 1){
- Log.v("Database: ", "No elements in ACHIE");
- // If the table doesn't have any records insert a default row.
- ContentValues v = new ContentValues();
- v.put(ACHIE_ID, "1");
- v.put(ACHIE_STATE, "-1");
- v.put(EMPLOYEES_STATE, "-1");
- Log.v("Database: ", "Inserting ");
- db.insert(ACHIE_TABLE, null, v);
- db.execSQL("UPDATE "+ACHIE_TABLE+ " SET "+ACHIE_STATE+ " = 0 WHERE _id = 1;" );
- }
- c = db.query(ACHIE_TABLE, new String[]{ACHIE_STATE}, ACHIE_ID + " = 1", null, null, null, null);
- Log.v("Database: ", "in initDatabase "+c.moveToFirst());
- if(c.moveToFirst()){
- if(c.getInt(c.getColumnIndex(ACHIE_STATE)) >= 0){
- //returns true if the ACHIE state is >= 0
- Log.v("Database: ", "in initDatabase state is "+c.getInt(c.getColumnIndex(ACHIE_STATE)));
- return true;
- }
- }
- return false;
- }
- public void setFlag(String column, int flag){
- db.execSQL("UPDATE "+ACHIE_TABLE+ " SET "+column+ " = "+flag+" WHERE _id = 1;" );
- }
- public int getFlag(String column){
- Cursor c = db.query(ACHIE_TABLE, new String[]{column}, ACHIE_ID + " = 1", null, null, null, null);
- if(c.moveToFirst()){
- return c.getInt(0);
- }
- return -2;
- }
- public boolean checkDatabase(){
- Cursor c = null;
- c = db.query(ACHIE_TABLE, new String[]{ACHIE_STATE, EMPLOYEES_STATE },
- ACHIE_ID + " = 1", null, null, null, null);
- if(c.moveToFirst()){
- int flagCount = c.getInt(0) + c.getInt(1);
- if(flagCount < 2)
- return false;
- return true;
- }
- return false;
- }
- public Cursor getDatabaseStatus(){
- return db.query(ACHIE_TABLE, new String[]{ACHIE_STATE, EMPLOYEES_STATE},
- ACHIE_ID + " = 1", null, null, null, null);
- }
- // Employees
- public void createEmployeesTable(){
- db.execSQL("CREATE TABLE IF NOT EXISTS " + EMPLOYEES_TABLE + " (" + EID + " INTEGER PRIMARY KEY , " + EMPLOYEE_NAME
- + " TEXT NOT NULL );");
- }
- public void deleteEmployeesTable(){
- db.execSQL("DROP TABLE IF EXISTS " +EMPLOYEES_TABLE+ ";");
- }
- public long addEmployee(Employee e){
- ContentValues values = new ContentValues();
- values.put(EID, e.getId());
- values.put(EMPLOYEE_NAME, e.getName());
- long result = -1;
- result = db.insert(EMPLOYEES_TABLE, null, values);
- return result;
- }
- public Cursor fetchEmployees() {
- Log.v(this.getClass().getName(), "Fetching Employees");
- Cursor c = db.query(EMPLOYEES_TABLE, new String[] {EID, EMPLOYEE_NAME}, null, null, null, null, EMPLOYEE_NAME);
- return c;
- }
- }
Parsed in 0.053 seconds, using GeSHi 1.0.8.4
Everything works fine.
Even when I open the application It downloads for the first time and just shows the list from the next time.
My only problem is that It shows these errors when I click on back and open the list for three or four times. It then stops.
can anyone tell me whats causing this and how to solve this?
Looks like the sursor has not been closed. But I am trying to close it in the onDestroy and onStop menthods
Using xml Syntax Highlighting
- I/dalvikvm( 846): at android.database.sqlite.SQLiteCursor.finalize(SQLiteCursor.java:596)
- I/dalvikvm( 846): at dalvik.system.NativeStart.run(Native Method)
- I/dalvikvm( 846): Uncaught exception thrown by finalizer (will be discarded):
- I/dalvikvm( 846): Ljava/lang/IllegalStateException;: Finalizing cursor android.database.sqlite.SQLiteCursor@43acd858 on achie that has not been deactivated or closed
- I/dalvikvm( 846): at android.database.sqlite.SQLiteCursor.finalize(SQLiteCursor.java:596)
- I/dalvikvm( 846): at dalvik.system.NativeStart.run(Native Method)
- I/dalvikvm( 846): Uncaught exception thrown by finalizer (will be discarded):
- I/dalvikvm( 846): Ljava/lang/IllegalStateException;: Finalizing cursor android.database.sqlite.SQLiteCursor@43ac02d8 on achie that has not been deactivated or closed
Parsed in 0.000 seconds, using GeSHi 1.0.8.4
I can also send my code to anyone who wants to recreate the entire app.
I would also post the entire solution here after solving it if anyone is interested.
thank you.


