samedi 16 avril 2016

How to get image saved in drawable folder to database in SQLite using JAVA / Android Studio

I would like to display a dynamic images of "football stadiums" for my "football app." The images are saved in the drawable folder and I have created an attribute to attempt to reference the images. I am completely lost on the best approach to this, hence the amount of code I have posted. Even if I could reference image URLS instead this would be a lot of help. Many thanks in advance

StadiumSQLiteHelper.java

package com.example.dermot.sqliteexample4;


import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class StadiumSQLiteHelper extends SQLiteOpenHelper {
    // database version
    private static final int database_VERSION = 1;
    // database name
    private static final String database_NAME = "BookDB";
    private static final String table_BOOKS = "books";
    private static final String book_ID = "id";
    private static final String book_TITLE = "stadium_name";
    private static final String book_AUTHOR = "stadium_city";
    private static final String book_CAPACITY = "stadium_capacity";
    private static final String book_YEAR = "stadium_year";
    private static final String book_IMAGE = "stadium_image";
    private static final String book_GPS = "stadium_gps";
    private static final String[] COLUMNS = { book_ID, book_TITLE, book_AUTHOR, book_CAPACITY, book_YEAR, book_IMAGE, book_GPS };
    public StadiumSQLiteHelper(Context context) {
        super(context, database_NAME, null, database_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // SQL statement to create book table
        String CREATE_BOOK_TABLE = "CREATE TABLE books ( " + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "stadium_name TEXT, " + "stadium_city TEXT, "
                + "stadium_capacity TEXT, " + "stadium_year TEXT, " + "stadium_image BLOB, " + "stadium_gps TEXT )";
        db.execSQL(CREATE_BOOK_TABLE);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // drop books table if already exists
        db.execSQL("DROP TABLE IF EXISTS books");
        this.onCreate(db);
    }
    public void createBook(Stadium stadium) {
        // get reference of the BookDB database
        SQLiteDatabase db = this.getWritableDatabase();
        // make values to be inserted
        ContentValues values = new ContentValues();
        values.put(book_TITLE, stadium.getStadium_name());
        values.put(book_AUTHOR, stadium.getStadium_city());
        values.put(book_CAPACITY, stadium.getStadium_capacity());
        values.put(book_YEAR, stadium.getStadium_year());
        values.put(book_IMAGE, stadium.getStadium_image());
        values.put(book_GPS, stadium.getStadium_gps());
        // insert stadium
        db.insert(table_BOOKS, null, values);
        // close database transaction
        db.close();
    }

    public Stadium readBook(int id) {
        // get reference of the BookDB database
        SQLiteDatabase db = this.getReadableDatabase();
        // get stadium query
        Cursor cursor = db.query(table_BOOKS, // a. table
                COLUMNS, " id = ?", new String[] { String.valueOf(id) }, null, null,
                null, null);
        // if results !=null, parse the first one
        if (cursor != null)
            cursor.moveToFirst();
        Stadium stadium = new Stadium();
        stadium.setId(Integer.parseInt(cursor.getString(0)));
        stadium.setStadium_name(cursor.getString(1));
        stadium.setStadium_city(cursor.getString(2));
        stadium.setStadium_capacity(cursor.getString(3));
        stadium.setStadium_year(cursor.getString(4));
        stadium.setStadium_image(cursor.getString(5));
        stadium.setStadium_gps(cursor.getString(6));

        return stadium;
    }
    public List getAllBooks() {
        List books = new LinkedList();
        // select stadium query
        String query = "SELECT * FROM " + table_BOOKS;
        // get reference of the BookDB database
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query, null);
        // parse all results
        Stadium stadium = null;
        if (cursor.moveToFirst()) {
            do {
                stadium = new Stadium();
                stadium.setId(Integer.parseInt(cursor.getString(0)));
                stadium.setStadium_name(cursor.getString(1));
                stadium.setStadium_city(cursor.getString(2));
                stadium.setStadium_capacity(cursor.getString(3));
                stadium.setStadium_year(cursor.getString(4));
                stadium.setStadium_image(cursor.getString(5));
                stadium.setStadium_gps(cursor.getString(6));
                // Add stadium to books
                books.add(stadium);
            } while (cursor.moveToNext());
        }
        return books;
    }
    public int updateBook(Stadium stadium) {
        // get reference of the BookDB database
        SQLiteDatabase db = this.getWritableDatabase();
        // make values to be inserted
        ContentValues values = new ContentValues();
        values.put("stadium_name", stadium.getStadium_name()); // get stadium_name
        values.put("stadium_city", stadium.getStadium_city()); // get stadium_city
        values.put("stadium_capacity", stadium.getStadium_capacity()); // get stadium_city
        values.put("stadium_year", stadium.getStadium_year()); // get stadium_city
        values.put("stadium_image", stadium.getStadium_image()); // get stadium_city
        values.put("stadium_gps", stadium.getStadium_gps()); // get stadium_city

        // update
        int i = db.update(table_BOOKS, values, book_ID + " = ?", new String[] {
                String.valueOf(stadium.getId()) });
        db.close();
        return i;
    }
    // Deleting single stadium
    public void deleteBook(Stadium stadium) {
        // get reference of the BookDB database
        SQLiteDatabase db = this.getWritableDatabase();
        // delete stadium
        db.delete(table_BOOKS, book_ID + " = ?", new String[] {
                String.valueOf(stadium.getId()) });
        db.close();
    }
}

Stadium.Java

public class Stadium {
    private int id;
    private String stadium_name;
    private String stadium_city;
    private String stadium_capacity;
    private String stadium_year;
    private String stadium_image;
    private String stadium_gps;

    public Stadium(){}
    public Stadium(String stadium_name, String stadium_city, String stadium_capacity, String stadium_year, String stadium_image, String stadium_gps) {
        super();
        this.stadium_name = stadium_name;
        this.stadium_city = stadium_city;
        this.stadium_capacity = stadium_capacity;
        this.stadium_year = stadium_year;
        this.stadium_image = stadium_image;
        this.stadium_gps = stadium_gps;

    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public String getStadium_name() {
        return stadium_name;
    }
    public void setStadium_name(String stadium_name) {
        this.stadium_name = stadium_name;
    }

    public String getStadium_city() {
        return stadium_city;
    }
    public void setStadium_city(String stadium_city) {
        this.stadium_city = stadium_city;
    }

    public String getStadium_capacity() {
        return stadium_capacity;
    }
    public void setStadium_capacity(String stadium_capacity) {
        this.stadium_capacity = stadium_capacity;
    }

    public String getStadium_year() {
        return stadium_year;
    }
    public void setStadium_year(String stadium_year) {
        this.stadium_year = stadium_year;
    }

    public String getStadium_image() {
        return stadium_image;
    }
    public void setStadium_image(String stadium_image) {
        this.stadium_image = stadium_image;
    }

    public String getStadium_gps() {
        return stadium_gps;
    }
    public void setStadium_gps(String stadium_gps) {
        this.stadium_gps = stadium_gps;
    }

    @Override
    public String toString() {
        return "Stadium [id=" + id + ", stadium_name=" + stadium_name + ", stadium_city=" + stadium_city
                + ", stadium_capacity=" + stadium_capacity + ", stadium_year" + stadium_year + "stadium_image" + stadium_image + "stadium_gps" + stadium_gps + "]";
    }
}

StadiumActivity.Java

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.widget.TextView;
    import android.widget.ImageView;

    public class StadiumActivity extends Activity {
        TextView stadium_name;
        TextView stadium_city;
        TextView stadium_capacity;
        TextView stadium_year;
        Stadium selectedStadium;
        StadiumSQLiteHelper db;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_stadiumdetails);
            stadium_name = (TextView) findViewById(R.id.stadium_name);
            stadium_city = (TextView) findViewById(R.id.stadium_city);
            stadium_capacity = (TextView) findViewById(R.id.stadium_capacity);
            stadium_year = (TextView) findViewById(R.id.stadium_year);
            // get the intent that we have passed from AndroidDatabaseExample
            Intent intent = getIntent();
            int id = intent.getIntExtra("book", -1);
            // open the database of the application context
            db = new StadiumSQLiteHelper(getApplicationContext());

            // read the book with "id" from the database
            selectedStadium = db.readBook(id);
            initializeViews();
        }
        public void initializeViews() {
            stadium_name.setText(selectedStadium.getStadium_name());
            stadium_city.setText(selectedStadium.getStadium_city());
            stadium_capacity.setText(selectedStadium.getStadium_capacity());
            stadium_year.setText(selectedStadium.getStadium_year());
        }
    }

StadiumListActivity.Java
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;

public class StadiumListActivity extends ListActivity implements OnItemClickListener {
    StadiumSQLiteHelper db = new StadiumSQLiteHelper(this);
    List<Stadium> list;
    List<String> listTitle;
    ArrayAdapter myAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stadiumlist);
        // drop this database if already exists

        db.onUpgrade(db.getWritableDatabase(), 1, 2);
        db.createBook(new Stadium("Stade de France", "Saint-Denis", "80000", "1998", "drawable1.jpg", "48,924438 ,2.360186"));
        db.createBook(new Stadium("Stade Velodrome", "Marseille", "67000", "1937", "drawable2.jpg", "48,924438 ,2.360186"));
        db.createBook(new Stadium("Stade de Lyon", "Lyon", "59000", "2015", "drawable3.jpg", "48,924438 ,2.360186"));
        db.createBook(new Stadium("Stade Pierre Mauroy", "Lille", "50000", "2012", "drawable4.jpg", "48,924438 ,2.360186"));
        db.createBook(new Stadium("Parc des Princes", "Paris", "45000", "1972", "drawable5.jpg", "48,924438 ,2.360186"));
        db.createBook(new Stadium("Stade de Bordeaux", "Bordeaux", "42000", "2015", "drawable6.jpg", "48,924438 ,2.360186"));
        db.createBook(new Stadium("Stade Geoffroy-Guichard", "Saint-Etienne", "42000", "1931", "drawable7.jpg", "48,924438 ,2.360186"));
        db.createBook(new Stadium("Stade de Nice", "Nice", "35000", "2013", "drawable8.jpg", "48,924438 ,2.360186"));
        db.createBook(new Stadium("Stade Bollaert-Delelis", "Lens", "35000", "1933", "drawable9.jpg", "48,924438 ,2.360186"));
        db.createBook(new Stadium("Stadium de Toulouse","Toulouse", "33000", "1937", "drawable10.jpg", "48,924438 ,2.360186"));
        // get all books
        list = db.getAllBooks();
        List<String> listTitle = new ArrayList<String>();
        for (int i = 0; i < db.getAllBooks().size(); i++) {
            listTitle.add(i, list.get(i).getStadium_name());
        }
        myAdapter = new ArrayAdapter(this, R.layout.row_layout, R.id.listText,
                listTitle);
        getListView().setOnItemClickListener(this);
        setListAdapter(myAdapter);
    }
    @Override
    public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
        // start StadiumActivity with extras the book id
        Intent intent = new Intent(this, StadiumActivity.class);
        intent.putExtra("book", list.get(arg2).getId());
        startActivityForResult(intent, 1);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // get all books again, because something changed
        list = db.getAllBooks();
        List<String> listTitle2 = new ArrayList<String>();

        for (int i = 0; i < list.size(); i++) {
            listTitle2.add(i, list.get(i).getStadium_name());
        }
        myAdapter = new ArrayAdapter(this, R.layout.row_layout, R.id.listText,
                listTitle2);
        getListView().setOnItemClickListener(this);
        setListAdapter(myAdapter);
    }
}

activity_stadiumdetails.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="25dp"
    android:weightSum="1">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="5dp" >

        <TextView
            android:id="@+id/stadium_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="32dp"
            android:fontFamily="sans-serif-thin"
            android:textStyle="bold"
            android:text="Stadium Name:"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

    <ImageView
        android:id="@+id/imgIcon"
        android:layout_width="334dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_weight="0.66" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="5dp" >

        <TextView
            android:id="@+id/stadium_city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Stadium City:"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="5dp" >

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="5dp" >

    </LinearLayout>

    <TextView
        android:id="@+id/capacityText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Capacity:"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/stadium_capacity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stadium Capacity:"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/yearText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Opening Year:"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/stadium_year"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Opening Year:"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Aucun commentaire:

Enregistrer un commentaire