Android aplikacija i baze podataka

Slides:



Advertisements
Similar presentations
Programming with Android: Data management
Advertisements

Programming with Android: Network Operations
SQLite is a software library. It is: self-contained + Serverless + zero-configuration transactional = SQL database engine. Most widely deployed. The source.
IPhone/Android & MySQL Hongsheng Lu CSE40333/ Spring University of Notre Dame.
Cosc 4730 Brief return Sockets And HttpClient And AsyncTask.
Android course Database dr Milan Vidaković Chair of Informatics Faculty of Technical Sciences University of Novi Sad.
CONTENT PROVIDER. Content Provider  A content provider makes a specific set of the application's data available to other applications => Share data to.
Cosc 5/4730 Android and Blackberry SQLite. For the sql language syntax, please see SQlite documentation –
SQLLite and Java CS-328 Dick Steflik. SQLLite Embedded RDBMS ACID Compliant Size – about 257 Kbytes Not a client/server architecture –Accessed via function.
Data Persistence in Android
SQLite Database. SQLite Public domain database – Advantages Small (about 150 KB) – Used on devices with limited resources Each database contained within.
HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Data Storage: Part 3 (SQLite)
Cosc 5/4730 Android Content Providers and Intents.
Data Storage: Part 4 (Content Providers). Content Providers Content providers allow the sharing of data between applications. Inter-process communication.
Package org.androidtown.database.query; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;
Purdue Pride Joe Gutierrez Tung Ho Janam Jhaveri 4/7/2010Purdue Pride1.
前置工作 1. 安裝 TomCat 2. 下載及安裝 AppServ exe 內含 Appache 2.2/Php5/MySQL 3. 修改相關參數檔 Appache 2.2/conf/ httpd.conf, workers.properties TomCat/conf/server.xml.
SQLite Android Club SQLite About onCreate Insert Select Update Delete onUpdate.
HTTP and Threads. Getting Data from the Web Believe it or not, Android apps are able to pull data from the web. Developers can download bitmaps and text.
Android Storage. There are several options for storage of data with Android We can put data into a preferences file. We can put data into a ‘normal’ file.
Address Book App 1. Define styles   Specify a background for a TextView – res/drawable/textview_border.xml.
Robolectric (version 2.4 기준 ). class AbcTest public static void setUpOnce() { public void public void testA()
UNIT 30 네트워크 전송 2 로봇 SW 콘텐츠 교육원 조용수.
Persistence Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.
SQLite (part deux) 1 CS440. Traditional Model View Controller (MVC) CS440 2.
Mobile Software Development ISCG 7424 Department of Computing UNITEC John Casey and Richard Rabeder SQLite and Permissions.
네트워크 전송 1/2 UNIT 29 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Android Network 통신 2.
SQLite DB Storing Data in Android RAVI GAURAV PANDEY 1.
SQlite. SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
1. Playing with SQLite Database  SQLite : Database specific name for Android Application  For windows there are several kind of database name : Mysql,
Address Book App 1 Fall 2014 CS7020: Game Design and Development.
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
Database Programming Code Dissection. Layered Approach Presentation (Activity) DbSampleActivity.java DataAccess (DataSource) CommentsDataSource.java MySQLiteHelper.java.
CS499 – Mobile Application Development
Making content providers
Data Storage: Part 3 (SQLite)
Cosc 5/4730 Sqlite primer.
Android Content Providers & SQLite
SQLite in Android Landon Cox March 2, 2017.
Mobile Software Development for Android - I397
Mobile Application Development BSCS-7 Lecture # 18, 19
ListView: Part 2.
Android Application SQLite 1.
Reactive Android Development
Concurrency in Android
Android Database using SQLite
Android 4: Saving Data Kirk Scott.
Tashkent Weather ANDROID CLUB 2015.
RADE new features via JAVA
Android 18: Saving Data Kirk Scott.
Android Storage.
Mobile Computing With Android ACST Android Database Storage Part 2
Pristup podacima Uvod Nikola Vlahović.
null, true, and false are also reserved.
Introduction to Java Programming
CMPE419 Mobile Application Development
CMPE419 Mobile Application Development
JavaScript Reserved Words
Mobile Computing With Android ACST 4550 Android Database Storage
Android Developer Fundamentals V2
Module 2 - Part 1 Variables, Assignment, and Data Types
Android Developer Fundamentals V2
Making Text for the Web part 6
ListView A view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view. ListAdapter is used to.
Department of School of Computing and Engineering
SQLLite and Android.
plus content providers, loaders, recyclerview
程式範例 - Android String url = "
Presentation transcript:

Android aplikacija i baze podataka

Tipovi baza podataka Interna baza podataka – SQLite vidljive samo unutar aplikacije Eksterna baza podataka – MySQL nije moguć direktan pristup web servisi

Aplikacija SQLite baza vozača MySQL baza vozila

Aplikacija i SQLite baza podataka klasa Vozac.java – atributi id i ime klasa naslijeđena iz SQLiteOpenHelper kreiranje baze podataka DAO klasa - VozacDataSource uspostava konekcije pristup podacima

2) MySQLiteHelper public class MySQLiteHelper extends SQLiteOpenHelper { public static final String TABLE_VOZACI = "vozaci"; public static final String COLUMN_ID = "id"; public static final String COLUMN_IME = "ime"; private static final String DATABASE_NAME = "vozaci.db"; private static final int DATABASE_VERSION = 1; // iskaz za kreiranje baze private static final String DATABASE_CREATE = "create table " + TABLE_VOZACI + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_IME + " text not null);"; public MySQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase database) { database.execSQL(DATABASE_CREATE); public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(MySQLiteHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TABLE_VOZACI); onCreate(db);

3) VozacDataSource public class VozacDataSource { private SQLiteDatabase database; private MySQLiteHelper dbHelper; private String[] allColumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_IME }; public VozacDataSource(Context context) { dbHelper = new MySQLiteHelper(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); public void close() { dbHelper.close(); public Vozac createVozac(String v) { ContentValues values = new ContentValues(); values.put(MySQLiteHelper.COLUMN_IME, v); long insertId = database.insert(MySQLiteHelper.TABLE_VOZACI, null, values); Cursor cursor = database.query(MySQLiteHelper.TABLE_VOZACI, allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null, null, null, null); cursor.moveToFirst(); Vozac novi = cursorToVozac(cursor); cursor.close(); return novi; public void deleteVozac(Vozac v) { long id = v.getId(); database.delete(MySQLiteHelper.TABLE_VOZACI, MySQLiteHelper.COLUMN_ID + " = " + id, null); public boolean updateVozac(long l, String novo) { ContentValues args = new ContentValues(); args.put(MySQLiteHelper.COLUMN_IME, novo); return database.update(MySQLiteHelper.TABLE_VOZACI, args, MySQLiteHelper.COLUMN_ID + "=" + l, null) > 0; } public ArrayList<Vozac> getAll() { ArrayList<Vozac> svi = new ArrayList<Vozac>(); Cursor cursor = database.query(MySQLiteHelper.TABLE_VOZACI, allColumns, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Vozac v = cursorToVozac(cursor); svi.add(v); cursor.moveToNext(); cursor.close(); return svi; private Vozac cursorToVozac(Cursor cursor) { Vozac v = new Vozac(); v.setId(cursor.getLong(0)); v.setIme(cursor.getString(1)); return v;

Aplikacija i MySQL baza podataka koraci za uspostavu veze s eksternom bazom podataka kreirati MySQL bazu podataka baza: test tabela: vozila polja: broj (broj linije), linija (naziv linije) kreirati web servis za komunikaciju s bazom za svaku od operacija (preuzimanje, umetanje, brisanje, izmjena) naslijediti klasu AsyncTask unutar koje će se vršiti komunikacija omogućava izvršenje pozadinskih operacija i rezultat tih operacija prikazuje na UI niti

2) Web servis (vozila.php) function zag() { header("{$_SERVER['SERVER_PROTOCOL']} 200 OK"); header('Content-Type: text/html'); header('Access-Control-Allow-Origin: *'); } function rest_get($request, $data) { $veza = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', ''); $veza->exec("set names utf8"); $upit = $veza->prepare("SELECT * FROM vozila"); $upit->execute(); print "{ \"vozila\": " . json_encode($upit->fetchAll()) . "}"; function rest_post($request, $data) { $broj = $data["broj"]; $linija = $data["linija"]; $upit = $veza->prepare("INSERT INTO vozila SET broj = :broj, linija = :linija;"); $upit->bindValue(":broj", $broj, PDO::PARAM_INT); $upit->bindValue(":linija", $linija, PDO::PARAM_STR); function rest_delete($request) { $poz = strrpos($request, "="); $broj=intval(substr($request, $poz+1)); ?> $upit=$veza->prepare("delete from vozila where broj=:broj"); $upit->bindValue(":broj", $broj, PDO::PARAM_INT); $upit->execute(); } function rest_put($request, $data) { $broj = $data["broj"]; $linija = $data["linija"]; $veza = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', ''); $veza->exec("set names utf8"); $upit = $veza->prepare("UPDATE vozila SET linija = :linija WHERE broj = :broj;"); $upit->bindValue(":linija", $linija, PDO::PARAM_STR); function rest_error($request) { } $method = $_SERVER['REQUEST_METHOD']; $request = $_SERVER['REQUEST_URI']; switch($method) { case 'PUT': parse_str(file_get_contents('php://input'), $put_vars); zag(); $data = $put_vars; rest_put($request, $data); break; case 'POST': zag(); $data = $_POST; rest_post($request, $data); break; case 'GET': zag(); $data = $_GET; rest_get($request, $data); break; case 'DELETE': zag(); rest_delete($request); break; default: header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found"); rest_error($request); break; ?>

3a) UcitajVozila class UcitajVozila extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { HttpGet httpGet = new HttpGet("http://178.77.23.9/vozila.php"); try { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpGet);     return EntityUtils.toString(response.getEntity(), HTTP.UTF_8); } catch (Exception e) { e.printStackTrace(); return null; protected void onPostExecute(String response) { final JSONArray jsonObj = new JSONObject(response).getJSONArray("vozila"); vozila.clear(); for (int i = 0; i < jsonObj.length(); i++) { Vozilo vozilo = new Vozilo(); vozilo.setBrojVozila(jsonObj.getJSONObject(i).getInt("broj")); vozilo.setLinija(jsonObj.getJSONObject(i).getString("linija")); vozila.add(vozilo); osvjeziListu(); } catch (Exception e) {

3b) DodajVozilo class DodajVozilo extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String broj = params[0]; String linija = params[1]; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://178.77.23.9/vozila.php"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("broj", broj)); nameValuePairs.add(new BasicNameValuePair("linija", linija)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); Log.d("response", EntityUtils.toString(response.getEntity(), HTTP.UTF_8)); } catch (Exception e) { e.printStackTrace(); } return null; protected void onPostExecute(String response) { new UcitajVozila().execute();

3c) ObrisiVozilo class ObrisiVozilo extends AsyncTask<Vozilo, Void, String> { @Override protected String doInBackground(Vozilo... params) { Vozilo vozilo = params[0]; HttpClient httpclient = new DefaultHttpClient(); HttpDelete httpdelete = new HttpDelete("http://178.77.23.9/vozila.php?=" + String.valueOf(vozilo.getBrojVozila())); try { HttpResponse response = httpclient.execute(httpdelete); } catch (Exception e) { e.printStackTrace(); } return null; protected void onPostExecute(String response) { new UcitajVozila().execute();

3d) IzmijeniVozilo class IzmijeniVozilo extends AsyncTask<Vozilo, Void, String> { @Override protected String doInBackground(Vozilo... params) { Vozilo vozilo = params[0]; HttpPut httpPut = new HttpPut("http://178.77.23.9/vozila.php"); try { HttpClient httpclient = new DefaultHttpClient(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("broj", String.valueOf(vozilo.getBrojVozila()))); nameValuePairs.add(new BasicNameValuePair("linija", vozilo.getLinija())); httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httpPut); return EntityUtils.toString(response.getEntity(), HTTP.UTF_8); } catch (Exception e) { e.printStackTrace(); } return null; protected void onPostExecute(String response) { new UcitajVozila().execute();