Commit a8f9bef9 authored by Lucas NAURY's avatar Lucas NAURY

Add images in DB

parent 0d481251
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="jbr-17" project-jdk-type="JavaSDK">
......
......@@ -26,11 +26,11 @@ public class DBHelper extends SQLiteOpenHelper {
static final String DB_NAME = "LEBONCOIN.DB";
// database version
static final int DB_VERSION = 2;
static final int DB_VERSION = 3;
// Creating table query
private static final String CREATE_TABLE = "create table " + TABLE_NAME + "(" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + TITLE + " TEXT NOT NULL, " + ADDRESS + " TEXT, " + IMAGE + " TEXT, " + PRICE + " DOUBLE, " + DESCRIPTION + " TEXT);";
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + TITLE + " TEXT NOT NULL, " + ADDRESS + " TEXT, " + IMAGE + " BLOB, " + PRICE + " DOUBLE, " + DESCRIPTION + " TEXT);";
public DBHelper(Context context) {
super(context,
......@@ -64,12 +64,10 @@ public class DBHelper extends SQLiteOpenHelper {
String title = data.getString(data.getColumnIndexOrThrow(TITLE));
String address = data.getString(data.getColumnIndexOrThrow(ADDRESS));
String image = data.getString(data.getColumnIndexOrThrow(IMAGE));
byte[] image = data.getBlob(data.getColumnIndexOrThrow(IMAGE));
double price = data.getDouble(data.getColumnIndexOrThrow(PRICE));
String description = data.getString(data.getColumnIndexOrThrow(DESCRIPTION));
data.close();
return new Annonce(title, address, image, price, description);
}
}
......@@ -9,10 +9,16 @@ import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.example.tpleboncoin.R;
import com.example.tpleboncoin.models.Annonce;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
public class DBManager {
......@@ -24,7 +30,6 @@ public class DBManager {
private DBManager(Context c) {
context = c;
}
public static DBManager getDBManager(Context context) {
......@@ -34,14 +39,14 @@ public class DBManager {
return DBManager;
}
public DBManager open() throws SQLException {
public DBManager open(Context context) throws SQLException {
dbHelper = new DBHelper(context);
database = dbHelper.getWritableDatabase();
//S'il n'y a pas d'annonce, on initialise une liste d'annonces
Cursor cursor = fetch();
if(cursor != null && cursor.getCount() == 0){
init();
init(context);
}
return this;
......@@ -52,13 +57,25 @@ public class DBManager {
}
// Add ads manually.
public void init(){
insert(new Annonce("Wood", "Douai", "https://media.istockphoto.com/id/134253640/photo/construction-of-a-wooden-roof-frame-underway.jpg?s=612x612&w=0&k=20&c=e5gUkic9LGQWahIdHozOsEzHKy_HtsmvmtOHmYsejSU=",24.99, "High-quality seasoned firewood for sale! Perfect for cozy nights by the fireplace or powering your wood-burning stove. Our carefully selected wood is sourced sustainably, ensuring both quality and environmental responsibility. Available for delivery to your doorstep, our firewood is split and ready to use, saving you time and effort. Whether you're a homeowner, camper, or outdoor enthusiast, our firewood is ideal for all your needs. Stock up now and enjoy the warmth and ambiance of natural wood burning. Don't miss out on this opportunity to elevate your fire experience. Contact us today to place your order!"));
insert(new Annonce("Steel", "Lille", "https://as2.ftcdn.net/v2/jpg/03/91/83/87/1000_F_391838708_4HFADW5beay2VVlnoual6Qi5fWeIaD9V.jpg", 18.9, "Premium steel available for sale! Engineered for strength and durability, our high-grade steel is suitable for a wide range of applications. Whether you're a contractor, builder, or DIY enthusiast, our steel products are perfect for construction projects, fabrication, or repairs. With various sizes and shapes available, we cater to diverse needs and specifications. Our steel undergoes rigorous quality checks to ensure top-notch performance and reliability. Conveniently order online and have it delivered to your location. Upgrade your projects with our superior steel today. Contact us now to place your order and experience the difference!"));
insert(new Annonce("Clay", "Douai", "https://constrofacilitator.com/wp-content/uploads/2020/02/clay-in-construction.jpg", 7.88, "Quality clay for sale! Ideal for pottery, sculpting, and crafting projects, our premium-grade clay offers versatility and excellent molding properties. Sourced from reliable suppliers, our clay is carefully processed to ensure consistency and workability. Whether you're a professional artist or a hobbyist, our clay is perfect for bringing your creative visions to life. Available in various quantities, we cater to both small-scale and large-scale projects. Order online for convenient delivery to your doorstep. Elevate your crafting experience with our top-quality clay. Contact us today to place your order and unleash your artistic potential!"));
insert(new Annonce("Metal", "Lyon", "https://www.meto-constructions.fr/wp-content/uploads/2018/12/IMG_6067.jpg", 12.99, "Discover the perfect metal for your projects! Our high-quality metal is meticulously crafted to meet the demands of various industries and applications. Whether you're in construction, manufacturing, or metalworking, our premium-grade metal offers unparalleled strength, durability, and versatility. From stainless steel to aluminum and everything in between, we provide a wide range of metal options to suit your specific needs. Our metals are sourced from trusted suppliers and undergo rigorous quality checks to ensure superior performance. Conveniently order online and have it delivered to your location. Elevate your projects with our exceptional metal products. Contact us today to place your order and experience the difference!"));
insert(new Annonce("Glass", "Valenciennes", "https://i0.wp.com/www.tipsnepal.com/wp-content/uploads/2020/09/simple-float-glass-1505049573-3306125.jpeg?resize=500%2C317&quality=100&strip=all&ssl=1", 12.0, "Explore the brilliance of our premium glass products! Crafted with precision and quality in mind, our glass offerings are perfect for a variety of applications. Whether you're in need of durable windows for your home, sleek glass tabletops for your office, or intricate glassware for your dining table, we have you covered. Our extensive range includes tempered glass, laminated glass, decorative glass, and more, ensuring we meet your specific requirements. Sourced from trusted manufacturers, our glass products undergo stringent quality control measures to guarantee clarity, strength, and safety. Order online for hassle-free delivery to your desired location. Elevate your spaces with our exquisite glass solutions. Contact us today to place your order and bring sophistication to your projects!"));
insert(new Annonce("Wood", "Orchies", "https://yieldpro.com/wp-content/uploads/2020/08/lumber1.jpg", 3, "Experience the unparalleled warmth and charm of Orchies wood – the epitome of quality and elegance. Our carefully curated selection of Orchies wood is renowned for its superior craftsmanship and timeless appeal. Sourced from sustainably managed forests in the scenic city of Orchies, France, our wood exudes a unique character and richness that sets it apart. Whether you're crafting bespoke furniture or enhancing your living space with exquisite wood accents, Orchies wood promises unmatched beauty and durability. Elevate your projects with the finest Orchies wood and indulge in the rustic allure of this picturesque city. Transform your space with Orchies wood – where timeless elegance meets sustainable craftsmanship."));
public void init(Context c){
insert(new Annonce("Wood", "Douai", imageToByteArray(R.drawable.mat1, c),24.99, "High-quality seasoned firewood for sale! Perfect for cozy nights by the fireplace or powering your wood-burning stove. Our carefully selected wood is sourced sustainably, ensuring both quality and environmental responsibility. Available for delivery to your doorstep, our firewood is split and ready to use, saving you time and effort. Whether you're a homeowner, camper, or outdoor enthusiast, our firewood is ideal for all your needs. Stock up now and enjoy the warmth and ambiance of natural wood burning. Don't miss out on this opportunity to elevate your fire experience. Contact us today to place your order!"));
insert(new Annonce("Steel", "Lille", imageToByteArray(R.drawable.mat2, c), 18.9, "Premium steel available for sale! Engineered for strength and durability, our high-grade steel is suitable for a wide range of applications. Whether you're a contractor, builder, or DIY enthusiast, our steel products are perfect for construction projects, fabrication, or repairs. With various sizes and shapes available, we cater to diverse needs and specifications. Our steel undergoes rigorous quality checks to ensure top-notch performance and reliability. Conveniently order online and have it delivered to your location. Upgrade your projects with our superior steel today. Contact us now to place your order and experience the difference!"));
insert(new Annonce("Clay", "Douai", imageToByteArray(R.drawable.mat3, c), 7.88, "Quality clay for sale! Ideal for pottery, sculpting, and crafting projects, our premium-grade clay offers versatility and excellent molding properties. Sourced from reliable suppliers, our clay is carefully processed to ensure consistency and workability. Whether you're a professional artist or a hobbyist, our clay is perfect for bringing your creative visions to life. Available in various quantities, we cater to both small-scale and large-scale projects. Order online for convenient delivery to your doorstep. Elevate your crafting experience with our top-quality clay. Contact us today to place your order and unleash your artistic potential!"));
insert(new Annonce("Metal", "Lyon", imageToByteArray(R.drawable.mat4, c), 12.99, "Discover the perfect metal for your projects! Our high-quality metal is meticulously crafted to meet the demands of various industries and applications. Whether you're in construction, manufacturing, or metalworking, our premium-grade metal offers unparalleled strength, durability, and versatility. From stainless steel to aluminum and everything in between, we provide a wide range of metal options to suit your specific needs. Our metals are sourced from trusted suppliers and undergo rigorous quality checks to ensure superior performance. Conveniently order online and have it delivered to your location. Elevate your projects with our exceptional metal products. Contact us today to place your order and experience the difference!"));
insert(new Annonce("Glass", "Valenciennes", imageToByteArray(R.drawable.mat5, c), 12.0, "Explore the brilliance of our premium glass products! Crafted with precision and quality in mind, our glass offerings are perfect for a variety of applications. Whether you're in need of durable windows for your home, sleek glass tabletops for your office, or intricate glassware for your dining table, we have you covered. Our extensive range includes tempered glass, laminated glass, decorative glass, and more, ensuring we meet your specific requirements. Sourced from trusted manufacturers, our glass products undergo stringent quality control measures to guarantee clarity, strength, and safety. Order online for hassle-free delivery to your desired location. Elevate your spaces with our exquisite glass solutions. Contact us today to place your order and bring sophistication to your projects!"));
insert(new Annonce("Wood", "Orchies", imageToByteArray(R.drawable.mat6, c), 3, "Experience the unparalleled warmth and charm of Orchies wood – the epitome of quality and elegance. Our carefully curated selection of Orchies wood is renowned for its superior craftsmanship and timeless appeal. Sourced from sustainably managed forests in the scenic city of Orchies, France, our wood exudes a unique character and richness that sets it apart. Whether you're crafting bespoke furniture or enhancing your living space with exquisite wood accents, Orchies wood promises unmatched beauty and durability. Elevate your projects with the finest Orchies wood and indulge in the rustic allure of this picturesque city. Transform your space with Orchies wood – where timeless elegance meets sustainable craftsmanship."));
}
//Convert drawable image to byteArray
public byte[] imageToByteArray(int img, Context c) {
// Convert image to Bitmap
Bitmap bitmap = BitmapFactory.decodeResource(c.getResources(), img);
//Convert Bitmap to byte array
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
return stream.toByteArray();
}
public void insert(Annonce ad) {
......@@ -113,7 +130,7 @@ public class DBManager {
do {
String titre = cursor.getString(abs(cursor.getColumnIndex(DBHelper.TITLE)));
String adresse = cursor.getString(abs(cursor.getColumnIndex(DBHelper.ADDRESS)));
String image = cursor.getString(abs(cursor.getColumnIndex(DBHelper.IMAGE)));
byte[] image = cursor.getBlob(abs(cursor.getColumnIndex(DBHelper.IMAGE)));
double prix = cursor.getDouble(abs(cursor.getColumnIndex(DBHelper.PRICE)));
String description = cursor.getString(abs(cursor.getColumnIndex(DBHelper.DESCRIPTION)));
......
......@@ -11,11 +11,11 @@ public class Annonce implements Parcelable {
private String titre;
private String adresse;
private double prix;
private String image;
private byte[] image;
private String description;
// Constructeur
public Annonce(String titre, String adresse, String image, double prix, String description) {
public Annonce(String titre, String adresse, byte[] image, double prix, String description) {
this.titre = titre;
this.adresse = adresse;
this.image = image;
......@@ -37,7 +37,7 @@ public class Annonce implements Parcelable {
public double getPrix(){return prix;}
public String getAdresse(){return adresse;}
public String getImage(){return image;}
public byte[] getImage(){return image;}
public String getDescription(){return description;}
......@@ -53,7 +53,10 @@ public class Annonce implements Parcelable {
parcel.writeString(adresse);
parcel.writeDouble(prix);
parcel.writeString(image);
parcel.writeInt(image.length);
parcel.writeByteArray(image);
parcel.writeString(description);
parcel.writeInt(id);
}
......@@ -70,8 +73,12 @@ public class Annonce implements Parcelable {
private Annonce(Parcel in) {
titre = in.readString();
adresse = in.readString();
prix = in.readDouble();
image = in.readString();
image = new byte[in.readInt()];
in.readByteArray(image);
description = in.readString();
id = in.readInt();
}
......
......@@ -3,6 +3,7 @@ package com.example.tpleboncoin.ui.ajout_annonce;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
......@@ -30,6 +31,8 @@ import com.example.tpleboncoin.db.DBManager;
import com.example.tpleboncoin.models.Annonce;
import com.google.android.material.snackbar.Snackbar;
import java.io.ByteArrayOutputStream;
public class AjoutAnnonceFragment extends Fragment {
private FragmentAjoutAnnonceBinding binding;
......@@ -50,11 +53,12 @@ public class AjoutAnnonceFragment extends Fragment {
final EditText adresseAnnonce = binding.adresseAnnonce;
final EditText prixAnnonce = binding.prixAnnonce;
final EditText descriptionAnnonce = binding.descriptionAnnonce;
final ImageView imageAnnonce = binding.imageAnnonce;
final Button boutonCreation = binding.boutonAjoutAnnonce;
// Initialisation de la DB
DBManager dbManager = DBManager.getDBManager(this.getContext());
dbManager.open();
dbManager.open(this.getContext());
boutonCreation.setOnClickListener(new View.OnClickListener() {
......@@ -68,8 +72,14 @@ public class AjoutAnnonceFragment extends Fragment {
return;
}
// On convertit l'image en byte array
Bitmap bitmap = ((BitmapDrawable) imageAnnonce.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageInByte = baos.toByteArray();
// On créé l'objet de la nouvelle annonce
Annonce nouvelleAnnonce = new Annonce(titreAnnonce.getText().toString(), adresseAnnonce.getText().toString(), "", Double.parseDouble(prixAnnonce.getText().toString()), descriptionAnnonce.getText().toString());
Annonce nouvelleAnnonce = new Annonce(titreAnnonce.getText().toString(), adresseAnnonce.getText().toString(), imageInByte, Double.parseDouble(prixAnnonce.getText().toString()), descriptionAnnonce.getText().toString());
//On ajoute la nouvelle annonce à la DB
dbManager.insert(nouvelleAnnonce);
......@@ -83,7 +93,6 @@ public class AjoutAnnonceFragment extends Fragment {
final Button boutonAppareilPhoto = binding.photoBtn;
final Button boutonGalerie = binding.galerieBtn;
final ImageView imageAnnonce = binding.imageAnnonce;
boutonGalerie.setOnClickListener(new View.OnClickListener() {
@Override
......
......@@ -4,10 +4,13 @@ package com.example.tpleboncoin.ui.home;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.activity.result.contract.ActivityResultContracts;
......@@ -17,6 +20,8 @@ import com.example.tpleboncoin.R;
import com.example.tpleboncoin.models.Annonce;
import com.example.tpleboncoin.ui.DetailScreen;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
......@@ -31,6 +36,7 @@ public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView titreTextView;
private final ImageView imageView;
private final TextView adresseTextView;
private final TextView prixTextView;
......@@ -51,6 +57,7 @@ public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
titreTextView = (TextView) v.findViewById(R.id.titre_annonce);
adresseTextView = (TextView) v.findViewById(R.id.adresse_annonce);
prixTextView = (TextView) v.findViewById(R.id.prix_annonce);
imageView = (ImageView) v.findViewById(R.id.image_annonce);
}
public TextView getTitreTextView() {
......@@ -62,6 +69,7 @@ public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
public TextView getPrixTextView() {
return prixTextView;
}
public ImageView getImageView() { return imageView; }
}
/**
......@@ -97,11 +105,16 @@ public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Log.d(TAG, "Element " + position + " set.");
//Byte array to img
InputStream is = new ByteArrayInputStream(mDataSet.get(position).getImage());
Bitmap bmpImage = BitmapFactory.decodeStream(is);
// Get element from dataset at this position and replace the contents of the view
// with that element
viewHolder.getTitreTextView().setText(mDataSet.get(position).getTitre());
viewHolder.getAdresseTextView().setText(mDataSet.get(position).getAdresse());
viewHolder.getPrixTextView().setText(String.format("%,.2f €", mDataSet.get(position).getPrix()));
viewHolder.getImageView().setImageBitmap(bmpImage);
}
// Return the size of dataset (invoked by the layout manager)
......
......@@ -163,7 +163,7 @@ public class HomeFragment extends Fragment {
*/
private void initDataset() {
DBManager dbManager = DBManager.getDBManager(this.getContext());
dbManager.open();
dbManager.open(this.getContext());
// On récupère toutes les annonces de la DB
mDataset = reverseArrayList(dbManager.getAll());
......
......@@ -25,16 +25,17 @@
android:text="Adresse, 59000 Douai" />
<ImageView
android:id="@+id/imageView"
android:id="@+id/image_annonce"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_launcher_background" />
<TextView
android:id="@+id/titre_annonce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView"
android:layout_below="@+id/image_annonce"
android:fontFamily="sans-serif-medium"
android:text="Titre annonce de test"
android:textAppearance="@style/TextAppearance.AppCompat.Medium" />
......
......@@ -23,10 +23,15 @@
android:paddingBottom="8dp">
<ImageView
android:id="@+id/imageView"
android:id="@+id/image_annonce"
android:layout_width="70dp"
android:layout_height="80dp"
android:layout_height="70dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:foregroundGravity="fill_horizontal|fill_vertical"
android:scaleType="centerCrop"
android:src="@drawable/ic_launcher_background"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
......@@ -35,11 +40,10 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
android:fontFamily="sans-serif-medium"
android:text="Titre annonce de test"
android:textAppearance="@style/TextAppearance.AppCompat.Medium"
app:layout_constraintStart_toEndOf="@+id/imageView"
app:layout_constraintStart_toEndOf="@+id/image_annonce"
app:layout_constraintTop_toTopOf="parent" />
<TextView
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment