Datenbank

S

Schräg

Neues Mitglied
0
Hallo zusammen,

für mein Studium schreibe ich grade an einer App zur Dokumentation von Mängeln. um die anfallenden Daten zu speichern möchte ich eine SQLite Datenbank verwenden. Vllt sollte ich an dieser Stelle noch sagen, das ich absoluter Anfänger bin ^^

Das Grundgerüst steht auch schon, wahrscheinlich nicht die sauberste Lösung, aber es läuft. Ich kann Projekte anlegen und der Projektname und die Projektnummer werden in einer Datenbank abgelegt.

Jetzt möchte ich aber Mängel einfügen und diese den einzelnen Projekten zuordnen. Weiß aber absolut nicht was ich tun muss, um das zu realisieren.

schonmal vielen Dank
Code:
---------MainActivity---------

package com.example.maengel_dokumentation;

import java.util.ArrayList;
import java.util.List;

import com.example.maengel_dokumentation.klassen.DBAdapter;
import com.example.maengel_dokumentation.klassen.Projekt;
import com.example.maengel_dokumentation.klassen.ProjektZwischenspeicher;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
	//globale Variablen
	public static int DBcounter;
	public static String AktuellesProjekt;
	
	DBAdapter myDB;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//Einstellungen für die Menüleiste
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		//Einstellungen für die MenüleistenItems
		//nimmt Bezug auf res/menu/main.xml
		switch (item.getItemId()){
			case R.id.neues_projekt:
				startActivity(new Intent(MainActivity.this, NeuesProjektActivity.class));
				return true;
				
			case R.id.suche:
				//Suchfunktion implementieren
				Toast.makeText(this, "kommt noch", Toast.LENGTH_SHORT).show();
				return true;
		
			case R.id.ClearAll:
				myDB.deleteAll();
				populateListViewFromDB();
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//öffent die Datenbank
		openDB();
		
		//Fragt die Eingabe eines neuen Projektes ab
		//und trägt diese,falls vorhanden, in die DB 
		populateProjektListe();
		//Auswertung der DB und übertragen in Ansicht und ListView
		populateListViewFromDB();
		
		registerListClickCallback();
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		closeDB();
	}
	
	private void openDB() {
		myDB = new DBAdapter(this);
		myDB.open();		
	}
	
	private void closeDB() {
		myDB.close();		
	}
	
	private void populateProjektListe() {
		Intent projektIntent = getIntent();
		
		//Daten erhalten
		String name=projektIntent.getStringExtra("Eingabe1");
		String nummer=projektIntent.getStringExtra("Eingabe2");
		if (name == null){
			return;
		}
		if (nummer == null){
			return;
		}
		myDB.insertRow(name, nummer, R.drawable.fh_koeln, R.drawable.app_background_gedreht);
	}

	private void populateListViewFromDB() {

		Cursor cursor = myDB.getAllRows();
		
		//Erlaubt der Activity die Laufzeit des cursors zu beeinflussen
		//Runs on the UI thread, OK für kleiner Listen
		startManagingCursor(cursor);
		
		//Setup mapping from cursor to the view
		String[] fromFieldNames = new String[] {
			DBAdapter.KEY_PROJEKTNAME, DBAdapter.KEY_PROJEKTNUMMER, DBAdapter.KEY_PROJEKTIMAGE, DBAdapter.KEY_BACKIMAGE
		};	
		int[] toViewIDs = new int[]{
			R.id.lv_TextView_projekt_name, R.id.lv_TextView_projekt_nummer, R.id.lv_ImageView_projekt_Foto, R.id.lv_ImageView_projekt_back	
		};
		
		//Create adapter to may columns of the DB onto elements in the UI.
		SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, R.layout.lv_main_projekte,cursor,fromFieldNames,toViewIDs);
		
		//Set the adapter for the ListView
		ListView myList = (ListView) findViewById(R.id.main_listView);
		myList.setAdapter(myCursorAdapter);
	}
	
	private void registerListClickCallback() {
		ListView myList = (ListView) findViewById(R.id.main_listView);
		myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View viewClicked, int position,long idInDB){
				Cursor cursor = myDB.getRow(idInDB);
					if (cursor.moveToFirst()){
				
						String name = cursor.getString(DBAdapter.COL_PROJEKTNAME);
						//String nummer = cursor.getString(DBAdapter.COL_ROWID);
						
						String message = "Projekt: " + name;
						
						//Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
						
						DBcounter = cursor.getInt(DBAdapter.COL_ROWID);
						AktuellesProjekt = message;	
					
						Intent projektAnsichtIntent = new Intent (MainActivity.this, ProjektAnsichtActivity.class);
						
						startActivity(projektAnsichtIntent);
			
						cursor.close();
					}
						
				
			}
		});
		
	}	

}

---------Datenbank---------

package com.example.maengel_dokumentation.klassen;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
 

// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {

	/////////////////////////////////////////////////////////////////////
	//	Constants & Data
	/////////////////////////////////////////////////////////////////////
	// For logging:
	private static final String TAG = "DBAdapter";
	
	// DB Fields
	public static final String KEY_ROWID = "_id";
	public static final int COL_ROWID = 0;
	/*
	 * CHANGE 1:
	 */
	// TODO: Setup your fields here:
	public static final String KEY_PROJEKTNAME = "name";
	public static final String KEY_PROJEKTNUMMER = "projektNum";
	public static final String KEY_PROJEKTIMAGE = "projektImage";
	public static final String KEY_BACKIMAGE = "backImage";
	
	// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
	public static final int COL_PROJEKTNAME = 1;
	public static final int COL_PROJEKTNUMMER = 2;
	public static final int COL_PROJEKTIMAGE = 3;
	public static final int COL_BACKIMAGE = 4;

	
	public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_PROJEKTNAME, KEY_PROJEKTNUMMER, KEY_PROJEKTIMAGE, KEY_BACKIMAGE};
	
	// DB info: it's name, and the table we are using (just one).
	public static final String DATABASE_NAME = "MyDB"; //test: geändert von MyDb auf MyDB.
	public static final String DATABASE_TABLE = "mainTable";
	// Track DB version if a new version of your app changes the format.
	public static final int DATABASE_VERSION = 1;	
	
	private static final String DATABASE_CREATE_SQL = 
			"create table " + DATABASE_TABLE 
			+ " (" + KEY_ROWID + " integer primary key autoincrement, "
			
			/*
			 * CHANGE 2:
			 */
			// TODO: Place your fields here!
			// + KEY_{...} + " {type} not null"
			//	- Key is the column name you created above.
			//	- {type} is one of: text, integer, real, blob
			//		(http://www.sqlite.org/datatype3.html)
			//  - "not null" means it is a required field (must be given a value).
			// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
			+ KEY_PROJEKTNAME + " text not null, "
			+ KEY_PROJEKTNUMMER + " Text not null,"
			+ KEY_PROJEKTIMAGE + " integer not null,"
			+ KEY_BACKIMAGE + " integer not null"

			
			// Rest  of creation:
			+ ");";
	
	// Context of application who uses us.
	private final Context context;
	
	private DatabaseHelper myDBHelper;
	private SQLiteDatabase db;

	/////////////////////////////////////////////////////////////////////
	//	Public methods:
	/////////////////////////////////////////////////////////////////////
	
	public DBAdapter(Context ctx) {
		this.context = ctx;
		myDBHelper = new DatabaseHelper(context);
	}
	
	// Open the database connection.
	public DBAdapter open() {
		db = myDBHelper.getWritableDatabase();
		return this;
	}
	
	// Close the database connection.
	public void close() {
		myDBHelper.close();
	}
	
	// Add a new set of values to the database.
	public long insertRow(String name, String projektNum, int projektImage, int backImage) {
		/*
		 * CHANGE 3:
		 */		
		// TODO: Update data in the row with new fields.
		// TODO: Also change the function's arguments to be what you need!
		// Create row's data:
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_PROJEKTNAME, name);
		initialValues.put(KEY_PROJEKTNUMMER, projektNum);
		initialValues.put(KEY_PROJEKTIMAGE, projektImage);
		initialValues.put(KEY_BACKIMAGE, backImage);
		
		// Insert it into the database.
		return db.insert(DATABASE_TABLE, null, initialValues);
	}
	
	// Delete a row from the database, by rowId (primary key)
	public boolean deleteRow(long rowId) {
		String where = KEY_ROWID + "=" + rowId;
		return db.delete(DATABASE_TABLE, where, null) != 0;
	}
	
	public void deleteAll() {
		Cursor c = getAllRows();
		long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
		if (c.moveToFirst()) {
			do {
				deleteRow(c.getLong((int) rowId));				
			} while (c.moveToNext());
		}
		c.close();
	}
	
	// Return all data in the database.
	public Cursor getAllRows() {
		String where = null;
		Cursor c = 	db.query(true, DATABASE_TABLE, ALL_KEYS, 
							where, null, null, null, null, null);
		if (c != null) {
			c.moveToFirst();
		}
		return c;
	}

	// Get a specific row (by rowId)
	public Cursor getRow(long rowId) {
		String where = KEY_ROWID + "=" + rowId;
		Cursor c = 	db.query(true, DATABASE_TABLE, ALL_KEYS, 
						where, null, null, null, null, null);
		if (c != null) {
			c.moveToFirst();
		}
		return c;
	}
	
	// Change an existing row to be equal to new data.
	public boolean updateRow(long rowId, String name, String projektNum, int projektImage, int backImage) {
		String where = KEY_ROWID + "=" + rowId;

		/*
		 * CHANGE 4:
		 */
		// TODO: Update data in the row with new fields.
		// TODO: Also change the function's arguments to be what you need!
		// Create row's data:
		ContentValues newValues = new ContentValues();
		newValues.put(KEY_PROJEKTNAME, name);
		newValues.put(KEY_PROJEKTNUMMER, projektNum);
		newValues.put(KEY_PROJEKTIMAGE, projektImage);
		newValues.put(KEY_BACKIMAGE, backImage);

		
		// Insert it into the database.
		return db.update(DATABASE_TABLE, newValues, where, null) != 0;
	}
	
	
	
	/////////////////////////////////////////////////////////////////////
	//	Private Helper Classes:
	/////////////////////////////////////////////////////////////////////
	
	/**
	 * Private class which handles database creation and upgrading.
	 * Used to handle low-level database access.
	 */
	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_SQL);			
		}

		@Override
		public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading application's database from version " + oldVersion
					+ " to " + newVersion + ", which will destroy all old data!");
			
			// Destroy old database:
			_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			
			// Recreate new database:
			onCreate(_db);
		}
	}
}
 
Ich gaube das dürfte helfen ;) SQLite Foreign Key Support Cascade auch einstellen, damit die "Childs" auch gelöscht werden wenn "parent" gelöscht wird.
 
Zuletzt bearbeitet:

Ähnliche Themen

S
Antworten
33
Aufrufe
2.674
Sempervivum
S
S
  • softwareunkundig
Antworten
1
Aufrufe
886
jogimuc
J
Zurück
Oben Unten