Problem beim Zugriff auf vorbereitete SQLite Datenbank

  • 7 Antworten
  • Letztes Antwortdatum
O

obelixpp

Neues Mitglied
0
Hallo zusammen,
ich habe ein Problem und zwar habe ich eine SQLite Datenbank vorbereitet und diese nach folgender Anleitung in mein Android Projekt eingefügt.
Reicht es wenn ich in meiner "Main" Klasse die also direkt beim Start aufgerufen wird die Datenbank mit

Code:
// Datenbank wird geöffnet
        DataBaseHelper myDbHelper = new DataBaseHelper(this);
        myDbHelper = new DataBaseHelper(this);
        
        try {
 
        	myDbHelper.createDataBase();
 
	 	} catch (IOException ioe) {
	 
	 		throw new Error("Unable to create database");
	 
	 	}
	 
	 	try {
	 
	 		myDbHelper.openDataBase();
	 
	 	}catch(SQLException sqle){
	 
	 		throw sqle;
	 
	 	}        
	}

in der OnCreate Methode öffne, oder erst wenn sie wirklich in einer Activity benötigt wird?
Mein Problem ist jetzt das ich mir zwar den Namen der Datenbank ausgeben lassen kann, aber sonst irgendwie nicht weiß wie ich auf die einzelnen Tabellen zugreifen kann.
Ich möchte eine ListView haben mit der Spalte name haben, also jede Zeile der DB soll eine Zeile in der ListView sein und wenn ich dann auf den entsprechenden Eintrag klicke soll sich später eine neue Activity öffnen wo die restlichen dazugehörigen Daten wie Adresse, Telefon, etc. geladen und in Textviews geschrieben werden.

Hier mal die Tabelle Servicestellen:
sqlitearxgt.jpg


Die DataBaseHelper Klasse sieht wie folgt aus:

Code:
package com.example.studyguide;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper{
	
	//The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.example.studyguide/databases/";
 
    private static String DB_NAME = "studyDB";
 
    private SQLiteDatabase myDataBase; 
 
    private final Context myContext;
 
    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DataBaseHelper(Context context) {
 
    	super(context, DB_NAME, null, 1);
        this.myContext = context;
    }	
 

    /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{
 
    	boolean dbExist = checkDataBase();
 
    	if(dbExist){
    		//do nothing - database already exist
    	}else{
 
    		//By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
        	this.getReadableDatabase();
 
        	try {
 
    			copyDataBase();
 
    		} catch (IOException e) {
 
        		throw new Error("Error copying database");
 
        	}
    	}
 
    }
 
    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){
 
    	SQLiteDatabase checkDB = null;
 
    	try{
    		String myPath = DB_PATH + DB_NAME;
    		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
 
    	}catch(SQLiteException e){
 
    		//database does't exist yet.
 
    	}
 
    	if(checkDB != null){
 
    		checkDB.close();
 
    	}
 
    	return checkDB != null ? true : false;
    }
 
    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{
 
    	//Open your local db as the input stream
    	InputStream myInput = myContext.getAssets().open(DB_NAME);
 
    	// Path to the just created empty db
    	String outFileName = DB_PATH + DB_NAME;
 
    	//Open the empty db as the output stream
    	OutputStream myOutput = new FileOutputStream(outFileName);
 
    	//transfer bytes from the inputfile to the outputfile
    	byte[] buffer = new byte[1024];
    	int length;
    	while ((length = myInput.read(buffer))>0){
    		myOutput.write(buffer, 0, length);
    	}
 
    	//Close the streams
    	myOutput.flush();
    	myOutput.close();
    	myInput.close();
 
    }
 
    public void openDataBase() throws SQLException{
 
    	//Open the database
        String myPath = DB_PATH + DB_NAME;
    	myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
 
    }
 
    @Override
	public synchronized void close() {
 
    	    if(myDataBase != null)
    		    myDataBase.close();
 
    	    super.close();
 
	}
 
	@Override
	public void onCreate(SQLiteDatabase db) {
 
	}
 
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
	}

 
        // Add your public helper methods to access and get content from the database.
       // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
       // to you to create adapters for your views.
}

Die Klasse wo die Servicestellen als ListView angezeigt werden sollen sieht wie folgt aus:
Code:
package com.example.studyguide;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class serviceStellen extends Activity{

	DataBaseHelper myDb;
	SQLiteDatabase sqliteDB = myDb.getReadableDatabase();
	
	@SuppressLint("NewApi")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.servicestellen);
		
		openDB();
			
		TextView titel = (TextView) findViewById(R.id.textViewService);
		titel.setText(myDb.getDatabaseName());
		
		populateListView();	
		
	}

	protected void onDestroy(){
		super.onDestroy();
		closeDB();
	}
	
	private void openDB(){
		myDb = new DataBaseHelper(this);
		myDb.openDataBase();
	}
	
	private void closeDB(){
		myDb.close();
	}
		
	private void populateListView()
	{
		// Create list of items
		String[] myItems = this.getResources().getStringArray(R.array.mainArray);
		//String[] serviceArray = myDb.;
		
		// Build Adapter
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
																this, 					// Context for the activity
																R.layout.main_items, 	// Layout to use (create)
																myItems);				// Items to be displayed
		
		// Configure the list view
		ListView list = (ListView) findViewById(R.id.mainlist);
		list.setAdapter(adapter);
	}

	private void registerClickCallback()
	{
		final ListView list = (ListView) findViewById(R.id.mainlist);
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() 
			{
				@Override
				public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id)
				{
				    switch( position )
				    {
				       case 0:  Intent serviceStellenActivity = new Intent();
				       			serviceStellenActivity.setClassName(getPackageName(),getPackageName()+".serviceStellen");
				       			serviceStellenActivity.putExtra("selected",list.getAdapter().getItem(position).toString());
				                startActivity(serviceStellenActivity);
				                break;
				    }
					TextView textView = (TextView) viewClicked;
				}
			});
	}
	
	
}

Das Layout für Servicestellen:
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background" >

    <TextView
        android:id="@+id/textViewService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/textView1"
        android:text="TextView"
        android:textColor="@color/WhiteSmoke" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Name der Datenbank: "
        android:textColor="@color/WhiteSmoke" />

    <ListView
        android:id="@+id/listViewServiceStellen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textViewService" >

    </ListView>

</RelativeLayout>


Vielen Dank schon mal an alle die sich meinem Problem annehmen,
ich weiß einfach nicht mehr weiter.
Vielleicht habe ich auch einfach eine ganz falsche Herangehensweise an das Problem.
 
Zuletzt bearbeitet:
Hast Du von den 5 Leuten die Erlaubnis, deren Daten hier einzustellen?
 
COleException schrieb:
Hast Du von den 5 Leuten die Erlaubnis, deren Daten hier einzustellen?

Danke für den Hinweis, ich habs mal editiert. Sollte aber kein Problem sein da diese Daten für jeden öffentlich zugänglich auf der Seite der Hochschule sind.

Vielleicht eine Idee was mein Problem angeht?
 
Ich hab das bei mir so gelöst:

Meine DBAdapter Activity für die Datenbank
Code:
public class DBAdapter{
    
        public static final String KEY_ROWID = "kunde_id"; // vortlaufende nummer in der tabelle
        public static final String KEY_VORNAME = "vorname";
        public static final String KEY_NACHNAME = "nachname";
        public static final String KEY_ORT = "ort";
        public static final String KEY_STRASSE = "strasse";
        public static final String KEY_TELEFON = "telefon";
        private static final String TAG = "DBAdapter";

 private static final String DATABASE_NAME = "Kunde";
        private static final String DATABASE_TABLE = "Kundenstamm";
        private static final int DATABASE_VERSION = 1;

        private static final String DATABASE_CREATE = 
                "create table " + DATABASE_TABLE + " ("+ KEY_ROWID +" integer primary key autoincrement, "
                  +KEY_VORNAME+" varchar(255), "+KEY_NACHNAME+" varchar(255), "
                        + KEY_ORT +" varchar(255), "+KEY_TELEFON+" varchar(255), "+KEY_STRASSE+" varchar(255));";

 private final Context context; 
        
        private DatabaseHelper DBHelper;
        private SQLiteDatabase db;

        public DBAdapter(Context ctx) 
        {
            this.context = ctx;
            DBHelper = new DatabaseHelper(context);
        }
            
        private static class DatabaseHelper extends SQLiteOpenHelper 
        {
            DatabaseHelper(Context context) 
            {
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }

            @Override
            public void onCreate(SQLiteDatabase db) 
            {
                db.execSQL(DATABASE_CREATE);
}
 @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, 
            int newVersion) 
            {
                Log.w(TAG, "Upgrading database from version " + oldVersion 
                        + " to "
                        + newVersion + ", which will destroy all old data");
                db.execSQL("DROP TABLE IF EXISTS titles");
                onCreate(db);
            }
        }    
        
        //---opens the database---
        public DBAdapter open() throws SQLException 
        {
            db = DBHelper.getWritableDatabase();
            return this;
        }

        //---closes the database---    
        public void close() 
        {
            DBHelper.close();
        }
        
        
        //---insert a kunde into the database---
        public long insertKunde(String vorname, String nachname, String ort, String strasse, String telefon) 
        {
            ContentValues initialValues = new ContentValues();
            initialValues.put(KEY_VORNAME, vorname);
            initialValues.put(KEY_NACHNAME, nachname);
            initialValues.put(KEY_ORT, ort);
            initialValues.put(KEY_STRASSE, strasse);
            initialValues.put(KEY_TELEFON, telefon);
            return db.insert(DATABASE_TABLE, null, initialValues);
        }
 //---deletes a  kunde---
        public boolean deleteKunde(long rowId) 
        {
            return db.delete(DATABASE_TABLE, KEY_ROWID + 
                    "=" + rowId, null) > 0;
        }

//---retrieves all the kunden---
        public List<Kunde> getAllKunde() 
        {
            List<Kunde> Kunden = new ArrayList<Kunde>();
            Cursor cursor =  db.query(DATABASE_TABLE, new String[] {
                    KEY_ROWID, 
                    KEY_VORNAME,
                    KEY_NACHNAME,
                    KEY_ORT,
                    KEY_STRASSE,
                    KEY_TELEFON}, 
                    null, 
                    null, 
                    null, 
                    null, 
                    KEY_NACHNAME);
            cursor.moveToFirst();
            while(!cursor.isAfterLast()){
                Kunde kunde = cursortokunde(cursor);
            Kunden.add(kunde);
            cursor.moveToNext();
            }
        cursor.close();
        return Kunden;
    
        }
        private Kunde cursortokunde(Cursor c){
            Kunde kunde = new Kunde();
            kunde.setKundeId(c.getInt(0));
            kunde.setvorname(c.getString(1));
            kunde.setnachname(c.getString(2));
            kunde.setort(c.getString(3));
            kunde.setstrasse(c.getString(4));
            kunde.settelefon(c.getString(5));
                  
            
            return kunde;
            
        }
//---retrieves a particular Kunde---
        public Cursor getKunde(long rowId) throws SQLException 
        {
            Cursor mCursor =
                    db.query(true, DATABASE_TABLE, new String[] {
                            KEY_ROWID,
                            KEY_VORNAME, 
                            KEY_NACHNAME,
                            KEY_ORT,
                            KEY_STRASSE,
                            KEY_TELEFON}, 
                            KEY_ROWID + "=" + rowId, 
                            null,
                            null, 
                            null, 
                            null, 
                            null);
            if (mCursor != null) {
                mCursor.moveToFirst();
            }
            return mCursor;
        }
 //---updates a kunde---
        public boolean updateKunde(long rowId, String vorname, 
        String nachname, String ort, String strasse, String telefon) 
        {
            ContentValues args = new ContentValues();
            args.put(KEY_VORNAME, vorname);
            args.put(KEY_NACHNAME, nachname);
            args.put(KEY_ORT, ort);
            args.put(KEY_STRASSE, strasse);
            args.put(KEY_TELEFON, telefon);
            return db.update(DATABASE_TABLE, args, 
                             KEY_ROWID + "=" + rowId, null) > 0;
        }
Meine MainActivity mit einer Listview wo pro eintrag in der ListView 3 Zeilen sind ( Vorname, Nachname;
Ort, Strasse;
Telefonnummer)
plus ein kleines bildchen davor ;)

Hier meine MAIN ACTIVITY:
Code:
public class MainActivity extends Activity {
    
        ListView list;
        private DBAdapter db;
         
        
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
     
   db = new DBAdapter(this);
   db.open();
   
   
   List<Kunde> kunden = db.getAllKunde();
   list = (ListView)findViewById(R.id.listViewStamm);
   registerForContextMenu(getListView());
   list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       
       
    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
       
         TextView txt = (TextView)view.findViewById(R.id.txt_list_kunde_id);
         
         Intent intent = new Intent(MainActivity.this, KesselActivity.class);
         intent.putExtra("id", txt.getText().toString());
         startActivity(intent);
    }
       
   });
   KundeListViewAdapter kundeadapter = new KundeListViewAdapter(this, R.layout.kunden_datensatz, kunden);
   list.setAdapter(kundeadapter); 
    
    }
    
    
  

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }
      
        
    }
    
    
@Override
protected void onResume(){
    db.open();
    super.onResume();
}
@Override
protected void onPause(){
    db.close();
    super.onPause();
}

}
Hier noch die Activity um " neue Kunden einzutragen" . Hier hab ich noch drinnen, dass in jedem textView was drinnen stehen muss! ansonst kommt ein TOAST mit einer fehlermeldung.
Code:
public class NeuerKundeActivity extends Activity{
    Button neuerkunde;
    EditText txtVorname, txtNachname, txtOrt, txtStrasse, txtTelefon;
    DBAdapter db;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.neuerkunde);
                   
        
        db = new DBAdapter(getBaseContext());
        db.open();
                
        txtVorname   =   (EditText)findViewById(R.id.txtVorname);
        txtNachname  =   (EditText)findViewById(R.id.txtNachname);
        txtOrt       =   (EditText)findViewById(R.id.txtOrt);
        txtStrasse   =   (EditText)findViewById(R.id.txtStrasse);
        txtTelefon   =   (EditText)findViewById(R.id.txtTelefon);
            
        neuerkunde = (Button)findViewById(R.id.btn_neuerkunde);
        neuerkunde.setOnClickListener(new View.OnClickListener() {
            
            
            
            
            @Override
            public void onClick(View v) {
                if (!txtVorname.getText().toString().equals("") &&
                    !txtNachname.getText().toString().equals("") &&
                    !txtOrt.getText().toString().equals("") &&
                    !txtStrasse.getText().toString().equals("") &&
                    !txtTelefon.getText().toString().equals(""))  
                {                    
                    long kunde_id = db.insertKunde(txtVorname.getText().toString(), 
                                      txtNachname.getText().toString(), 
                                      txtOrt.getText().toString(), 
                                      txtStrasse.getText().toString(),
                                      txtTelefon.getText().toString());
                    
                    Intent intent = new Intent(NeuerKundeActivity.this, KesselActivity.class);
                    intent.putExtra("id", String.valueOf(kunde_id));
                    startActivity(intent);
                    Toast.makeText(getBaseContext(), "Daten gespeichert", Toast.LENGTH_LONG).show();
                } else  {
                    Toast.makeText(getBaseContext(), "Fehler: Es wurden nicht alle Felder ausgefüllt!", Toast.LENGTH_LONG).show();
                }
            }
        });
    
    }
        protected void onClose() {
        db.close();    
    }
    
}
und hier die layouts für die ListView:

Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="top"
    android:orientation="vertical"
    tools:context=".MainActivity" >

  

        <ListView
            android:id="@+id/listViewStamm"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="top">
        
    </ListView>


</LinearLayout>
und das layout für die 3-zeilen-listView:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:background="#000000"
    android:gravity="right"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="20sp"
        android:src="@drawable/zahnrad2"
        android:contentDescription="@string/nein"/>
    
    <TextView
            android:id="@+id/txt_list_kunde_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20sp"
            android:textColorHint="#99CC66"
            android:textStyle="italic"
            android:textColor="#FFFFFF"
            android:textSize="20sp" 
            android:visibility="gone"/>
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000000"
        android:gravity="center"
        android:orientation="vertical" >
    
    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center|fill" >

        <TextView
            android:id="@+id/txt_list_kundename"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20sp"
            android:textColor="#FFFFFF"
            android:textColorHighlight="#99CC66"
            android:textSize="30sp" />

    </TableRow>
    
    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/txt_list_kundeadresse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20sp"
            android:textColorHighlight="#99CC66"
            android:textColor="#FFFFFF"
            android:textSize="20sp" />

    </TableRow>
    
    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/txt_list_kundetelefon"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20sp"
            android:textColorHint="#99CC66"
            android:textStyle="italic"
            android:textColor="#FFFFFF"
            android:textSize="20sp" />

    </TableRow>
    </LinearLayout>
</LinearLayout>
So ich hoffe ich habe keinen fehler bei COPY&PASTE gemacht (da meine datenbank ein bisschen umfangreicher ist ):confused2:
eventuell kannst du von dem wirr-warr hier was verwenden ;))))
viel spass beim lesen.
 
Astarte schrieb:
Ich hab das bei mir so gelöst:

So ich hoffe ich habe keinen fehler bei COPY&PASTE gemacht (da meine datenbank ein bisschen umfangreicher ist ):confused2:
eventuell kannst du von dem wirr-warr hier was verwenden ;))))
viel spass beim lesen.

Vielen Dank fürs Posten, ich werde das heute Abend oder morgen früh mal durcharbeiten. :smile:
 
Eine generelle Frage hätte ich auch noch zum Thema SQLite, und zwar habe ich eine vorbereitete DB in der 5 Tabellen sind (android_metadata und 4 weitere die ich befüllt habe)
Mein Problem ist allerdings das die App immer abstürzt mit der Begründung (LogCat) das es die anderen Tabellen nicht geben würde, die einzige Tabelle die ich mir ausgeben lassen kann ist die android_metadata.
Gibt es eine bestimmte Norm wie die Tabellennamen definiert werden müssen?
Die ersten Spalten der PKs habe ich mit _id benannt.
Trotzdem kann ich auf keine der anderen 4 Tabellen zugreifen.
Weiß da jemand etwas genaueres zu?
 
kannst du den code mal posten? dann kann ich eventuell den fehler finden
 
Hier ist die DataBaseManager Klasse, ich habe allerdings auch direkt über ein SQLiteDatabase Objekt versucht drauf zuzugreifen.
Klappt ja auch soweit nur das er halt die anderen Tabellen nicht findet.
Ich habe es jetzt mit Objekten gelöst, aber finde ich schade weil genau für diesen Anwendungszweck ist ja eine Datenbank bestens geeignet.

Code:
package com.example.studyguide;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
 
 
public class DataBaseManager extends SQLiteOpenHelper {
 
    // The Android's default system path of the application database.
    //data/data/ and /databases remain the same always. The one that must be changed is com.example which represents
    //the MAIN package of the project
    private static String DB_PATH = "/data/data/com.example.studyguide/databases/";
 
    //the name of the database
    private static String DB_NAME = "studyDB";
 
    private static SQLiteDatabase mDataBase;
 
    private static DataBaseManager sInstance = null;
    // database version    
    private static final int DATABASE_VERSION = 1;
    
    /**
     * Constructor Takes and keeps a reference of the passed context in order to
     * access to the application assets and resources.
     */
    private DataBaseManager() {
        super(ApplicationContextProvider.getContext(), DB_NAME, null, DATABASE_VERSION);
 
        try {
            createDataBase();
            openDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
    /**
     * Singleton for DataBase
     *
     * @return singleton instance
     */
    public static DataBaseManager instance() {
 
        if (sInstance == null) {
            sInstance = new DataBaseManager();
        }
        return sInstance;
    }
 
 
    /**
     * Creates a empty database on the system and rewrites it with the own
     * database.
     *
     * @throws java.io.IOException io exception
     */
    private void createDataBase() throws IOException {
 
        boolean dbExist = checkDataBase();
 
        if (dbExist) {
            // do nothing - database already exist
        } else {
 
            // By calling this method an empty database will be created into
            // the default system path
            // of the application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();
 
            try {
 
                copyDataBase();
 
            } catch (IOException e) {
 
                throw new Error("Error copying database");
            }
        }
    }
 
    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
 
        SQLiteDatabase checkDB = null;
 
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);
 
        } catch (SQLiteException e) {
 
            // database doesn't exist yet.
 
        }
 
        if (checkDB != null) {
 
            checkDB.close();
 
        }
 
        return checkDB != null;
    }
 
    /**
     * Copies the database from the local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     *
     * @throws java.io.IOException io exception
     */
    public void copyDataBase() throws IOException {
 
        // Open the local db as the input stream
        InputStream myInput = ApplicationContextProvider.getContext().getAssets().open(DB_NAME);
 
        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;
 
        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);
 
        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
 
        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
 
    }
 
    public void openDataBase() throws SQLException {
 
        // Open the database
        String myPath = DB_PATH + DB_NAME;
        mDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }
 
    /**
     * Select method
     *
     * @param query select query
     * @return - Cursor with the results
     * @throws android.database.SQLException sql exception
     */
    public Cursor select(String query) throws SQLException {
        return mDataBase.rawQuery(query, null);
    }
 
 
    /**
     * Let you make a raw query
     *
     * @param command - the sql comand you want to run
     */
    public void sqlCommand(String command) {
        mDataBase.execSQL(command);
    }
    
    
    /**
     * Let you select the content from the specific table
     * The data gets 'converted' from an ArrayList to a StringArray
     * Returns the result
     **/
    public String[] getServicestellen(){
        
        Cursor c = mDataBase.rawQuery("SELECT name FROM Servicestellen" ,null);
        
        ArrayList<String> list = new ArrayList<String>();   
          
        String SpaltenName = "name";
            if (c.moveToFirst())
            {
                do
                {
                    String s = c.getString(c.getColumnIndex(SpaltenName));
                    list.add(s);
                }
                while (c.moveToNext());
            }
            
            if (c != null && !c.isClosed())
            {
                c.close();
            }
            
            String[] result = new String[list.size()];
            result = list.toArray(result);
            
            return result;
    }
 
    @Override
    public synchronized void close() {
 
        if (mDataBase != null)
            mDataBase.close();
 
        super.close();
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
 
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
    }
}
 

Ähnliche Themen

D
Antworten
8
Aufrufe
754
jogimuc
J
Zurück
Oben Unten